<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="18px"
            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 - 120px)' }"
                style="overflow: auto"
                ref="treeRef"
                :props="defaultProps"
                highlight-current
                :filter-node-method="filterNode"
                node-key="id"
                show-checkbox
                @check="handleCheckChange"
                :default-checked-keys="defaultCheckedKeys"
                v-bind="$attrs"
                :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>
</template>

<script lang="ts" setup>
import useCurrentInstance from '@/utils/useCurrentInstance'
import { ElMessage, ElTree } from 'element-plus'
import { ref, watch } from 'vue'
import { createTreeFilterNode } from './govern/treeFilterUtils'

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

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

const props = withDefaults(defineProps<Props>(), {
    width: '280px',
    canExpand: true
})

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

const { proxy } = useCurrentInstance()
const menuCollapse = ref(false)
const filterText = ref('')
const defaultProps = { label: 'name', value: 'id' }
const filterNode = createTreeFilterNode()
const checkedNodes = ref<any[]>([])
const defaultCheckedKeys = ref<string[]>([])
const MAX_CHECK = 5
const MONITOR_LEVEL = 3

watch(filterText, val => treeRef.value?.filter(val))

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

const handleCheckChange = (_data: any, checkInfo: any) => {
    const monitoringPointNodes = (checkInfo.checkedNodes as any[]).filter(node => node.level === MONITOR_LEVEL)

    if (monitoringPointNodes.length > MAX_CHECK) {
        const previousCheckedNodes = checkedNodes.value
        const newNodes = monitoringPointNodes.filter(
            node => !previousCheckedNodes.some(prev => prev.id === node.id)
        )

        if (newNodes.length > 0) {
            const allowedNewCount = MAX_CHECK - previousCheckedNodes.length
            if (allowedNewCount > 0) {
                const finalNodes = [...previousCheckedNodes, ...newNodes.slice(0, allowedNewCount)]
                checkedNodes.value = finalNodes
                treeRef.value?.setCheckedNodes(finalNodes)
                emit('checkedNodesChange', finalNodes)
                updateNodeCheckStatus(finalNodes.length)
                if (monitoringPointNodes.length > MAX_CHECK) {
                    ElMessage.warning(`最多只能选择${MAX_CHECK}个监测点`)
                }
                return
            }
        }

        ElMessage.warning(`最多只能选择${MAX_CHECK}个监测点`)
        treeRef.value?.setCheckedNodes(checkedNodes.value)
        return
    }

    checkedNodes.value = monitoringPointNodes
    emit('checkedNodesChange', monitoringPointNodes)
    updateNodeCheckStatus(monitoringPointNodes.length)
}

const updateNodeCheckStatus = (currentCount: number) => {
    if (!treeRef.value) return
    const isMaxSelected = currentCount >= MAX_CHECK
    treeRef.value.store._getAllNodes().forEach((node: any) => {
        if (node.level === MONITOR_LEVEL) {
            node.data.disabled = isMaxSelected && !node.checked
        }
    })
}

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>
