<template>
    <el-dialog draggable class="cn-operate-dialog" v-model="dialogVisible" width="500px" :title="title" @close="cancel">
        <div style="display: flex">
            <el-form :inline="false" :model="form" label-width="auto" :rules="rules" ref="formRef" style="flex: 1">
                <el-form-item class="top" label="上级树" prop="system">
                    <!-- <el-cascader
                        v-model="form.system"
                        :options="customDeptOption"
                        :props="props"
                        clearable
                        filterable
                        placeholder="请选择上级树"
                        style="width: 100%"
                    /> -->
                    <el-select v-model="form.system" placeholder="请选择上级树" style="width: 100%">
                        <el-option
                            v-for="item in customDeptOption"
                            :key="item.id"
                            :label="item.name"
                            :value="item.id"
                        />
                    </el-select>
                </el-form-item>
                <el-form-item class="top" label="树名称" prop="name">
                    <el-input maxlength="32" show-word-limit  v-model="form.name" placeholder="请输入组件名称"></el-input>
                </el-form-item>

                <el-form-item class="top" label="树排序" prop="sort">
                    <el-input maxlength="32" show-word-limit  v-model.number="form.sort" placeholder="请输入排序"></el-input>
                </el-form-item>
            </el-form>
        </div>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="cancel">取消</el-button>
                <el-button type="primary" @click="submit" :loading="loading">确定</el-button>
            </span>
        </template>
    </el-dialog>
</template>
<script lang="ts" setup>
import { ref, inject, onMounted, type Component, defineAsyncComponent, h, markRaw } from 'vue'
import { reactive } from 'vue'
import { ElMessage } from 'element-plus'
import { useDictData } from '@/stores/dictData'
import { getFatherComponent, componentAdd, componentEdit } from '@/api/user-boot/dept'

import { componentTree } from '@/api/user-boot/user'
import { pid } from 'process'
const dictData = useDictData()
const emit = defineEmits(['cancel', 'submit'])
const dialogVisible = ref(false)
const title = ref('')
const formRef = ref()
const loading = ref(false)
// 注意不要和表单ref的命名冲突
const form = ref<anyObj>({
    name: '',
    sort: 100,
    system: '',
    timeKey: '3',
    code: 'base'
})
const props = { label: 'name', value: 'id', checkStrictly: true }
const rules = {
    name: [{ required: true, message: '请输输入树名称', trigger: 'blur' }],
    system: [{ required: true, message: '请先择父组件节点', trigger: 'change' }],

    sort: [{ required: true, message: '请输入排序', trigger: 'blur' }]
}
const customDeptOption: any = ref([])
onMounted(() => {})

const open = (text: string, data?: anyObj) => {
    getFather()
    title.value = text
    dialogVisible.value = true
    if (data) {
        let Data = JSON.parse(JSON.stringify(data))
        form.value.system = Data.systemType//[]
        form.value.name = Data.name
        form.value.sort = Data.sort
        form.value.id = Data.id
    }
}
// 查询父节点
const getFather = () => {
    componentTree().then(res => {
        customDeptOption.value = deletePathNotNull(JSON.parse(JSON.stringify(res.data)))
    })
}

// 递归删除path不为null的数据
function deletePathNotNull(data: any) {
    // 若为数组，遍历处理每个元素
    if (Array.isArray(data)) {
        const filtered = []
        for (let item of data) {
            // 递归处理子节点
            if (item.children && item.children.length > 0) {
                item.children = deletePathNotNull(item.children)
            }
            // 仅保留path为null或空字符串的节点
            if (item.path === null || item.path === '') {
                filtered.push(item)
            }
        }
        return filtered
    }
    // 若为单个对象（递归子节点时用）
    if (typeof data === 'object' && data !== null) {
        if (data.children && data.children.length > 0) {
            data.children = deletePathNotNull(data.children)
        }
        return data.path === null || data.path === '' ? data : null
    }
    return data
}
const submit = () => {
    formRef.value.validate(async (valid: boolean) => {
        if (valid) {
            loading.value = true
            if (title.value == '新增树') {
                await componentAdd({
                    ...form.value,
                    systemType: form.value.system,
                    pid:  '0' //form.value.system.length == 1 ? '0' : form.value.system
                }).then(res => {
                    ElMessage.success('新增成功!')
                    emit('submit')
                    cancel()
                }).finally(() => {
                    loading.value = false
                })
            } else {
                await componentEdit({
                    ...form.value,
                    systemType: form.value.system,
                    pid: '0'//form.value.system.length == 1 ? '0' : form.value.system
                }).then(res => {
                    ElMessage.success('修改成功!')
                    emit('submit')
                    cancel()
                }).finally(() => {
                    loading.value = false
                })
            }
        }
    })
}

const cancel = () => {
    emit('cancel')
    dialogVisible.value = false
}
defineExpose({ open })
</script>
