<template>
    <Tree ref="treRef" :width="width" :data="tree" :expand-on-click-node="false" default-expand-all
        @checkedNodesChange="handleCheckedNodesChange" />
</template>

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

interface Props {
    template?: boolean
}

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

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

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

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 handleCheckedNodesChange = (nodes: any[]) => emit('checkChange', nodes)

function markPortableNoCheckbox(node: any) {
    node.noCheckbox = true
    node.children?.forEach(markPortableNoCheckbox)
}

async function loadTree() {
    tree.value = []
    const res = await getLineTree()
    const leaves = decorateLineTree(res.data, '1', decorators, { disableParents: false })
    // tree.value = res.data.filter((item: any) => (item.name === '监测设备'||item.name === '便携式设备'))

    const monitorRoot = res.data.find((item: any) => item.name === '监测设备')
    const portableRoot = res.data.find((item: any) => item.name === '便携式设备')

    if (portableRoot) {
        markPortableNoCheckbox(portableRoot)
    }

    tree.value = [monitorRoot, portableRoot].filter(Boolean)
    const node = leaves.monitor[0]
    if (!node) {
        emit('init')
        return
    }

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

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