<template>
    <Tree
        ref="treRef"
        @checkTreeNodeChange="handleCheckChange"
        :default-checked-keys="defaultCheckedKeys"
        :show-checkbox="props.showCheckbox"
        :data="tree"
    />
</template>

<script lang="ts" setup>
import { ref } from 'vue'
import Tree from '../index.vue'
import { getDeviceTree } from '@/api/cs-device-boot/csLedger'
import { useConfig } from '@/stores/config'
import { createLineTreeDecorators } from './lineTreeUtils'
import { decorateDeviceInfoTree } from './deviceTreeUtils'
import { selectTreeNode } from './treeCommonUtils'

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

const props = withDefaults(
    defineProps<{
        showCheckbox?: boolean
        defaultCheckedKeys?: any[]
    }>(),
    {
        showCheckbox: false,
        defaultCheckedKeys: () => []
    }
)

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

const config = useConfig()
const tree = ref<any[]>([])
const treRef = ref<InstanceType<typeof Tree>>()
const decorators = createLineTreeDecorators(() => config.getColorVal('elementUiPrimary'))

async function initTree(list: any[]) {
    const leaves = decorateDeviceInfoTree(list, decorators)
    tree.value = list

    const node = leaves[0]
    if (!node) {
        emit('init')
        return
    }

    await selectTreeNode(treRef.value, node, {
        onSelect: selected => emit('init', { level: 2, ...selected })
    })
}

getDeviceTree().then(res => initTree(res.data))

const getTreeList = (list: any[]) => initTree(list)

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

defineExpose({ getTreeList })
</script>
