<template>
    <!-- 左侧树 -->
    <div>
        <el-card style="height: calc(100vh - 125px)">
            <el-row :gutter="20" style="display: flex; align-items: center">
                <el-col :span="16">
                    <el-input v-model="filterText" placeholder="输入关键字" @keyup.enter.native="onHandleSearch">
                    </el-input>
                </el-col>
                <el-col :span="8">
                    <el-button type="primary" size="small" @click="onHandleSearch">
                        查询
                    </el-button>
                    <el-button plain size="small" type="primary" icon="el-icon-plus"
                        v-hasPermi="['archive:catalogue:add']" @click="addTree">
                        新增
                    </el-button>
                </el-col>
            </el-row>

            <div class="tree-container">
                <el-tree ref="leftTreeRef" :data="treeDataList" default-expand-all class="left-tree-list"
                    @node-click="onHandleNodeClick" :filter-node-method="filterNode" highlight-current node-key="id">
                    <span class="custom-tree-node" slot-scope="{ node, data }">
                        <template v-if="isTruncated(node.label)">
                            <el-tooltip effect="dark" :content="node.label" placement="right">
                                <span class="node-label">{{ truncateLabel(node.label) }}</span>
                            </el-tooltip>
                        </template>
                        <template v-else>
                            <span class="node-label">{{ node.label }}</span>
                        </template>
                        <span class="btn-box">
                            <el-button type="text" icon="el-icon-plus" v-if="node.level !== 4"
                                @click.stop="() => addTree(data)" v-hasPermi="['archive:catalogue:add']">
                            </el-button>
                            <el-button type="text" v-if="node.level > 1" icon="el-icon-edit-outline"
                                style="color: #007ce0" @click.stop="() => editTree(node, data)" v-hasPermi="['archive:catalogue:edit']">
                            </el-button>
                            <el-button type="text" v-if="node.level > 1" icon="el-icon-delete" style="color: #f00000;"
                                @click.stop="() => delTree(node, data)" v-hasPermi="['archive:catalogue:del']">
                            </el-button>
                        </span>
                    </span>
                </el-tree>
            </div>
        </el-card>
        <!-- 树的操作（新增、修改） -->
        <AddTreeData v-if="isflag" :isAdd="isAdd" :rowData="row" :title="title" @closeDialog="closeDialog"
            @showColose="showColose" :dataForm="row" :width="600" />
    </div>

</template>

<script>
import { getArchivalCatalogueTreeApi,delArchiveApi } from '@/api/archivesManagement/index.js'
import AddTreeData from './addTreeData.vue'
import { validSecurity } from '@/utils/validate'
export default {
    name: 'LeftTree',
    components: { AddTreeData },
    data() {
        return {
            treeDataList: [],
            filterText: '',
            originalTreeData: [], // 保存原始数据,
            isflag: false,
            isAdd: '',
            title:'',
            row: {},
            selectedNodeId: null, // 保存当前选中的节点ID
            delArchiveApi
        }
    },
    computed: {
        // 过滤后的树数据
        filteredTreeData() {
            if (!this.filterText) {
                return this.treeDataList
            }
            return this.filterTreeData(this.treeDataList)
        }
    },
    methods: {
        /* 刷新树节点 */
        async handleQuery() {
            // 保存当前选中的节点ID
            const currentNode = this.$refs.leftTreeRef.getCurrentNode();
            if (currentNode) {
                this.selectedNodeId = currentNode.id;
            }

            // 重新获取树数据
            await this.getLeftTreeList();

            // 恢复选中状态
            this.$nextTick(() => {
                if (this.selectedNodeId) {
                    this.$refs.leftTreeRef.setCurrentKey(this.selectedNodeId);
                }
            });
        },
        closeDialog() {
            this.isflag = false;
            // 关闭弹窗后刷新树节点
            this.handleQuery();
        },
        showColose() {
            this.isflag = false;
        },
        /* 新增树节点 */
        addTree(data) {
            this.title = "新增";
            this.isAdd = 'add';
            this.isflag = true;
            if(data){
                this.row = data;
                this.row.level = Number(data.level) + 1
            }
        },
        /* 修改树节点 */
        editTree(row, data) {
            this.title = "修改";
            this.isAdd = 'edit';
            this.row = data;
            this.isflag = true;
        },
        /* 删除树节点 */
        delTree(row, data){
            this.$modal.confirm(`是否确认删除节点名称为"${row.label}"的数据项？`).then(() => {
                // 显示加载遮罩
                this.$modal.loading("正在删除，请稍候...");
                delArchiveApi({ id: data.id }).then(res => {
                    this.$modal.closeLoading();
                    if (res.code === 200) {
                        this.$modal.msgSuccess("删除成功");
                        this.handleQuery();
                    } else {
                        this.$modal.msgError(res.msg);
                    }
                })
                .catch(error => {
                    this.$modal.closeLoading();
                    this.$modal.msgError(error);
                    console.error('删除失败:', error);
                });
            }).catch(() => {
                // 用户取消删除，不需要处理
            });

        },
        // 节点点击事件
        onHandleNodeClick(data) {
            // 保存选中的节点ID
            this.selectedNodeId = data.id;
            this.$emit('handleNodeClick', data)
        },
        
        // 树数据过滤 - 支持无限层级转换
        convertToVueTree(data) {
            if (!data || !Array.isArray(data)) {
                return [];
            }

            return data.map(item => {
                const node = {
                    id: item.id,
                    label: item.contentName,
                    level: item.level,
                    sort: item.sort,
                    parentId: item.parentId,
                    parentName:item.parentName
                };

                // 递归处理子节点
                if (item.children && Array.isArray(item.children) && item.children.length > 0) {
                    const children = this.convertToVueTree(item.children);
                    // 只有当子节点不为空时才添加 children 属性
                    if (children.length > 0) {
                        node.children = children;
                    }
                }

                return node;
            });
        },
        // 文本截断显示（超过27个字符以 ... 显示）
        truncateLabel(text) {
            if (!text) return '';
            const max = this.getMaxLabelLength();
            return text.length > max ? text.slice(0, max) + '...' : text;
        },
        isTruncated(text) {
            if (!text) return false;
            return text.length > this.getMaxLabelLength();
        },
        getMaxLabelLength() {
            return 100; // 统一控制阈值
        },
        // 获取左侧树列表
        async getLeftTreeList() {
            const res = await getArchivalCatalogueTreeApi()
            const transformedData = this.convertToVueTree(res.data)
            this.treeDataList = transformedData;
            // 保存原始数据
            this.originalTreeData = JSON.parse(JSON.stringify(this.treeDataList))
        },
        // 搜索
        onHandleSearch() {
            // 安全校验
            if (this.filterText && !validSecurity(this.filterText)) {
                this.$message.error('搜索内容包含非法字符，请重新输入')
                return
            }
            this.$refs.leftTreeRef.filter(this.filterText)
        },
        // 树节点过滤方法
        filterNode(value, data) {
            if (!value) return true
            return data.label.indexOf(value) !== -1
        },
        // 递归过滤树数据
        filterTreeData(treeData) {
            const result = []
            for (const node of treeData) {
                const newNode = { ...node }
                if (node.children && node.children.length > 0) {
                    const filteredChildren = this.filterTreeData(node.children)
                    if (filteredChildren.length > 0) {
                        newNode.children = filteredChildren
                        result.push(newNode)
                    } else if (node.label.indexOf(this.filterText) !== -1) {
                        // 如果父节点匹配，保留所有子节点
                        result.push(node)
                    }
                } else if (node.label.indexOf(this.filterText) !== -1) {
                    result.push(newNode)
                }
            }
            return result
        },
    },
    created() {
        this.getLeftTreeList()
    },
}
</script>

