<template>
  <el-card class="analysis-label-item-container">
    <div class="back-container">
      <el-button type="default" size="small" @click="handleBack" class="back-btn">
        返回
      </el-button>
    </div>
    <el-row :gutter="20">
      <!-- 左侧树状图区域 -->
      <el-col :span="5">
        <div class="tree-container" style="height: calc(100vh - 205px)">


          <el-input
            placeholder="搜索标签项"
            v-model="treeSearchKey"
            class="tree-search"
            clearable
            size="small"
          />

          <el-tree
            ref="labelItemTree"
            :data="treeData"
            :props="treeProps"
            node-key="analysisLabelItemId"
            :filter-node-method="filterTreeNode"
            default-expand-all
            @node-click="handleTreeNodeClick"
            @current-change="handleTreeNodeChange"
          >
            <template #default="{ node, data }">
              <span class="tree-node-content">
                <span>{{ node.label }}</span>
                <span class="tree-node-actions">
                  <i
                    class="el-icon-edit"
                    @click.stop="handleEditTreeNode(data)"
                    v-hasPermi="['template:analysisLabelItem:edit']"
                  ></i>
                  <i
                    class="el-icon-delete"
                    @click.stop="handleDeleteTreeNode(data)"
                    v-hasPermi="['template:analysisLabelItem:del']"
                  ></i>
                </span>
              </span>
            </template>
          </el-tree>
        </div>
      </el-col>

      <!-- 右侧表格区域 -->
      <el-col :span="19">
        <div>
          <TableModel
            :showOperation="true"
            :showRightTools="false"
            :showBtnCrews="false"
            :showSearch="false"
            ref="analysisLabelItemTableRef"
            :columnsList="columnsItemList"
            :request-api="listAnalysisLabelItem"
            :sendParams="tableSendParams"
          >
          <!-- 表格标题 -->
          <template v-slot:tableTitle>
            <h3>标签项列表</h3>
          </template>

          <!-- 表格操作按钮 -->
          <template v-slot:tableActions>
            <el-button
              @click="handleAdd"
              v-hasPermi="['template:analysisLabelItem:add']"
              class="add-btn"
            >
              <i class="el-icon-plus"></i> 新增标签项
            </el-button>
          </template>

          <!-- 上级标签显示：通过parentId映射名称 -->
          <template v-slot:parentName="{ data }">
              <span>
                {{ getParentName(data.parentId) || '' }}
              </span>
          </template>

          <!-- 层级显示 -->
          <template v-slot:analysisLevel="{ data }">
              <span>
                {{ levelMap[data.analysisLevel] || data.analysisLevel }}
              </span>
          </template>

          <template v-slot:analysisSort="{ data }">
              <span>
                {{ data.analysisSort }}
              </span>
          </template>

          <!-- 操作按钮 -->
          <template slot="handle" slot-scope="{ data }">
            <el-button
              type="text"
              v-hasPermi="['template:analysisLabelItem:edit']"
              class="action-btn"
              style="color: #EAA819;"
              @click="handleUpdate(data)"
            >
              编辑
            </el-button>
            <el-button
              type="text"
              v-hasPermi="['template:analysisLabelItem:del']"
              class="action-btn"
              style="color: #DB3E29;"
              @click="handleDelete(data)"
            >
              删除
            </el-button>
          </template>
          </TableModel>
        </div>
      </el-col>
    </el-row>

    <!-- 新增/编辑标签项抽屉 -->
    <AnalysisLabelItemForm
      v-if="drawerVisible"
      :visible="drawerVisible"
      :type="isAdd"
      :row-data="row"
      :tree-data="treeData"
      @close="drawerVisible = false"
      @save-success="handleQuery"
      @refresh-tree="loadTreeData"
    />
  </el-card>
</template>

