<template>
    <Tree
        ref="treRef"
        
        :width="width"
        :showPush="props.showPush"
        :expand-on-click-node="false"
        :data="tree"
        @changePointType="changePointType"
        @onAdd="onAdd"
    />
</template>

<script lang="ts" setup>
import { ref } from 'vue'
import Tree from '../index.vue'
import { getCldTree } 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 { decorateCloudTree } from './deviceTreeUtils'
import { bootstrapWithTemplate, selectTreeNode } from './treeCommonUtils'

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

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

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

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 getCldTree()
    const leaves = decorateCloudTree(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, level: selected.level ?? 3 })
            changePointType('4', selected)
        }
    })
}

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

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