<!-- 设备监控使用折叠面板渲染多个tree -->
<template>
    <div :style="{ width: menuCollapse ? '40px' : props.width }" class="point-tree-root">
        <!-- <Icon
            v-show="menuCollapse"
            @click="onMenuCollapse"
            :name="menuCollapse ? 'el-icon-Expand' : 'el-icon-Fold'"
            :class="menuCollapse ? 'unfold' : ''"
            size="18px"
            class="fold ml10 mt20 menu-collapse"
            style="cursor: pointer"
            v-if="route.path != '/admin/govern/reportCore/statistics/index'"
        /> -->
        <div class="cn-tree" :style="{ opacity: menuCollapse ? 0 : 1, display: menuCollapse ? 'none' : '' }">
            <div class="tree-search mb10">
                <el-input v-model.trim="filterText" placeholder="请输入内容" clearable>
                    <template #prepend>
                        <el-select v-model="treeType" @change="changeTreeType" style="min-width: 75px">
                            <el-option v-for="item in options" :key="item.value" :label="item.label"
                                :value="item.value" />
                        </el-select>
                    </template>
                    <template #prefix>
                        <Icon name="el-icon-Search" style="font-size: 16px" />
                    </template>
                </el-input>
                <!-- <Icon
                    @click="onMenuCollapse"
                    :name="menuCollapse ? 'el-icon-Expand' : 'el-icon-Fold'"
                    :class="menuCollapse ? 'unfold' : ''"
                    size="18px"
                    class="fold ml10 menu-collapse"
                    style="cursor: pointer"
                    v-if="props.canExpand && route.path != '/admin/govern/reportCore/statistics/index'"
                /> -->
            </div>

            <el-collapse :accordion="true" v-model="activeName" class="device-collapse" @change="changeDevice"
                v-if="treeType == '1'" v-loading="loading">
                <el-collapse-item title="治理设备" name="0" v-if="zlDeviceData.length">
                    <div class="collapse-tree-panel collapse-tree-panel--govern">
                        <el-select v-model="process" clearable placeholder="请选择状态" class="mb10">
                            <el-option label="功能调试" value="2" />
                            <el-option label="出厂调试" value="3" />
                            <el-option label="正式投运" value="4" />
                        </el-select>
                        <el-tree ref="treeRef1" :props="defaultProps" highlight-current :filter-node-method="filterNode"
                            node-key="id" v-bind="$attrs" :data="zlDevList" class="collapse-tree"
                            :default-expand-all="false">
                            <template #default="{ node, data: nodeData }">
                                <span class="custom-tree-node">
                                    <Icon :name="nodeData.icon" style="font-size: 16px"
                                        :style="{ color: nodeData.color }" v-if="nodeData.icon" />
                                    <span style="margin-left: 4px">{{ node.label }}</span>
                                </span>
                            </template>
                        </el-tree>
                    </div>
                </el-collapse-item>
                <el-collapse-item title="便携式设备" name="1" v-if="bxsDeviceData.length">
                    <div class="collapse-tree-panel">
                        <el-tree ref="treeRef2" :props="defaultProps" highlight-current :default-expand-all="false"
                            :filter-node-method="filterNode" node-key="id" :data="bxsDeviceData" v-bind="$attrs"
                            class="collapse-tree">
                            <template #default="{ node, data: nodeData }">
                                <span class="custom-tree-node">
                                    <Icon :name="nodeData.icon" style="font-size: 16px"
                                        :style="{ color: nodeData.color }" v-if="nodeData.icon" />
                                    <span style="margin-left: 4px">{{ node.label }}</span>
                                </span>
                            </template>
                        </el-tree>
                    </div>
                </el-collapse-item>
                <el-collapse-item title="监测设备" name="2" v-if="yqfDeviceData.length">
                    <div class="collapse-tree-panel">
                        <el-tree ref="treeRef3" :props="defaultProps" highlight-current :default-expand-all="false"
                            :filter-node-method="filterNode" node-key="id" :data="yqfDeviceData" v-bind="$attrs"
                            class="collapse-tree">
                            <template #default="{ node, data: nodeData }">
                                <span class="custom-tree-node">
                                    <Icon :name="nodeData.icon" style="font-size: 16px"
                                        :style="{ color: nodeData.color }" v-if="nodeData.icon" />
                                    <span style="margin-left: 4px">{{ node.label }}</span>
                                </span>
                            </template>
                        </el-tree>
                    </div>
                </el-collapse-item>
            </el-collapse>
            <div v-if="treeType == '2'" class="engineering-tree-wrap" v-loading="loading">
                <el-tree class="engineering-tree pt10 collapse-tree" ref="treeRef4" :props="defaultProps"
                    highlight-current :filter-node-method="filterNode" node-key="id" v-bind="$attrs" :data="props.data"
                    :default-expand-all="false">
                    <template #default="{ node, data: nodeData }">
                        <span class="custom-tree-node">
                            <Icon :name="nodeData.icon" style="font-size: 16px" :style="{ color: nodeData.color }"
                                v-if="nodeData.icon" />
                            <span style="margin-left: 4px">{{ node.label }}</span>
                        </span>
                    </template>
                </el-tree>
            </div>
        </div>
    </div>
