<template>
    <Tree
        ref="treRef"
        :width="width"
        :showPush="props.showPush"
        :data="tree"
        default-expand-all
        @changePointType="changePointType"
        @onAdd="onAdd"
    />
</template>

<script lang="ts" setup>
import { ref, nextTick, onMounted, defineProps } from 'vue'
import Tree from '../index.vue'
import { getLineTree, objTree } from '@/api/cs-device-boot/csLedger'
import { useConfig } from '@/stores/config'
import { querySysExcel } from '@/api/harmonic-boot/luckyexcel'
import { useDictData } from '@/stores/dictData'

interface Props {
    template?: boolean
    showPush?: boolean
}
const props = withDefaults(defineProps<Props>(), {
    template: false,
    showPush: false
})
defineOptions({
    name: 'govern/deviceTree'
})

const emit = defineEmits(['init', 'checkChange', 'pointTypeChange', 'Policy', 'onAdd'])
const config = useConfig()
const tree = ref()
const dictData = useDictData()
const treRef = ref()
const width = ref('')

const info = (selectedNodeId?: string) => {
    tree.value = []
    let arr1: any[] = []
    objTree().then(res => {
        try {
            res.data.map((item: any) => {
                item.icon = 'el-icon-HomeFilled'
                item.level = 1
                item.color = config.getColorVal('elementUiPrimary')
                item.children.forEach((item: any) => {
                    item.icon = 'el-icon-List'
                    item.level = 2
                    item.color = config.getColorVal('elementUiPrimary')
                    item.children.forEach((item2: any) => {
                        arr1.push(item2)
                        item2.icon = 'el-icon-Platform'
                        item2.level = 3
                        item2.color = config.getColorVal('elementUiPrimary')
                    })
                })
            })
            tree.value = res.data
            nextTick(() => {
                if (arr1.length) {
                    //初始化选中
                    treRef.value.treeRef.setCurrentKey(arr1[0].id)
                    // 注册父组件事件
                    emit('init', arr1[0])
                    return
                } else {
                    emit('init')
                    return
                }
            })
        } catch (error) {
            console.error('Error in processing getCldTree response:', error)
        }
    })
}

const changePointType = (val: any, obj: any) => {
    emit('pointTypeChange', val, obj)
}

const onAdd = () => {
    emit('onAdd')
}
if (props.template) {
    querySysExcel({ id: dictData.state.area[0]?.id })
        .then((res: any) => {
            emit('Policy', res.data)
            info()
        })
        .catch(err => {
            info()
        })
} else {
    info()
}

// 暴露 info 方法给父组件调用
defineExpose({
    info
})

onMounted(() => {})
</script>
