<template>
    <div>
        <!-- <pro-input :formItemProps="{ label: '用途:', prop: 'use' }" v-model:value="useYn" placeholder="请输入"
            :allowClear="true">
        </pro-input> -->

        <a-select ref="selectRef" v-model:value="selectedDisplayValue" :open="isDropdownOpen" @click="handleSelectClick"
            placeholder="请选择" :allowClear="true" @clear="handleClear" style="width: 500px">
            <template #dropdownRender>
                <div ref="dropdownRef" class="dropdown-content">
                    <!-- 搜索框 -->
                    <a-input v-model:value="searchValue" placeholder="搜索..." @input="handleSearch" />
                    <!-- 搜索结果列表 -->
                    <div v-if="searchResultList.length">
                        <a-list :data-source="searchResultList" bordered @itemClick="onItemClick">
                            <a-list-item v-for="item in searchResultList" :key="item.key" @click="onItemClick(item)">
                                {{ item.title }}
                            </a-list-item>
                        </a-list>
                    </div>
                    <!-- 树结构 -->
                    <a-tree v-else :tree-data="filteredTreeData" :checkable="true" v-model:expandedKeys="expandedKeys"
                        v-model:selectedKeys="selectedKeys" v-model:checkedKeys="checkedKeys" @select="onSelect"
                        @expand="onExpand" @check="onCheck" />
                </div>
            </template>
        </a-select>
        <pro-input :formItemProps="{ label: '用途:', prop: 'use' }" v-model:value="useYn" placeholder="请输入"
            :allowClear="true">
        </pro-input>
    </div>
    <button @click="changeRelationNo">改变机构汇总关系 relationNo</button>
    <pro-tree2 v-model:relationNo="relationNo" v-model:txBrNo="txBrNo" treeType="deptTree" :checkable="true"
        v-model:checkedKeys="testCheckedKeys" v-model:expandedKeys="testExpandedKeys" @onCheck="onCheck1"></pro-tree2>
    <div>1父组件选中机构{{ txBrNo }}</div>
    <pro-tree2 v-model:txBrNo="txBrNo" v-model:sobNo="sobNo" treeType="sobTree" :checkable="true"></pro-tree2>
    <div>1父组件选中账套{{ sobNo }}</div>





    <!-- <pro-select-tree2 treeType="sobTree"></pro-select-tree2>
    <pro-select-tree2 treeType="deptTree"></pro-select-tree2> -->

    <!-- <ProSelectTree2 treeType="sobTree"></ProSelectTree2> -->

    <!-- <pro-tree3 :treeData="treeData" v-treeType="sobTree"model:checkedKeys="testCheckedKeys"
        v-model:expandedKeys="testExpandedKeys"></pro-tree3>
    <div>父组件选中{{ testCheckedKeys }}</div>
    <div>父组件展开{{ testExpandedKeys }}</div> -->
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount, onUnmounted, watch } from 'vue';

const relationNo = ref('AAAAAA');
// 改变机构树 relationNo 的函数
const testCheckedKeys = ref(['1-1']);
const testExpandedKeys = ref(['1']);
const changeRelationNo = () => {
    if (relationNo.value === 'AAAAAA') {
        relationNo.value = 'BBBBBB';
        testCheckedKeys.value = ['2-1'];
        testExpandedKeys.value = ['2'];
    } else {
        relationNo.value = 'AAAAAA';
        testCheckedKeys.value = ['1-1'];
        testExpandedKeys.value = ['1'];
    }
};

const onCheck1 = (checkedKeys, info) => {
    console.log('wyq---------checkedKeys', checkedKeys, info);
    console.log('wyq---------info', info.node.key);

}

const txBrNo = ref('1');
const sobNo = ref('');
// const testCheckedKeys = ref([]);// 已勾选的节点
// testCheckedKeys.value = ['1'];
// const testExpandedKeys = ref(['1']);// 已勾选的节点



// 下拉框功能
// 用于显示在下拉框中的选中值
const selectedDisplayValue = ref('');
// 是否显示下拉框
const isDropdownOpen = ref(false);
// 处理 a-select 清除事件
const handleClear = () => {
    checkedKeys.value = [];
    selectedDisplayValue.value = '';
};

// 处理选择框点击事件
const handleSelectClick = () => {
    // 清空搜索框
    searchValue.value = '';
    searchResultList.value = [];
    isDropdownOpen.value = true;
};

// 搜索框功能
// 搜索框的值
const searchValue = ref('');
// 搜索结果列表
const searchResultList = ref([]);
// 监听搜索框的值，过滤列表
watch(searchValue, (value) => {
    if (value) {
        const result = [];
        const traverse = (nodes) => {
            nodes.forEach((node) => {
                if (node.title.includes(value)) {
                    result.push(node);
                }
                if (node.children) {
                    traverse(node.children);
                }
            });
        };
        traverse(treeData);
        searchResultList.value = result;
    } else {
        searchResultList.value = [];
    }
});

const onItemClick = (item) => {
    //selectedKey.value = item.key; // 记录选中的项
    //expandedKeys.value = [getParentKey(item.key, gData.value)]; // 展开父节点
    //autoExpandParent.value = true; // 自动展开父节点

    selectedDisplayValue.value = item.title;
    checkedKeys.value = [item.key]; // 勾选当前节点
    // 展开父节点和爷节点
    const parentKeys = getParentKeys(item.key, treeData);
    expandedKeys.value = [...new Set([...expandedKeys.value, ...parentKeys])];
    // 关闭下拉框
    isDropdownOpen.value = false;

};

