<template>
    <el-dialog
        draggable
        :title="title"
        v-model.trim="dialogVisible"
        width="500px"
        :before-close="handleClose"
        :close-on-click-modal="false"
    >
        <el-form ref="formRef" :rules="rules" :model="form" label-width="90px" class="form-one">
            <el-form-item label="项目名称:" prop="name">
                <el-input
                    maxlength="32"
                    show-word-limit
                    v-model.trim="form.name"
                    placeholder="请输入项目名称"
                ></el-input>
            </el-form-item>
            <el-form-item label="是否全局:" class="top" v-if="hasAdmin">
                <el-switch
                    v-model="form.scope"
                    inline-prompt
                    width="60px"
                    :active-value="1"
                    :inactive-value="0"
                    active-text="是  "
                    inactive-text="否  "
                />
            </el-form-item>
            <el-form-item label="工程项目:" class="top" prop="projectIds" v-if="!hasAdmin || form.scope == 0">
                <el-tree-select
                    v-model.trim="form.projectIds"
                    default-expand-all
                    show-checkbox
                    node-key="id"
                    :props="defaultProps"
                    multiple
                    :data="Engineering"
                    collapse-tags
                    style="width: 100%"
                />
            </el-form-item>
            <el-form-item label="项目排序:" prop="orderBy">
                <el-input maxlength="32" show-word-limit-number v-model.number="form.orderBy" style="width: 100%" />
            </el-form-item>

            <el-form-item label="备注:" class="top">
                <el-input
                    maxlength="300"
                    show-word-limit
                    type="textarea"
                    :rows="2"
                    placeholder="请输入内容"
                    v-model.trim="form.remark"
                ></el-input>
            </el-form-item>
        </el-form>

        <template #footer>
            <span class="dialog-footer">
                <el-button @click="dialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="addFn">确定</el-button>
            </span>
        </template>
    </el-dialog>
</template>
<script setup lang="ts">
import { ref, reactive } from 'vue'
import { deviceTree, add, audit, getztProjectTree } from '@/api/cs-harmonic-boot/mxgraph'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useAdminInfo } from '@/stores/adminInfo'
const adminInfo = useAdminInfo()
const hasAdmin = adminInfo.roleCode.some(item => item.includes('operation_manager') || item.includes('root'))
const title = ref('')
const formRef = ref()
const Engineering = ref([])
const dialogVisible = ref(false)
const emit = defineEmits(['submit'])
const defaultProps = {
    children: 'children',
    value: 'id',
    label: 'name',
    multiple: true,
    expandTrigger: 'hover' as const
}
const form: any = reactive({
    name: '',
    projectIds: [],
    scope: 1,
    orderBy: 100,
    remark: ''
})
const rules = {
    name: [{ required: true, message: '请输入项目名称', trigger: 'blur' }],
    projectIds: [{ required: true, message: '请选择工程项目', trigger: 'change' }],
    orderBy: [{ required: true, message: '请输入排序', trigger: 'blur' }]
}
const addFn = () => {
    console.log('🚀 ~ add ~ form:', form)

    formRef.value.validate((valid: boolean) => {
        if (valid) {
            if (title.value == '新增项目') {
                add({ ...form, projectIds: form.scope == 1 ? ['WIRELESS_PROJECT_ID'] : form.projectIds }).then(
                    (res: any) => {
                        ElMessage.success('新增项目成功!')
                        dialogVisible.value = false
                        emit('submit')
                    }
                )
            } else {
                audit({ ...form, projectIds: form.scope == 1 ? ['WIRELESS_PROJECT_ID'] : form.projectIds }).then(
                    (res: any) => {
                        ElMessage.success('修改项目成功!')
                        dialogVisible.value = false
                        emit('submit')
                    }
                )
            }
        }
    })
}
const handleTree = (data: any) => {
    if (data && data.length != 0) {
        data.map((item: any) => {
            if (item.level != 2) {
                item.disabled = true
            } else {
                item.disabled = false
            }
        })
    }
}
const open = ref((row: any) => {
    formRef.value?.resetFields()
    // deviceTree({}).then((res: any) => {
    //     res.data.forEach((item: any) => {
    //         item.children.forEach((child: any) => {
    //             child.children = []
    //         })
    //     })
    //     Engineering.value = res.data
    // })
    getztProjectTree().then((res: any) => {
        res.data.forEach((item: any, index: any) => {
            if (!item.children || item.children.length == 0) {
                res.data.splice(index, 1)
                return
            }
            item.newList = []
            item.children.forEach((vv: any, vvs: any) => {
                vv.children.forEach((ss: any, ssIndex: any) => {
                    if (ss.level == 1) {
                        item.newList.push(ss)
                    }
                })
            })
            item.disabled = true
            if (item.children && item.children.length != 0) {
                item.children.forEach((vv: any, vvs: any) => {
                    vv.disabled = true
                    if (item.name.includes('治理')) {
                        if (vv.level === 0) {
                            vv.disabled = true
                        } else {
                            vv.disabled = false
                        }
                        // item.children = item.newList
                    }
                    if (item.name.includes('便携式')) {
                        if (vv.level === 1) {
                            vv.disabled = false
                        } else {
                            vv.disabled = true
                        }
                    }
                    if (vv.children && vv.children.length != 0) {
                        vv.children.forEach((kk: any, kks: any) => {
                            if (item.name.includes('便携式') && kk.level === 2) {
                                kk.disabled = true
                                vv.children.splice(kks, 1)
                            }
                            // else {
                            //     kk.disabled = true
                            // }
                        })
                    }
                })
            }
        })
        Engineering.value = removeData(res.data)
    })
    title.value = row.title
    dialogVisible.value = true
    if (row.title == '新增项目') {
        form.name = ''
        form.projectIds = []
        form.orderBy = 100
        form.remark = ''
    } else {
        for (let key in form) {
            form[key] = row.row[key] || ''
        }
        form.id = row.row.id
        form.orderBy = row.row.orderBy - 0
    }
})
const removeData = arr => {
    return arr
        .map(item => {
            if (item.children) {
                item.children = removeData(item.children)
            }
            return item.level <= 1 ? item : {}
        })
        .filter(item => Object.keys(item).length > 0)
}

const handleClose = () => {
    dialogVisible.value = false
}
defineExpose({ open })
</script>
<style lang="scss" scoped></style>
