<template>
    <Tree
        ref="treRef"
        @check-change="handleCheckChange"
        :default-checked-keys="defaultCheckedKeys"
        :show-checkbox="props.showCheckbox"
        :data="tree"
        :height="props.height"
        @changeDeviceType="changeDeviceType"
        @changeTreeType="info"
        :engineering="props.engineering"
    />
</template>

<script lang="ts" setup>
import { ref, nextTick } from 'vue'
import Tree from '../device.vue'
import { getDeviceTree } from '@/api/cs-device-boot/csLedger'
import { useConfig } from '@/stores/config'
import { throttle } from 'lodash'

defineOptions({
    name: 'govern/deviceTree'
})
const props = withDefaults(
    defineProps<{
        showCheckbox?: boolean
        defaultCheckedKeys?: any
        height?: number
        engineering?: boolean
    }>(),
    {
        showCheckbox: false,
        defaultCheckedKeys: [],
        height: 0,
        engineering: false
    }
)
const emit = defineEmits(['init', 'checkChange', 'deviceTypeChange'])
const config = useConfig()
const tree = ref()
const treRef = ref()
const changeDeviceType = (val: any, obj: any) => {
    emit('deviceTypeChange', val, obj)
}

const info = (type?: string) => {
    getDeviceTree({ type: type == '2' ? 'engineering' : '' }).then(res => {
        let arr: any[] = []
        let arr2: any[] = []
        let arr3: any[] = []
        let arr4: any[] = []
        //治理设备
        res.data.map((item: any) => {
            if (type == '2') {
                item.icon = 'el-icon-HomeFilled'
                item.color = config.getColorVal('elementUiPrimary')
                item.children.forEach((item: any) => {
                    item.icon = 'el-icon-List'
                    item.color = config.getColorVal('elementUiPrimary')
                    item.children.forEach((item2: any) => {
                        item2.icon = 'el-icon-Platform'
                        item2.color = config.getColorVal('elementUiPrimary')
                        item2.color =
                            item2.comFlag === 2 ? config.getColorVal('elementUiPrimary') : '#e26257 !important'
                        arr4.push(item2)
                    })
                })
            } else {
                if (item.name == '治理设备') {
                    item.children.forEach((item: any) => {
                        item.icon = 'el-icon-HomeFilled'
                        item.color = config.getColorVal('elementUiPrimary')
                        item.children.forEach((item2: any) => {
                            item2.icon = 'el-icon-List'
                            item2.color = config.getColorVal('elementUiPrimary')
                            item2.children.forEach((item3: any) => {
                                item3.pName = '治理设备'
                                item3.icon = 'el-icon-Platform'
                                item3.level = 2
                                item3.color = config.getColorVal('elementUiPrimary')
                                if (item3.comFlag === 1) {
                                    item3.color = '#e26257 !important'
                                }
                                arr.push(item3)
                            })
                        })
                    })
                } else if (item.name == '便携式设备') {
                    item.children.forEach((item: any) => {
                        item.icon = 'el-icon-Platform'
                        item.color = config.getColorVal('elementUiPrimary')
                        item.color = '#e26257 !important'
                        item.color = item.comFlag === 2 ? config.getColorVal('elementUiPrimary') : '#e26257 !important'
                        // item.disabled =true
                        item.pName = '便携式设备'
                        if (item.type == 'device') {
                            arr2.push(item)
                        }
                        item.children.forEach((item2: any) => {
                            item2.icon = 'el-icon-Platform'
                            item2.color =
                                item2.comFlag === 2 ? config.getColorVal('elementUiPrimary') : '#e26257 !important'
                            item2.pName = '便携式设备'
                            // item2.children.forEach((item3: any) => {
                            //     item3.icon = 'el-icon-Platform'
                            //     item3.color = config.getColorVal('elementUiPrimary')
                            //     if (item3.comFlag === 1) {
                            //         item3.color = '#e26257 !important'
                            //     }
                            //     arr.push(item3)
                            // })
                        })
                    })
                } else if (item.name == '监测设备') {
                    item.children.forEach((item: any) => {
                        item.icon = 'el-icon-HomeFilled'
                        item.color = config.getColorVal('elementUiPrimary')
                        item.children.forEach((item2: any) => {
                            item2.icon = 'el-icon-List'
                            item2.color = config.getColorVal('elementUiPrimary')
                            item2.children.forEach((item3: any) => {
                                item3.pName = '监测设备'
                                item3.icon = 'el-icon-Platform'
                                item3.color = config.getColorVal('elementUiPrimary')
                                if (item3.comFlag === 1) {
                                    item3.color = '#e26257 !important'
                                }
                                arr3.push(item3)
                            })
                        })
                    })
                }
            }
        })
        tree.value = res.data

        nextTick(() => {
            setTimeout(() => {
                if (type == '2') {
                    //初始化选中

                    treRef.value?.treeRef4.setCurrentKey(arr4[0]?.id)
                    // 注册父组件事件
                    emit('init', {
                        level: 2,
                        ...arr4[0]
                    })
                    // changePointType('4', arr4[0])
                    return
                }
                if (arr.length > 0) {
                    treRef.value.treeRef1.setCurrentKey(arr[0]?.id)
                    // 注册父组件事件
                    emit('init', {
                        level: 2,
                        ...arr[0]
                    })
                    return
                } else if (arr2.length > 0) {
                    treRef.value.treeRef2.setCurrentKey(arr2[0]?.id)
                    // 注册父组件事件
                    emit('init', {
                        level: 2,
                        ...arr2[0]
                    })
                    return
                } else if (arr3.length > 0) {
                    console.log('🚀 ~ arr3:', arr3)

                    treRef.value.treeRef3.setCurrentKey(arr3[0].id)
                    // 注册父组件事件
                    emit('init', {
                        level: 2,
                        ...arr3[0]
                    })
                    return
                } else {
                    emit('init')
                    return
                }
            }, 500)
        })
    })
}

onMounted(() => {
    info(props.engineering ? '2' : '1')
})

throttle(
    (data: any, checked: any, indeterminate: any) => {
        emit('checkChange', {
            data,
            checked,
            indeterminate
        })
    },
    300,
    {
        leading: true, // 首次触发立即执行（可选，默认 true）
        trailing: false // 节流结束后是否执行最后一次（可选，默认 true，根据需求调整）
    }
)

const handleCheckChange = (data: any, checked: any, indeterminate: any) => {
    emit('checkChange', {
        data,
        checked,
        indeterminate
    })
}
defineExpose({
    treRef
})
</script>