// 获取节点的父节点和爷节点的 key
// 获取节点的父节点和爷节点的 key
const getParentKeys = (key, nodes) => {
    const parentKeys = [];
    // 递归查找目标节点并记录其父节点信息
    const findNode = (currentNodes, parentKey = null, grandParentKey = null) => {
        for (const node of currentNodes) {
            if (node.key === key) {
                // 如果存在父节点，添加到结果数组
                if (parentKey) {
                    parentKeys.push(parentKey);
                }
                // 如果存在爷节点，添加到结果数组
                if (grandParentKey) {
                    parentKeys.push(grandParentKey);
                }
                return;
            }
            if (node.children) {
                // 递归调用，更新父节点和爷节点信息
                findNode(node.children, node.key, parentKey);
            }
        }
    };
    findNode(nodes);
    return parentKeys;
};


// 树功能
// 选中的树节点的键
const expandedKeys = ref([]);// 已展开的节点
const selectedKeys = ref([]);// 已选中的节点
const checkedKeys = ref([]);// 已勾选的节点

// 示例树结构数据
const treeData = [
    {
        title: 'node 1',
        key: '1',
        children: [
            {
                title: 'child node 1',
                key: '1-1'
            },
            {
                title: 'child node 2',
                key: '1-2'
            }
        ]
    },
    {
        title: 'node 2',
        key: '2',
        children: [
            {
                title: 'child node 1',
                key: '2-1'
            },
            {
                title: 'child node 2',
                key: '2-2'
            },
            {
                title: 'child node 3',
                key: '2-3'
            },
            {
                title: 'child node 4',
                key: '2-4'
            },
            {
                title: 'child node 5',
                key: '2-5'
            }, {
                title: 'child node 6',
                key: '2-6'
            }, {
                title: 'child node 7',
                key: '2-7'
            }, {
                title: 'child node 8',
                key: '2-8'
            }, {
                title: 'child node 9',
                key: '2-9'
            }, {
                title: 'child node 10',
                key: '2-10'
            }, {
                title: 'child node 11',
                key: '2-11'
            }, {
                title: 'child node 12',
                key: '2-12'
            }
        ]
    }
];
// 过滤后的树结构数据
const filteredTreeData = ref([...treeData]);

const useYn = ref('');

// 处理搜索框输入
const handleSearch = () => {
    if (searchValue.value) {
        // filteredTreeData.value = filterTreeData(treeData, searchValue.value);
    } else {
        //filteredTreeData.value = [...treeData];
    }
};

// 递归过滤树结构数据
const filterTreeData = (data, keyword) => {
    return data.filter(item => {
        if (item.title.includes(keyword)) {
            return true;
        }
        if (item.children && item.children.length > 0) {
            const filteredChildren = filterTreeData(item.children, keyword);
            if (filteredChildren.length > 0) {
                return { ...item, children: filteredChildren };
            }
        }
        return false;
    });
};

// 点击复选框触发
const onCheck = (checkedKeys, info) => {
    console.log('wyq---------checkedKeys', checkedKeys);
    checkedKeys.value = checkedKeys;
    updateSelectedDisplayValue();
};

// 点击树节点触发
function onSelect (selectedKeys, info) {
    console.log('wyq---------selectedKeys', selectedKeys);
}
// 展开/收起节点时触发
function onExpand (expandedKeys, info) {
    console.log('wyq---------expandedKeys', expandedKeys);
}



// 更新显示在下拉框中的选中值
const updateSelectedDisplayValue = () => {
    const selectedTitles = [];
    checkedKeys.value.forEach((key) => {
        const findTitle = (nodes) => {
            for (const node of nodes) {
                if (node.key === key) {
                    return node.title;
                }
                if (node.children) {
                    const childTitle = findTitle(node.children);
                    if (childTitle) {
                        return childTitle;
                    }
                }
            }
            return null;
        };
        const title = findTitle(treeData);
        if (title) {
            selectedTitles.push(title);
        }
    });
    selectedDisplayValue.value = selectedTitles.join(', ');
};



// 处理下拉框展开状态变化
const handleOpenChange = (open) => {
    isDropdownOpen.value = open;
};

// 点击其他区域隐藏下拉框
const selectRef = ref(null);
const dropdownRef = ref(null);
const handleDocumentClick = (event) => {
    if (
        selectRef.value &&
        dropdownRef.value &&
        !selectRef.value.$el.contains(event.target) &&
        !dropdownRef.value.contains(event.target)
    ) {
        isDropdownOpen.value = false;
    }
};
onMounted(() => {
    document.addEventListener('click', handleDocumentClick);
});

onBeforeUnmount(() => {
    document.removeEventListener('click', handleDocumentClick);
});
</script>

<style scoped>
/* .dropdown-content {
    padding: 8px;
} */

.dropdown-content {
    /* 设置固定的高度和宽度 */
    max-height: 300px;
    width: 500px;
    /* 设置溢出时显示滚动条 */
    overflow: auto;
    /* 可以根据需要添加其他样式 */
    border: 1px solid #ccc;
    padding: 8px;
}
</style>
