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

<script lang="ts" setup>
import { ref, onMounted, onBeforeUnmount } from 'vue'
import { debounce } from 'lodash-es'
import Tree from '../device.vue'
import { getDeviceTree } from '@/api/cs-device-boot/csLedger'
import { useConfig } from '@/stores/config'
import { waitForTreeRef, type TreeRefKey } from './lineTreeUtils'
import { createLineTreeDecorators } from './lineTreeUtils'
import { decorateDeviceTree } from './deviceTreeUtils'
import type { LineTreeLeaves } from './lineTreeUtils'

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<any[]>([])
const treRef = ref<InstanceType<typeof Tree>>()
const decorators = createLineTreeDecorators(() => config.getColorVal('elementUiPrimary'))

const changeDeviceType = debounce((val: any, obj: any) => {
    emit('deviceTypeChange', val, obj)
}, 300)

onBeforeUnmount(() => changeDeviceType.cancel())

async function selectInitialNode(type: string | undefined, leaves: LineTreeLeaves) {
    const candidates: { refKey: TreeRefKey; list: any[]; level: number }[] =
        type === '2'
            ? [{ refKey: 'treeRef4', list: leaves.engineering, level: 2 }]
            : [
                { 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 })
        return
    }
    emit('init')
}

const loadTree = (type?: string) => {
    getDeviceTree({ type: type === '2' ? 'engineering' : '' }).then(res => {
        const leaves = decorateDeviceTree(res.data, type, decorators)
        tree.value = res.data
        selectInitialNode(type, leaves)
    })
}

onMounted(() => loadTree( '2' ))

const handleCheckChange =
    (data: any, checked: any, indeterminate: any) => {
        emit('checkChange', { data, checked, indeterminate })
    }

defineExpose({ treRef })
</script>
