<template>
    <el-dialog draggable class="cn-operate-dialog" v-model="dialogVisible" :title="title" width="700px">
        <el-scrollbar>
            <el-form :inline="false" :model="form" label-width="auto" :rules="rules" ref="formRef">
                <el-form-item label="模版名称" prop="name">
                    <el-input v-model="form.name" placeholder="请输入模版名称" maxlength="32" show-word-limit   @input="handleInput"/>
                </el-form-item>

                <el-form-item label="模版">
                    <el-upload v-model:file-list="urlList" ref="upload" action="" :limit="1" :auto-upload="false"
                        :on-exceed="handleExceed">
                        <el-button type="primary">上传</el-button>
                    </el-upload>
                </el-form-item>
            </el-form>
        </el-scrollbar>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="dialogVisible = false">取消</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 { libtemplateAdd, updateTemplate } from '@/api/supervision-boot/database/index'
import { uploadFile, getFileNameAndFilePath } from '@/api/system-boot/file'
import { genFileId } from 'element-plus'
import type { UploadInstance, UploadProps, UploadRawFile } from 'element-plus'

const upload = ref<UploadInstance>()
const dialogVisible = ref(false)
const title = ref('')
const emit = defineEmits(['onSubmit'])
const formRef = ref()
// 注意不要和表单ref的命名冲突
const form = reactive<anyObj>({
    name: '',
    url: ''
})
const urlList: any = ref([])
const loading=ref(false)
const defaultProps = {
    children: 'children',
    label: 'name',
    value: 'id'
}
const rules = {
    name: [{ required: true, message: '请输入模版名称', trigger: 'blur' }]
}
const dataTree: any = ref([])
const open = (text: string, data?: anyObj) => {
    title.value = text
    urlList.value = []
    dialogVisible.value = true
    if (data) {
        // 表单赋值
        for (let key in form) {
            form[key] = data[key]
        }
        form.id = data.id

        if (data.url?.length > 0) {
            getFileNameAndFilePath({ filePath: data.url }).then(res => {
                urlList.value.push({
                    name: res.data.fileName,
                    url: res.data.name
                })
            })
        }
    } else {
        // 在此处恢复默认表单
        for (let key in form) {
            form[key] = ''
        }
    }
}
const handleExceed: UploadProps['onExceed'] = (files) => {
    upload.value!.clearFiles()
    const file = files[0] as UploadRawFile
    file.uid = genFileId()
    upload.value!.handleStart(file)
}


const submit = () => {
    loading.value = true
    formRef.value.validate(async (valid: boolean) => {
        if (valid) {
            if (urlList.value.length > 0) {
                const promises = urlList.value.map(async (item: any) => {
                    if (urlList.value[0].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 = ''
            }

            setTimeout(() => {
                if (title.value == '新增模版') {
                    libtemplateAdd({
                        name: form.name,
                        url: form.url
                    }).then(res => {
                        ElMessage.success('新增成功')
                        handleClose()
                        dialogVisible.value = false
                    })
                } else {
                    updateTemplate({
                        name: form.name,
                        url: form.url,
                        id: form.id
                    }).then(res => {
                        ElMessage.success('修改成功')
                        handleClose()
                        dialogVisible.value = false
                    })
                }
            }, 100)
        }
    })
    setTimeout(() => {
        loading.value = false
    }, 1000)
}
const handleClose = () => {
    urlList.value = []
    emit('onSubmit')
    dialogVisible.value = false
}


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

// ... 其余代码保持不变 ...

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