<template>
    <el-dialog draggable class="cn-operate-dialog" v-model="dialogVisible" :title="title" :before-close="handleClose"
        width="1200px">
        <el-scrollbar>
            <el-form :inline="false" :model="form" class="form-two" label-width="auto" :rules="rules" ref="formRef">
                <el-form-item label="事件名称" prop="name">
                    <el-input v-model="form.name" placeholder="请输入事件名称" maxlength="32" type="textarea" show-word-limit :autosize="{ minRows: 2, maxRows: 4 }" @input="handleInput('name', $event)"/>
                </el-form-item>
                <!-- <el-form-item label="发生事件" prop="type">
                    <el-input
                        v-model="form.type"
                        placeholder="请输入治理效果"
                        :autosize="{ minRows: 2, maxRows: 4 }"
                        type="textarea"
                    />
                </el-form-item> -->
                <el-form-item label="发生地点" prop="location">
                    <el-input v-model="form.location" placeholder="请输入发生地点" :autosize="{ minRows: 2, maxRows: 4 }"
                        type="textarea" maxlength="32" show-word-limit @input="handleInput('location', $event)"/>
                </el-form-item>

                <el-form-item label="事件经过" prop="process">
                    <el-input v-model="form.process" placeholder="请输入事件经过" :autosize="{ minRows: 2, maxRows: 4 }"
                        type="textarea" maxlength="32" show-word-limit @input="handleInput('process', $event)"/>
                </el-form-item>
                <el-form-item label="处理措施" prop="measures">
                    <el-input v-model="form.measures" placeholder="请输入处理措施" :autosize="{ minRows: 2, maxRows: 4 }"
                        type="textarea" maxlength="32" show-word-limit @input="handleInput('measures', $event)"/>
                </el-form-item>
                <el-form-item label="治理效果" prop="effect">
                    <el-input v-model="form.effect" placeholder="请输入治理效果" :autosize="{ minRows: 2, maxRows: 4 }"
                        type="textarea" maxlength="32" show-word-limit @input="handleInput('effect', $event)"/>
                </el-form-item>
                <el-form-item label="附件">
                    <el-upload v-model:file-list="fileList" action="" :auto-upload="false" multiple>
                        <el-button type="primary">上传</el-button>
                    </el-upload>
                </el-form-item>
            </el-form>

            <!-- <div style="display: flex">
                <div style="width: 80px">事件简介</div>
                <editor v-model="form.summary" />
            </div> -->
            <div style="display: flex; align-items: start;">
                <div style="width: 80px; flex-shrink: 0;">事件简介</div>
                <editor v-model="form.summary" />
            </div>
        </el-scrollbar>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="handleClose">取消</el-button>
                <el-button type="primary" @click="submit" :loading="loading">确认</el-button>
            </span>
        </template>
    </el-dialog>
</template>
<script lang="ts" setup>
import { ref, inject } from 'vue'
import { reactive } from 'vue'
import { ElMessage } from 'element-plus'
import TableStore from '@/utils/tableStore' // 若不是列表页面弹框可删除
import editor from '@/components/wangEditor/index.vue'
import { uploadFile, getFileNameAndFilePath } from '@/api/system-boot/file'
import { libcaseAdd, updateCaseLibrary } from '@/api/supervision-boot/database/index'
const emit = defineEmits(['onSubmit'])
const dialogVisible = ref(false)
const title = ref('')
const formRef = ref()
const loading = ref(false)
const fileList: any = ref([])
// 注意不要和表单ref的命名冲突
const form = reactive<anyObj>({
    // type: '',
    name: '',
    location: '',
    process: '',
    measures: '',
    summary: '',
    caseUrl: '',
    effect: '',
    url: ''
})

const rules = {
    name: [{ required: true, message: '请输入事件名称', trigger: 'blur' }],
    // type: [{ required: true, message: '角色编码不能为空', trigger: 'blur' }],
    location: [{ required: true, message: '请输入发生地点', trigger: 'blur' }],
    process: [{ required: true, message: '请输入事件经过', trigger: 'blur' }],
    measures: [{ required: true, message: '请输入处理措施', trigger: 'blur' }],
    effect: [{ required: true, message: '请输入治理效果', trigger: 'blur' }]
}

const open = (text: string, data?: anyObj) => {
    title.value = text
    dialogVisible.value = true
    if (data) {
        fileList.value = []
        // 表单赋值
        for (let key in form) {
            form[key] = data[key]
        }
        form.id = data.id
        if (data.url.length > 0) {
            data.url.split(',').forEach((item: string) => {
                getFileNameAndFilePath({ filePath: item }).then(res => {
                    fileList.value.push({
                        name: res.data.fileName,
                        url: res.data.name
                    })
                })
            })
        }
    } else {
        // 在此处恢复默认表单
        for (let key in form) {
            form[key] = ''
        }
    }
}
const submit = async () => {
    loading.value = true
    await  formRef.value.validate(async (valid: boolean) => {
        if (valid) {
            if (fileList.value.length > 0) {
                const promises = fileList.value.map(async item => {
                    if (item.raw) {
                        return new Promise((resolve, reject) => {
                            uploadFile(item.raw, '/supervision/')
                                .then((res: any) => {
                                    resolve(res.data.name)
                                })
                                .catch(reject)
                        })
                    } else {
                        return item.url
                    }
                })

                try {
                    const fileNames = await Promise.all(promises)
                    form.url = fileNames.join(',') + ''
                } catch (error) {
                    console.error('上传文件出错', error)
                    return
                }
            } else {
                form.url = ''
            }

            await setTimeout(async () => {
                if (title.value === '新增案例') {
                    await libcaseAdd(form).then(res => {
                        ElMessage.success(title.value + '成功!')
                        handleClose()
                    })
                } else {
                    await updateCaseLibrary(form).then(res => {
                        ElMessage.success(title.value + '成功!')

                        handleClose()
                    })
                }
            }, 100)
        }
    })
    await setTimeout(() => {
        loading.value = false
    }, 1000)
}

const handleClose = () => {
    fileList.value = []
    emit('onSubmit')
    dialogVisible.value = false
}


const handleInput = (field: string, value: string) => {
    // 过滤空格
    const filteredValue = value.replace(/\s/g, '')
    if (filteredValue !== value) {
        form[field] = filteredValue
    }
}

defineExpose({ open })
</script>
<style lang="scss" scoped>
:deep(.el-upload-list__item-info) {
    width: 300px !important;
}
</style>
