<script lang='ts' setup>
import { computed, onMounted, nextTick } from 'vue'
import { criteriaForPeopleList } from '@/api/hr/org/type'
import request from '@/utils/request';
import { useAttrs } from 'vue'
const attrs = useAttrs()

const props = withDefaults(
    defineProps<{
        modelValue?: string
        disabled?: boolean
        orgAndManTree?: any;
        data?: any;
    }>(),
    {}
)


const emits = defineEmits<{
    (e: 'update:modelValue', value: string): void
}>()


const value = ref([])
const treeData = ref([]) // 存储懒加载的数据
const isDataLoaded = ref(false) // 标记数据是否已加载
const loading = ref(false) // 是否正在加载
const treeSelectRef = ref() // 树选择器引用

watch(value, (newValue) => {
    if (newValue.length > 0) {
        let str = ""
        let userAry = new Array
        
        newValue.forEach(item => {
            userAry.push(item)
        })
        str = userAry.join(',')
        emits('update:modelValue', str)
    } else {
        let str = ""
        emits('update:modelValue', str)
    }
}, { deep: true })

function parseStringToArray(str: string) {
    try {
        const result = JSON.parse(str);
        if (Array.isArray(result)) {
            return result;
        } else {
            return [];
        }
    } catch (error) {
        return [];
    }
}

onBeforeMount(() => {
    setTimeout(() => {
        value.value = parseStringToArray(props.modelValue)
    }, 500)
})

// 加载完整数据的函数
const loadFullData = async () => {
    if (isDataLoaded.value) return treeData.value;
    
    loading.value = true;
    
    try {
        // 模拟数据加载过程
        await new Promise(resolve => setTimeout(resolve, 800));
        
        const result = await checkorgAndManTree1();
        treeData.value = result;
        isDataLoaded.value = true;
        return result;
    } catch (error) {
        console.error('加载组织数据失败:', error);
        return [];
    } finally {
        loading.value = false;
    }
}

// 点击树选择器时的处理
const handleTreeSelectClick = async () => {
    if (!isDataLoaded.value && !loading.value) {
        await loadFullData();
    }
}

// 下拉框显示状态变化时的处理
const handleVisibleChange = async (visible: boolean) => {
    if (visible && !isDataLoaded.value && !loading.value) {
        await loadFullData();
    }
}

const resData = computed(() => {
    return treeData.value;
})

function checkorgAndManTree1() {
    return new Promise((resolve) => {
        const check = () => {
            let result = []
            let i = 0
            props.orgAndManTree.forEach((element: any) => {
                if (element.hasOwnProperty('tree') && hasNodesInTree(element.tree)) {
                    i++
                }
            });
            if (i == props.orgAndManTree.length) {
                props.orgAndManTree.forEach((item: any) => {
                    if (props.data.name == item.name) {
                        console.log(item.tree)
                        result = item.tree
                    }
                });
                resolve(result)
            } else {
                setTimeout(check, 100)
            }
        }
        check()
    })
}

/**
 * 判断树形结构是否存在节点
 */
function hasNodesInTree(tree) {
    if (!Array.isArray(tree)) {
        return false;
    }

    function checkNode(node) {
        if (node == null) {
            return false;
        }
        return true;
    }

    for (const node of tree) {
        if (checkNode(node)) {
            return true;
        }
        if (Array.isArray(node?.children) && hasNodesInTree(node.children)) {
            return true;
        }
    }

    return false;
}

</script>
<template>


    <div class="tree-select-wrapper" v-if="props.types != 3">
        <el-tree-select 
            ref="treeSelectRef"
            node-key="number" 
            v-model="value" 
            :data="resData" 
            multiple 
            :render-after-expand="false"
            show-checkbox 
            clearable 
            collapse-tags 
            collapse-tags-tooltip 
            :max-collapse-tags="4" 
            filterable
            @click="handleTreeSelectClick"
            @visible-change="handleVisibleChange"
            :disabled="props.disabled"
            :popper-append-to-body="false"
        >
            <!-- 自定义空状态 -->
            <template #empty>
                <div class="custom-empty">
                    {{ loading ? '正在加载' : '无数据' }}
                </div>
            </template>
        </el-tree-select>
    </div>
</template>
<style lang='scss' scoped>

.tree-select-wrapper {
    position: relative;
    min-height: 40px;
    width: 100%;
}

.wordColor {
    color: #000000;
}

.el-tree-node__expand-icon {
    color: var(--el-tree-expand-icon-color);
    cursor: pointer;
    font-size: 18px;
    transform: rotate(0deg);
    transition: transform var(--el-transition-duration) ease-in-out;
}

.el-tree {
    --el-tree-node-content-height: 30px;
    --el-tree-node-hover-bg-color: var(--el-fill-color-light);
    --el-tree-text-color: var(--el-text-color-regular);
    --el-tree-expand-icon-color: var(--el-text-color-placeholder);
    background: var(--el-fill-color-blank);
    color: var(--el-tree-text-color);
    cursor: default;
    font-size: var(--el-font-size-base);
    position: relative;
}

.el-tree-select__popper .el-tree-node__expand-icon {
    margin-left: 7px;
    margin-right: 7px;
}

/* 自定义空状态样式 */
.custom-empty {
    padding: 10px;
    text-align: center;
    color: #909399;
    font-size: 14px;
}

</style>