</template>

<script lang="ts" setup>
import useCurrentInstance from '@/utils/useCurrentInstance'
import { ElTree, type CollapseModelValue } from 'element-plus'
import { ref, watch, nextTick } from 'vue'
import { useRoute } from 'vue-router'
import { collectDeviceLeaves } from './govern/lineTreeUtils'

defineOptions({
    name: 'govern/point',
    inheritAttrs: false
})

const emit = defineEmits(['changePointType', 'changeTreeType'])

interface Props {
    width?: string
    canExpand?: boolean
    type?: string
    data?: any[]
    height?: number
}

const props = withDefaults(defineProps<Props>(), {
    width: '100%',
    canExpand: true,
    type: '',
    data: () => [],
    height: 0
})

const route = useRoute()
const { proxy } = useCurrentInstance()

const treeType = ref('2')
const options = [
    { label: '工程', value: '2' },
    { label: '设备', value: '1' },
]

const menuCollapse = ref(false)
const activeName = ref('0')
const filterText = ref('')
const process = ref('')
const loading = ref(false)

const defaultProps = { label: 'name', value: 'id' }

const zlDeviceData = ref<any[]>([])
const zlDevList = ref<any[]>([])
const bxsDeviceData = ref<any[]>([])
const yqfDeviceData = ref<any[]>([])

const treeRef1 = ref<InstanceType<typeof ElTree>>()
const treeRef2 = ref<InstanceType<typeof ElTree>>()
const treeRef3 = ref<InstanceType<typeof ElTree>>()
const treeRef4 = ref<InstanceType<typeof ElTree>>()

defineExpose({ treeRef1, treeRef2, treeRef3, treeRef4 })

function splitTreeData(val: any[]) {
    zlDeviceData.value = []
    bxsDeviceData.value = []
    yqfDeviceData.value = []

    val.forEach(item => {
        if (item.name === '治理设备') {
            zlDeviceData.value = item.children ?? []
        } else if (item.name === '便携式设备') {
            bxsDeviceData.value = item.children ?? []
        } else if (item.name === '监测设备') {
            yqfDeviceData.value = item.children ?? []
        }
    })

    zlDevList.value = filterProcess(JSON.parse(JSON.stringify(zlDeviceData.value)))
}

/** 测点树专用：level=2 按 process 过滤，其余层级保留有子节点或匹配的节点 */
function filterProcess(nodes: any[]): any[] {
    if (!process.value) return nodes

    return nodes
        .map(node => {
            const children = node.children ? filterProcess(node.children) : []

            if (node.level === 2) {
                if (node.process == process.value) {
                    return { ...node, children }
                }
                return null
            }

            if (children.length > 0 || node.process == process.value || !node.children?.length) {
                return { ...node, children }
            }

            return null
        })
        .filter(Boolean)
}

function getActiveTreeRef() {
    if (treeType.value === '2') return treeRef4.value
    if (activeName.value === '0') return treeRef1.value
    if (activeName.value === '1') return treeRef2.value
    return treeRef3.value
}

function resolveActiveName() {
    if (zlDeviceData.value.length) return '0'
    if (bxsDeviceData.value.length) return '1'
    if (yqfDeviceData.value.length) return '2'
    return ''
}

function selectPointPanel(panelName: string, node?: any) {
    if (!node) return
    emit('changePointType', panelName, node)
    nextTick(() => {
        getActiveTreeRef()?.setCurrentKey(node.id)
    })
}

