<template>

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

<script lang="ts" setup>
import { ref } from 'vue'
import Tree from '../index.vue'
import { objTree } from '@/api/cs-device-boot/csLedger'
import { useConfig } from '@/stores/config'
import { querySysExcel } from '@/api/harmonic-boot/luckyexcel'
import { useDictData } from '@/stores/dictData'
import { createLineTreeDecorators } from './lineTreeUtils'
import { decorateObjTree } from './deviceTreeUtils'
import { bootstrapWithTemplate, selectTreeNode } from './treeCommonUtils'

interface Props {
    template?: boolean
    showPush?: boolean
    height?: number
}

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

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

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

const config = useConfig()
const dictData = useDictData()
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)
const onAdd = () => emit('onAdd')

async function loadTree() {
    tree.value = []
    const res = await objTree()
    const leaves = decorateObjTree(res.data, decorators)
    tree.value = res.data

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

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

bootstrapWithTemplate(
    props.template,
    loadTree,
    () => querySysExcel({ id: dictData.state.area[0]?.id }),
    data => emit('Policy', data)
)

defineExpose({ info: loadTree })
</script>
