<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="上级名称">
                    <!-- <el-input v-model="form.pid" placeholder="上级名称" /> -->
                    <el-tree-select
                        v-model="form.pid"
                        :data="dataTree"
                        check-strictly
                        clearable
                        default-expand-all
                        :render-after-expand="false"
                        :props="defaultProps"
                    />
                </el-form-item>
                <el-form-item label="名称" prop="name">
                    <el-input v-model="form.name" placeholder="名称" />
                </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">确认</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 { queryAllAlgorithmLibrary, addAlgorithm } from '@/api/supervision-boot/database/index'
const dialogVisible = ref(false)
const title = ref('')
const emit = defineEmits(['getTree'])
const formRef = ref()
// 注意不要和表单ref的命名冲突
const form = reactive<anyObj>({
    name: '',
    pid: ''
})
const defaultProps = {
    children: 'children',
    label: 'name',
    value: 'id'
}
const rules = {
    name: [{ required: true, message: '角色名称不能为空', trigger: 'blur' }]
}
const dataTree = ref([])
const open = (text: string, data?: anyObj) => {
    getTheTree()
    title.value = text
    dialogVisible.value = true
    if (data) {
        // 表单赋值
        for (let key in form) {
            form[key] = data[key]
        }
    } else {
        // 在此处恢复默认表单
        for (let key in form) {
            form[key] = ''
        }
    }
}
const getTheTree = () => {
    queryAllAlgorithmLibrary().then(res => {
        res.data.forEach((item: any) => {
            item.children.forEach((item2: any) => {
                item2.childrens = item2.children
                item2.children = []
            })
        })
        dataTree.value = res.data
    })
}
const submit = () => {
    formRef.value.validate(async (valid: boolean) => {
        if (valid) {
            addAlgorithm({
                pid: form.pid.length == 0 ? '' : form.pid,
                name: form.name
            }).then(res => {
                ElMessage.success('新增成功')
                emit('getTree')
                dialogVisible.value = false
            })
        }
    })
}

defineExpose({ open })
</script>
