<template>
    <el-dialog draggable class="cn-operate-dialog" v-model="dialogVisible" :title="title" width="500px">
        <el-scrollbar>
            <el-form :inline="false" :model="form" label-width="auto" class="form-one" :rules="rules" ref="formRef">
                <el-form-item label="上级名称" v-if="title == '新增'">

                    <el-select v-model="form.pid" placeholder="请选择上级名称" clearable filterable>
                        <el-option v-for="item in dataTree" :key="item.id" :label="item.name" :value="item.id" />
                    </el-select>
                </el-form-item>
                <el-form-item label="选择修改" v-if="title == '修改'">
                    <el-cascader v-model="cascaderId" :options="dataTree" placeholder="请选择需要修改的内容" filterable
                        checkStrictly :props="cascaderProps" @change="change" />
                </el-form-item>
                <el-form-item label="名称" prop="name">
                    <el-input v-model="form.name" placeholder="名称" maxlength="40" show-word-limit @input="handleInput"/>
                </el-form-item>

                <el-form-item label="标准" v-if="title == '新增' && form.pid?.length > 0">
                    <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-item label="标准" v-if="title == '修改' && cascaderId.length > 1">
                    <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 { queryAll, libstandardAdd, updateStandardLibrary } 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(['getTree', 'onSubmit'])
const formRef = ref()
// 注意不要和表单ref的命名冲突
const form: any = reactive<anyObj>({
    name: '',
    pid: '',
    url: ''
})
const cascaderId = ref([])
const urlList: any = ref([])
const loading = ref(false)
const cascaderProps = {
    children: 'children',
    label: 'name',
    value: 'id',
    checkStrictly: true,


}
const rules = {
    name: [{ required: true, message: '角色名称不能为空', trigger: 'blur' }]
}
const dataTree: any = ref([])
const open = (text: string, data?: anyObj) => {
    getTheTree()
    cascaderId.value = []
    title.value = text
    urlList.value = []
    dialogVisible.value = true
    // if (data) {
    //     // 表单赋值
    //     for (let key in form) {
    //         form[key] = data[key]
    //     }
    //     form.id = data.id
    //     if (form.pid == 0) {
    //         form.pid = ''
    //     }
    //     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 getTheTree = () => {
    queryAll().then(res => {
        dataTree.value = res.data
    })
}
const change = (val: any) => {
    const selectedNode = findNodeById(dataTree.value, val[val.length - 1]);
    urlList.value = []
    if (val.length > 0) {

        form.name = selectedNode.name
        form.id = selectedNode.id
        form.pid = selectedNode.pid
        if (selectedNode.url?.length > 0) {
            getFileNameAndFilePath({ filePath: selectedNode.url }).then(res => {
                urlList.value.push({
                    name: res.data.fileName,
                    url: res.data.name
                })
            })
        }
    } else {
        form.name = ''
        form.id = ''
        form.pid = ''
        form.url = ''
    }
}
const findNodeById = (tree: any[], id: any) => {
    for (const node of tree) {
        if (node.id === id) {
            return node;
        }
        if (node.children) {
            const found: any = findNodeById(node.children, id);
            if (found) {
                return found;
            }
        }
    }
    return null;
};
const submit = async () => {
    loading.value = true
    formRef.value.validate(async (valid: boolean) => {
        if (valid) {
            if (urlList.value.length > 0 && form.pid != '') {
                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 == '新增') {
                    libstandardAdd({
                        pid: form.pid == '' ? null : form.pid,
                        name: form.name,
                        url: form.url
                    }).then(res => {
                        ElMessage.success('新增成功')
                        handleClose()
                        dialogVisible.value = false
                    })
                } else {
                    updateStandardLibrary({
                        pid: form.pid == '' ? null : form.pid,
                        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>
