<template>
    <div :style="{ width: menuCollapse ? '40px' : props.width }" style='transition: all 0.3s; overflow: hidden;'>
        <Icon v-show='menuCollapse' @click='onMenuCollapse' :name="menuCollapse ? 'el-icon-Expand' : 'el-icon-Fold'"
            :class="menuCollapse ? 'unfold' : ''" size='18' class='fold ml10 mt20 menu-collapse'
            style='cursor: pointer' />
        <div class='cn-tree' :style='{ opacity: menuCollapse ? 0 : 1 }'>
            <div style='display: flex; align-items: center' class='mb10'>
                <el-input maxlength="32"  v-model.trim='filterText' placeholder='请输入内容' clearable>
                    <template #prefix>
                        <Icon name='el-icon-Search' style='font-size: 16px' />
                    </template>
                </el-input>
            </div>
             <el-tree 
                :style="{ height: 'calc(100vh)' }"
                style='overflow: auto;' 
                ref='treeRef' 
                :props='defaultProps' 
                highlight-current 
                :filter-node-method='filterNode' 
                node-key='id' 
                show-checkbox 
                @check="handleCheckChange" 
                @node-click="handleNodeClick"
                :default-checked-keys="defaultCheckedKeys"
                v-bind='$attrs'
                :default-expand-all="false"
                >
                <template #default='{ node, data }'>
                    <span class='custom-tree-node'>
                        <Icon :name='data.icon' style='font-size: 16px' :style='{ color: data.color }'
                            v-if='data.icon' />
                        <span style='margin-left: 4px'>{{ node.label }}</span>
                    </span>
                </template>
            </el-tree>
        </div>
    </div>
</template>

<script lang='ts' setup>
import useCurrentInstance from '@/utils/useCurrentInstance'
import { ElMessage, ElTree } from 'element-plus'
import { emit } from 'process';
import { ref, watch } from 'vue'

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

interface Props {
    width?: string
    canExpand?: boolean
}

const props = withDefaults(defineProps<Props>(), {
    width: '280px',
    canExpand: true
})
const { proxy } = useCurrentInstance()
const menuCollapse = ref(false)
const filterText = ref('')
const defaultProps = {
    label: 'name',
    value: 'id'
}
const emit = defineEmits(['changePointType', 'checkedNodesChange'])

watch(filterText, val => {
    treeRef.value!.filter(val)
    
})
const onMenuCollapse = () => {
    menuCollapse.value = !menuCollapse.value
    proxy.eventBus.emit('cnTreeCollapse', menuCollapse)
}
const filterNode = (value: string, data: any, node: any) => {
    if (!value) return true
    // return data.name.includes(value)
    if (data.name) {

        return chooseNode(value, data, node)
    }
}

// 过滤父节点 / 子节点 (如果输入的参数是父节点且能匹配，则返回该节点以及其下的所有子节点；如果参数是子节点，则返回该节点的父节点。name是中文字符，enName是英文字符.
const chooseNode = (value: string, data: any, node: any) => {

    if (data.name.indexOf(value) !== -1) {
        return true
    }
    const level = node.level
    // 如果传入的节点本身就是一级节点就不用校验了
    if (level === 1) {
        return false
    }
    // 先取当前节点的父节点
    let parentData = node.parent
    // 遍历当前节点的父节点
    let index = 0
    while (index < level - 1) {
        // 如果匹配到直接返回，此处name值是中文字符，enName是英文字符。判断匹配中英文过滤
        if (parentData.data.name.indexOf(value) !== -1) {
            return true
        }
        // 否则的话再往上一层做匹配
        parentData = parentData.parent
        index++
    }
    // 没匹配到返回false
    return false
}


// 处理节点点击事件
const handleNodeClick = (data: any, node: any, event: any) => {
 
}

// 存储所有勾选的节点
const checkedNodes = ref<any[]>([])
const defaultCheckedKeys = ref<string[]>([])

