<template>
    <Tree
        ref="treRef"
        :width="width"
        :data="tree"
        default-expand-all
        @changePointType="changePointType"
        @changeTreeType="loadTree"
    />
</template>

<script lang="ts" setup>
import { ref, nextTick } from 'vue'
import Tree from '../point.vue'
import { getLineTree } from '@/api/cs-device-boot/csLedger'
import { useConfig } from '@/stores/config'
import { querySysExcel } from '@/api/harmonic-boot/luckyexcel'
import {
    createLineTreeDecorators,
    decorateLineTree,
    waitForTreeRef,
    type LineTreeLeaves,
    type TreeRefKey
} from './lineTreeUtils'

interface Props {
    template?: boolean
}

const props = withDefaults(defineProps<Props>(), {
    template: false
})

defineOptions({
    name: 'govern/pointTree'
})

const emit = defineEmits(['init', 'checkChange', 'pointTypeChange', 'Policy'])

const config = useConfig()
const tree = ref<any[]>([])
const treRef = ref<InstanceType<typeof Tree>>()
const width = ref('')

const decorators = createLineTreeDecorators(() => config.getColorVal('elementUiPrimary'))

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

async function selectInitialNode(type: string | undefined, leaves: LineTreeLeaves) {
    const candidates: { refKey: TreeRefKey; list: any[]; level: number }[] =
        type === '2'
            ? [{ refKey: 'treeRef4', list: leaves.engineering, level: 3 }]
            : [
                  { refKey: 'treeRef1', list: leaves.govern, level: 2 },
                  { refKey: 'treeRef2', list: leaves.portable, level: 2 },
                  { refKey: 'treeRef3', list: leaves.monitor, level: 2 }
              ]

    for (const { refKey, list, level } of candidates) {
        const node = list[0]
        if (!node) continue

        const treeInstance = await waitForTreeRef(treRef.value, refKey)
        treeInstance?.setCurrentKey(node.id)
        emit('init', { ...node })

        if (type === '2') {
            changePointType('4', node)
        }
        return
    }

    emit('init')
}

const loadTree = (type?: string) => {
    console.log("🚀 ~ loadTree ~ type:", type)
    tree.value = []
    getLineTree({ type: type === '2' ? 'engineering' : '' }).then(res => {
        const leaves = decorateLineTree(res.data, type, decorators, { disableParents: false })
        tree.value = res.data
        nextTick(() => selectInitialNode(type, leaves))
    })
}

function bootstrap() {
    if (props.template) {
        querySysExcel({})
            .then((res: any) => {
                emit('Policy', res.data)
                loadTree('2')
            })
            .catch(() => loadTree())
    } else {     
      
           
        loadTree('2')
    }
}

bootstrap()

defineExpose({ treRef })
</script>