const changeDevice = (val: CollapseModelValue) => {
    if (Array.isArray(val) || val == null || val === '') return
    const panelName = String(val)
    const { govern, portable, monitor } = collectDeviceLeaves(
        zlDevList.value,
        bxsDeviceData.value,
        yqfDeviceData.value
    )

    const panelMap: Record<string, { nodes: any[]; clearOthers: any[][] }> = {
        '0': { nodes: govern, clearOthers: [portable, monitor] },
        '1': { nodes: portable, clearOthers: [govern, monitor] },
        '2': { nodes: monitor, clearOthers: [govern, portable] }
    }

    const panel = panelMap[panelName]
    if (!panel) return

    panel.clearOthers.forEach(list => list.forEach(item => (item.checked = false)))
    selectPointPanel(panelName, panel.nodes[0])
}

const setActiveName = () => {
    activeName.value = resolveActiveName()
    if (activeName.value) {
        nextTick(() => changeDevice(activeName.value))
    }
}

watch(
    () => props.data,
    val => {
        if (!val?.length) return
        splitTreeData(val)
        if (treeType.value === '1') {
            nextTick(() => setActiveName())
        }
    },
    { immediate: true, deep: true }
)

watch(filterText, val => {
    getActiveTreeRef()?.filter(val)
})

watch(process, () => {
    zlDevList.value = filterProcess(JSON.parse(JSON.stringify(zlDeviceData.value)))
    if (activeName.value === '0') {
        nextTick(() => changeDevice(activeName.value))
    }
})

const onMenuCollapse = () => {
    menuCollapse.value = !menuCollapse.value
    proxy.eventBus.emit('cnTreeCollapse', menuCollapse)
}

const filterNode = (value: string, data: any, node: any): boolean => {
    if (!value) return true
    if (!data.name) return false
    return chooseNode(value, data, node)
}

const chooseNode = (value: string, data: any, node: any): boolean => {
    if (data.name.indexOf(value) !== -1) return true

    const level = node.level
    if (level === 1) return false

    let parentData = node.parent
    for (let i = 0; i < level - 1; i++) {
        if (parentData?.data?.name?.indexOf(value) !== -1) return true
        parentData = parentData.parent
    }
    return false
}

const changeTreeType = (val: string) => {
    loading.value = true
    emit('changeTreeType', val)
    if (val === '1') {
        nextTick(() => setActiveName())
    }
    setTimeout(() => {
        loading.value = false
    }, 300)
}
</script>

<style lang="scss" scoped>
:deep(.el-tree-node) {
    white-space: none;
}

.point-tree-root {
    display: flex;
    overflow: hidden;
    height: 100%;
    min-height: 0;
}

.cn-tree {
    flex-shrink: 0;
    display: flex;
    flex-direction: column;
    box-sizing: border-box;
    padding: 10px;
    height: 100%;
    min-height: 0;
    max-height: 100%;
    width: 280px;
    background: #fff;
    overflow: hidden;

    :deep(.el-tree) {
        border: 1px solid var(--el-border-color);
    }

    :deep(.el-tree--highlight-current .el-tree-node.is-current > .el-tree-node__content) {
        background-color: var(--el-color-primary-light-7);
    }

    .tree-search {
        display: flex;
        align-items: center;
        flex-shrink: 0;
    }

    .device-collapse {
        flex: 1;
        min-height: 0;
        overflow: hidden;
        display: flex;
        flex-direction: column;
        border: none;

        :deep(.el-collapse-item) {
            flex-shrink: 0;

            .el-collapse-item__header {
                height: 48px;
                line-height: 48px;
            }

            &.is-active {
                flex: 1;
                min-height: 0;
                display: flex;
                flex-direction: column;
                overflow: hidden;

                .el-collapse-item__wrap {
                    flex: 1;
                    min-height: 0;
                }

                .el-collapse-item__content {
                    display: flex;
                    flex-direction: column;
                    height: 100%;
                    min-height: 0;
                    padding-bottom: 0;
                    box-sizing: border-box;
                }
            }
        }
    }

    .engineering-tree-wrap {
        flex: 1;
        min-height: 0;
        overflow: hidden;
        display: flex;
        flex-direction: column;
    }

    .engineering-tree {
        flex: 1;
        min-height: 0;
        overflow: auto;
    }

    .collapse-tree-panel {
        display: flex;
        flex-direction: column;
        flex: 1;
        min-height: 0;
        height: 100%;
        overflow: hidden;

        &--govern>.el-select {
            flex-shrink: 0;
        }
    }

    .collapse-tree {
        flex: 1;
        min-height: 0;
        overflow: auto;
    }

    .menu-collapse {
        color: var(--el-color-primary);
    }
}

.custom-tree-node {
    display: flex;
    align-items: center;
}

:deep(.el-input-group__prepend) {
    background-color: var(--el-fill-color-blank);
}

</style>