<style scoped>
.tree-container {
    margin-top: 10px;
    max-height: calc(100vh - 220px);
    overflow-x: hidden;
    overflow-y: auto;
}

/* 完全隐藏滚动条但保持滚动功能 */
.tree-container::-webkit-scrollbar {
    width: 0px;
    background: transparent;
}

.tree-container::-webkit-scrollbar-track {
    background: transparent;
}

.tree-container::-webkit-scrollbar-thumb {
    background: transparent;
}

.left-tree-list {
    width: 100%;
}

/* 自定义节点行：左右布局，左侧文本省略号 */
.custom-tree-node {
    display: flex;
    align-items: center;
    justify-content: space-between;
    width: 100%;
}

.node-label {
    flex: 1;
    min-width: 0;
    overflow: visible;
    text-overflow: initial;
    white-space: normal; /* 允许换行 */
    word-break: break-word; /* 长词断行 */
    line-height: 20px;
    font-size: 14px;
}

/* 使行容器自适应高度并顶对齐，兼容多行文本 */
.left-tree-list .el-tree-node__content {
    display: flex;
    align-items: flex-start;
    height: auto;
    min-height: 28px;
    padding-top: 6px;
    padding-bottom: 6px;
    line-height: 20px;
}

/* 高亮选中状态同样自适应高度 */
.el-tree--highlight-current .el-tree-node.is-current > .el-tree-node__content {
    height: auto !important;
    align-items: flex-start;
    line-height: 20px;
}

/* 选中节点的背景色 */
.left-tree-list .el-tree-node.is-current>.el-tree-node__content {
    background-color: #b3d9ff;
    color: #006e6a !important;
}

/* 确保选中节点的文字颜色正确应用 */
.left-tree-list .el-tree-node.is-current>.el-tree-node__content .el-tree-node__label {
    color: #006e6a !important;
}

/* 确保自定义树节点中的文字颜色正确应用 */
.left-tree-list .el-tree-node.is-current>.el-tree-node__content .custom-tree-node {
    color: #006e6a !important;
}

/* 悬停效果 */
.left-tree-list .el-tree-node__content:hover {
    background-color: #f5f5f5;
}
.el-tree--highlight-current .el-tree-node.is-current > .el-tree-node__content {
    height: auto;
}
/* 选中节点的悬停效果 */
.left-tree-list .el-tree-node.is-current>.el-tree-node__content:hover {
    background-color: #8cc8ff;
}


.btn-box {
    margin-left: 10px;
    opacity: 0;
    transition: opacity 0.15s ease-in-out;
}

/* 悬浮到整行时显示操作按钮 */
.left-tree-list .el-tree-node__content:hover .btn-box {
    opacity: 1;
}

::v-deep .el-tree-node__content {
    display: -webkit-box;
    display: -ms-flexbox;
    display: flex;
    -webkit-box-align: center;
    -ms-flex-align: center;
    align-items: center;
    cursor: pointer;
    height: auto;
}
</style>