<script>
import TableModel from '@/components/TableModel2'
import { columnsItemList } from './config'
import AnalysisLabelItemForm from './child/AnalysisLabelItemForm.vue'
import {
  listAnalysisLabelItem,
  delAnalysisLabelItem
} from '@/api/template/analysisLabelItem/analysisLabelItem'
import { encryptWithSM4, decryptWithSM4 } from '@/utils/sm'

export default {
  name: 'AnalysisLabelItem',
  components: {
    TableModel,
    AnalysisLabelItemForm
  },
  data() {
    return {
      columnsItemList,
      listAnalysisLabelItem,

      // 树状图配置
      treeData: [],
      treeProps: {
        label: 'analysisName',
        children: 'children'
      },
      treeSearchKey: '',
      // 存储所有标签项的ID与名称映射
      labelItemMap: new Map(),

      // 表格传递参数（与示例一致，使用sendParams对应的对象）
      tableSendParams: {
        analysisId: '', // 解密后的标签组ID
        nodeIds: ''     // 用于查询的节点ID列表（当前节点+所有子节点）
      },

      // 层级映射
      levelMap: {
        1: '一级',
        2: '二级',
        3: '三级'
      },

      // 抽屉控制
      drawerVisible: false,
      isAdd: '',
      row: {}
    }
  },

  created() {
    // 解密路由参数中的analysisLabelId，初始化sendParams
    this.tableSendParams.analysisId = decryptWithSM4(this.$route.query.analysisLabelId) || ''
    this.loadTreeData()
  },

  methods: {

    handleBack() {
      const obj = {
        path: "/analysisLabel/index",
      }
      this.$tab.closeOpenPage(obj)
    },

    // 加载树形结构数据，并构建ID-名称映射表
    loadTreeData() {
      const allItems = []; // 用于存储所有页的数据
      const pageSize = 1000; // 每页数量，根据后端接口定义调整
      let currentPage = 1; // 当前页码

      // 定义一个递归函数来获取每一页的数据
      const fetchPage = () => {
        listAnalysisLabelItem({
          analysisId: this.tableSendParams.analysisId,
          pageNum: currentPage,
          pageSize: pageSize
        }).then(res => {
          if (res.code === 200) {
            const { rows, total } = res;

            // 将当前页的数据追加到总数组
            if (rows && rows.length > 0) {
              allItems.push(...rows);
            }

            // 计算总页数
            const totalPages = Math.ceil(total / pageSize);

            // 如果当前页不是最后一页，则继续获取下一页
            if (currentPage < totalPages) {
              currentPage++;
              fetchPage(); // 递归调用，获取下一页
            } else {
              // 所有页都获取完毕，构建树形结构
              console.log('所有数据获取完毕，共', allItems.length, '条');
              this.treeData = this.buildTree(allItems);
              this.buildLabelItemMap(allItems); // 构建映射表
            }
          } else {
            // 出错处理
            this.$modal.msgError('加载标签项数据失败');
          }
        });
      };

      // 开始执行首次获取
      fetchPage();
    },

    // 构建树形结构
    buildTree(list) {
      const tree = []
      const map = {}

      list.forEach(item => {
        map[item.analysisLabelItemId] = { ...item, children: [] }
      })

      list.forEach(item => {
        if (item.parentId && map[item.parentId]) {
          map[item.parentId].children.push(map[item.analysisLabelItemId])
        } else {
          tree.push(map[item.analysisLabelItemId])
        }
      })

      return tree
    },

    // 构建所有标签项的ID与名称映射表
    buildLabelItemMap(list) {
      this.labelItemMap.clear() // 清空旧数据
      list.forEach(item => {
        this.labelItemMap.set(String(item.analysisLabelItemId), item.analysisName)
      })
    },

    // 根据parentId获取上级标签名称
    getParentName(parentId) {
      if (!parentId) return ''
      return this.labelItemMap.get(String(parentId)) || '未知'
    },

    // 树形节点过滤
    filterTreeNode(value, data) {
      if (!value) return true
      return data.analysisName.includes(value) || data.analysisCode.includes(value)
    },

    // 树形节点点击事件：查询当前节点及所有子节点数据
    handleTreeNodeClick(data) {
      const allNodeIds = this.collectAllNodeIds(data)
      this.tableSendParams.nodeIds = allNodeIds // 此时是字符串
      this.$nextTick(() => {
        this.handleQuery()
      })
    },

    // 树形节点切换事件（保持选中状态同步）
    handleTreeNodeChange(currentNode) {
      if (currentNode) {
        const allNodeIds = this.collectAllNodeIds(currentNode)
        this.tableSendParams.nodeIds = allNodeIds
      } else {
        this.tableSendParams.nodeIds = '' // 清空时也用空字符串
      }
      this.$nextTick(() => {
        this.handleQuery()
      })
    },

    // 递归收集当前节点及所有子节点的ID
    collectAllNodeIds(node) {
      if (!node || !node.analysisLabelItemId) return '';
      const currentId = String(node.analysisLabelItemId); // 强制转为字符串
      const ids = [currentId]; // 直接添加完整ID

      // 递归遍历子节点（无论层级）
      if (node.children && node.children.length > 0) {
        node.children.forEach(child => {
          const childIds = this.collectAllNodeIds(child);
          if (childIds) {
            // 将子节点返回的字符串拆分成数组，再合并（避免重复逗号）
            ids.push(...childIds.split(',').filter(id => id)); // 过滤空字符串
          }
        });
      }

      // 去重处理（避免重复ID）+ 拼接成字符串
      return [...new Set(ids)].join(',');
    },

    // 新增节点（树形图）
    handleAddTreeNode() {
      this.isAdd = 'add'
      this.row = {
        analysisId: this.tableSendParams.analysisId,
        parentId: this.$refs.labelItemTree.getCurrentKey() || ''
      }
      this.drawerVisible = true
    },

    // 编辑节点（树形图）
    handleEditTreeNode(data) {
      this.isAdd = 'edit'
      this.row = { ...data }
      this.drawerVisible = true
    },

    // 删除节点（树形图）
    handleDeleteTreeNode(data) {
      this.$modal.confirm(`是否确认删除“${data.analysisName}”标签项及其子节点？`)
        .then(() => {
          delAnalysisLabelItem({
            analysisLabelItemId: data.analysisLabelItemId
          })
            .then(res => {
              if (res.code === 200) {
                this.$modal.msgSuccess('删除成功')
                this.loadTreeData() // 重新加载树数据
                this.handleQuery()
              } else {
                this.$modal.msgError(res.msg)
              }
            })
        })
    },

    // 新增标签项（表格）
    handleAdd() {
      this.isAdd = 'add'
      this.row = {
        analysisId: this.tableSendParams.analysisId,
        // 若有选中节点，默认父节点为选中节点；否则为根节点
        parentId: this.$refs.labelItemTree.getCurrentKey() || ''
      }
      this.drawerVisible = true
    },

    // 编辑标签项（表格）
    handleUpdate(row) {
      this.isAdd = 'edit'
      this.row = { ...row }
      this.drawerVisible = true
    },

    // 删除标签项（表格）
    handleDelete(row) {
      this.$modal.confirm(`是否确认删除“${row.analysisName}”标签项及其子节点？`)
        .then(() => {
          delAnalysisLabelItem({
            analysisLabelItemId: row.analysisLabelItemId
          })
            .then(res => {
              if (res.code === 200) {
                this.$modal.msgSuccess('删除成功')
                this.loadTreeData() // 重新加载树数据
                this.handleQuery()
              } else {
                this.$modal.msgError(res.msg)
              }
            })
        })
    },

    // 刷新列表（与示例一致，通过ref调用TableModel的getTableList方法）
    handleQuery() {
      this.$refs.analysisLabelItemTableRef.getTableList()
    }
  },

  watch: {
    // 监听树搜索关键词变化
    treeSearchKey(val) {
      this.$refs.labelItemTree.filter(val)
    },

    // 监听路由参数变化（重新解密，更新sendParams）
    '$route.query.analysisLabelId'(val) {
      this.tableSendParams.analysisId = decryptWithSM4(val) || ''
      this.loadTreeData() // 重新加载树数据
      this.handleQuery()
    }
  }
}
</script>

