<template>
    <Tree
        ref="treRef"
        :width="width"
        :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 { lineTree } from '@/api/cs-device-boot/csLedger'
import { useConfig } from '@/stores/config'
import { querySysExcel } from '@/api/harmonic-boot/luckyexcel'
import { createLineTreeDecorators } from './lineTreeUtils'
import { decorateLedgerLineTree, resolveMonitorRoot } from './deviceTreeUtils'
import { bootstrapWithTemplate, findNodeById, selectTreeNode } from './treeCommonUtils'

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

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

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

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

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)
const onAdd = () => emit('onAdd')

async function loadTree(selectedNodeId?: string) {
    tree.value = []
    const res = await lineTree()
    const rootData = resolveMonitorRoot(res.data)
    const leaves = decorateLedgerLineTree(rootData, decorators)
    tree.value = rootData ? [rootData] : []

    if (!leaves.length) {
        emit('init')
        return
    }

    const targetNode = selectedNodeId
        ? findNodeById(tree.value, selectedNodeId) ?? leaves[0]
        : leaves[0]

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

bootstrapWithTemplate(
    props.template,
    () => loadTree(),
    () => querySysExcel({}),
    data => emit('Policy', data)
)

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