// 处理节点勾选变化
const handleCheckChange = (data: any, checkInfo: any) => {
    const { checkedNodes: nodes } = checkInfo
    // 过滤出监测点层级(level=3)的节点
    const monitoringPointNodes = nodes.filter((node: any) => {
        return node.level === 3 
    })
    
    
    // 限制最多只能勾选5个监测点
    if (monitoringPointNodes.length > 5) {
        // 获取之前选中的节点
        const previousCheckedNodes = checkedNodes.value || []
        
        // 计算新增的节点
        const newNodes = monitoringPointNodes.filter(
            (node: any) => !previousCheckedNodes.some((prev: any) => prev.id === node.id)
        )
        
        // 如果是从父级勾选导致超过限制，保留前几个直到达到限制数量
        if (newNodes.length > 0) {
            const allowedNewCount = 5 - previousCheckedNodes.length
            if (allowedNewCount > 0) {
                // 允许添加allowedNewCount个新节点
                const allowedNewNodes = newNodes.slice(0, allowedNewCount)
                const finalNodes = [...previousCheckedNodes, ...allowedNewNodes]
                
                checkedNodes.value = finalNodes
                
                // 设置树的勾选状态为正确的节点
                treeRef.value?.setCheckedNodes(finalNodes)
                
                // 将勾选的监测点节点暴露出去
                emit('checkedNodesChange', finalNodes)
                
                // 更新节点的可勾选状态
                updateNodeCheckStatus(finalNodes.length)
                
                // 只有在真正超过5个时才提示警告
                if (monitoringPointNodes.length > 5) {
                    ElMessage.warning('最多只能选择5个监测点')
                }
                return
            }
        }
        
        // 其他情况回滚到之前的状态
        ElMessage.warning('最多只能选择5个监测点')
        treeRef.value?.setCheckedNodes(checkedNodes.value)
        return
    }
    
    checkedNodes.value = monitoringPointNodes
    
    // 将勾选的监测点节点暴露出去
    emit('checkedNodesChange', monitoringPointNodes)
    
    // 更新节点的可勾选状态
    updateNodeCheckStatus(monitoringPointNodes.length)
}
// 处理节点勾选变化
const handleCheckChange2 = (data: any, checkInfo: any) => {
    const { checkedNodes: nodes } = checkInfo
    // 过滤出监测点层级(level=3)的节点
    const monitoringPointNodes = nodes.filter((node: any) => {
        // 监测点节点通常具有 comFlag 属性或其他标识
        return node.level === 3 
    })
       // 限制最多只能勾选5个监测点
    if (monitoringPointNodes.length > 5) {
        ElMessage.warning('最多只能选择5个监测点')
        // 保持之前勾选的状态
        treeRef.value?.setCheckedNodes(checkedNodes.value)
        return
    }
    
    checkedNodes.value = monitoringPointNodes
    
    // 将勾选的监测点节点暴露出去
    emit('checkedNodesChange', monitoringPointNodes)
    
    // 更新节点的可勾选状态
    updateNodeCheckStatus(monitoringPointNodes.length)
}


// 更新节点的可勾选状态
const updateNodeCheckStatus = (currentCount: number) => {
    if (!treeRef.value) return
    
    // 如果已经选了5个，则禁用其他未选中的监测点节点
    const isMaxSelected = currentCount >= 5
    
    // 获取所有节点并更新状态
    const allNodes = treeRef.value.store._getAllNodes()
    allNodes.forEach((node: any) => {
        if (node.level === 3) { // 监测点层级
            
            // 如果已达到最大数量且该节点未被选中，则禁用勾选
            if (isMaxSelected && !node.data.checked) {
                node.data.disabled = true
            } else {
                node.data.disabled = false
            }
        }
    })
}

const treeRef = ref<InstanceType<typeof ElTree>>()
defineExpose({ treeRef })
</script>


<style lang='scss' scoped>
.cn-tree {
    flex-shrink: 0;
    display: flex;
    flex-direction: column;
    box-sizing: border-box;
    padding: 10px;
    height: 100%;
    width: 100%;

    :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);
    }

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

.custom-tree-node {
    display: flex;
    align-items: center;
}
</style>