<style scoped lang="scss">


.back-container {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  margin-bottom: 20px;
  padding: 0 20px;

  .back-btn {
    width: 98px;
    height: 36px;
    background: #FFFFFF;
    box-shadow: 0px 4px 8px 0px rgba(76, 76, 76, 0.2);
    border-radius: 4px;
    border: none;
    color: #666;
    font-size: 14px;
    transition: all 0.3s ease;

    &:hover {
      background: #f5f5f5;
      color: #409EFF;
      box-shadow: 0px 6px 12px 0px rgba(76, 76, 76, 0.3);
    }
  }
}

.analysis-label-item-container {
  height: calc(100vh - 84px);
  overflow: hidden;
  background: linear-gradient(180deg, #F1F6FF 20%, #E5EFFF 100%);
  padding: 16px;
}

// 树形图样式
.tree-container {
  margin-top: 6px;
  height: 100%;
  background: #fff;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  padding: 16px;
  display: flex;
  flex-direction: column;
  box-sizing: border-box;

  .tree-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;
    h3 {
      margin: 0;
      font-size: 16px;
      font-weight: 600; // 增强标题权重，与表格标题一致
      color: #333;
    }
  }

  .tree-search {
    margin-bottom: 16px;
    ::v-deep .el-input__inner {
      border-color: #dcdfe6;
      border-radius: 4px;
      &:focus {
        border-color: #1f72ea; // 聚焦时边框色与表格交互元素一致
        box-shadow: 0 0 0 2px rgba(31, 114, 234, 0.2);
      }
    }
  }

  .el-tree {
    flex: 1;
    overflow-y: auto;
    &::-webkit-scrollbar {
      width: 6px;
      height: 6px;
    }
    &::-webkit-scrollbar-thumb {
      background-color: #ddd;
      border-radius: 3px;
    }
    &::-webkit-scrollbar-track {
      background-color: #f5f5f5;
    }

    ::v-deep .el-tree-node__content {
      height: 40px;
      &:hover {
        background-color: #f5f7fa;
      }
    }

    ::v-deep .el-tree-node.is-current > .el-tree-node__content {
      background-color: #e6f7ff;
      font-weight: 500;
    }
  }

  .tree-node-content {
    display: flex;
    justify-content: space-between;
    align-items: center;
    width: 100%;
    height: 100%; // 确保内容充满节点行高

    > span:first-child {
      font-size: 15px !important;
    }

    .tree-node-actions {
      opacity: 0;
      transition: opacity 0.3s;

      i {
        margin-left: 8px;
        cursor: pointer;
        font-size: 14px;
        // 9. 图标交互效果与表格操作按钮对齐
        &:hover {
          filter: brightness(1.2); // hover 时轻微提亮
        }
      }

      .el-icon-edit {
        color: #EAA819;
      }

      .el-icon-delete {
        color: #DB3E29;
      }
    }

    &:hover .tree-node-actions {
      opacity: 1;
    }
  }
}

// 按钮样式
.add-btn {
  width: 121px;
  height: 36px;
  background: #1F72EA;
  box-shadow: 0px 4px 8px 0px rgba(51, 135, 255, 0.5);
  border-radius: 4px;
  border: none;
  color: #fff;
  font-size: 14px;
  transition: all 0.3s;
  margin-right: 10px;

  &:hover {
    background: #4A8BFF;
    box-shadow: 0px 6px 12px 0px rgba(51, 135, 255, 0.6);
  }
}

.action-btn {
  margin-right: 8px;

  &:last-child {
    margin-right: 0;
  }
}
</style>
