<template>
  <div class="version-content">
    <!-- 左侧：版本记录时间线 -->
    <div class="version-timeline">
      <h3 class="section-title">版本记录</h3>
      <div class="timeline-list">
        <div
          v-for="(version, index) in filteredVersionList"
          :key="version.version"
          class="timeline-item"
          :class="{ 'active': currentVersion === version.version }"
          @click="handleVersionClick(version.version)"
        >
          <div class="timeline-dot"></div>
          <div class="timeline-line" v-if="index < filteredVersionList.length - 1"></div>
          <div class="timeline-content">
            <div class="version-number">{{ version.version }}</div>
            <div class="version-time">{{ formatDate(version.updateTime) }}</div>
          </div>
        </div>
        <div v-if="filteredVersionList.length === 0" class="empty-version">
          暂无有效版本记录
        </div>
      </div>
    </div>

    <!-- 右侧：版本规则详情 -->
    <div class="version-detail">
      <h3 class="section-title">
        版本规则详情
        <span class="current-version" v-if="currentVersion"> - {{ currentVersion }}</span>
      </h3>
      <div class="detail-content">
        <!-- 内容区域使用 flex 布局，使其占满高度 -->
        <el-row :gutter="20" class="rule-layout">
          <!-- 左侧树状图区域 -->
          <el-col :span="6">
            <div class="tree-container">
              <el-input
                placeholder="搜索标签项"
                v-model="treeSearchKey"
                class="tree-search"
                clearable
                size="small"
              />
              <div
                class="tree-wrapper"
                v-loading="isTreeLoading"
                element-loading-text="加载中"
                element-loading-spinner="el-icon-loading"
                element-loading-background="rgba(255, 255, 255, 0.8)"
              >
                <el-tree
                  ref="labelItemTree"
                  :data="treeData"
                  :props="treeProps"
                  node-key="analysisLabelItemId"
                  :filter-node-method="filterTreeNode"
                  default-expand-all
                  @node-click="handleTreeNodeClick"
                  @current-change="handleTreeNodeChange"
                  v-if="treeData.length > 0"
                >
                  <template #default="{ node, data }">
                    <span class="tree-node-content">
                      <span>{{ node.label }}</span>
                    </span>
                  </template>
                </el-tree>
                <div v-else-if="!isTreeLoading" class="empty-tree">暂无树节点数据</div>
              </div>
            </div>
          </el-col>

          <!-- 右侧表格区域 -->
          <el-col :span="18">
            <div>
              <div
                class="table-wrapper"
                v-loading="!isTableReady"
                element-loading-text="加载中"
                element-loading-spinner="el-icon-loading"
                element-loading-background="rgba(255, 255, 255, 0.8)"
              >
                <TableModel
                  v-if="isTableReady"
                  :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>
                    <!-- 此处留白 -->
                  </template>

                  <!-- 上级标签显示 -->
                  <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"
                      class="action-btn view-btn"
                      @click="handleView(data)"
                    >
                      查看
                    </el-button>
                  </template>
                </TableModel>
              </div>
            </div>
          </el-col>
        </el-row>

      </div>
    </div>
    <RuleDetailDrawer
      v-model="drawerVisible"
      :analysis-label-item-id="currentAnalysisLabelItemId"
      :current-version="currentVersion"
      :template-id="templateId"
    />
  </div>
</template>

<script>
import TableModel from '@/components/TableModel2'
import { listAnalysisLabelItem } from '@/api/template/analysisLabelItem/analysisLabelItem'
import { columnsItemList } from "../../../analysisLabel/components/config";
import RuleDetailDrawer from './RuleDetailDrawer.vue'

export default {
  name: 'VersionContent',
  components: {
    RuleDetailDrawer,
    TableModel
    // 修复4：移除Loading组件注册
  },
  props: {
    versionList: {
      type: Array,
      default: () => []
    },
    // 从父组件接收 analysisLabelId
    analysisLabelId: {
      type: [String, Number],
      default: ''
    },
    templateId: {
      type: [String, Number],
      required: true,
      // 确保templateId不会是null/undefined
      validator: (value) => {
        return value !== null && value !== undefined
      }
    }
  },
  computed: {
    // 过滤出有版本号的条目
    filteredVersionList() {
      return this.versionList.filter(item => item.version && item.version.trim());
    }
  },
  data() {
    return {
      drawerVisible: false,
      currentAnalysisLabelItemId: '',
      currentVersion: null,
      selectedVersion: null,
      isTableReady: false, // 控制表格是否渲染的标志
      isTreeLoading: false, // 新增：控制树加载状态的标志

      // --- 集成的树和表格数据 ---
      columnsItemList,
      listAnalysisLabelItem, // 引入API方法

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

      // 表格传递参数
      tableSendParams: {
        analysisId: '', // 由analysisLabelId赋值
        nodeIds: ''
      },

      // 层级映射
      levelMap: {
        1: '一级',
        2: '二级',
        3: '三级'
      }
    }
  },
  watch: {
    // 监听过滤后的版本列表
    filteredVersionList(newList) {
      // 确保analysisLabelId存在且有值时才执行
      if (newList && newList.length > 0 && this.analysisLabelId) {
        this.handleVersionClick(newList[0].version);
      } else if (newList && newList.length > 0 && !this.analysisLabelId) {
        // 如果analysisLabelId还未获取到，等待100ms重试
        setTimeout(() => {
          if (this.analysisLabelId) {
            this.handleVersionClick(newList[0].version);
          }
        }, 100);
      } else {
        this.currentVersion = null;
        this.selectedVersion = null;
      }
    },
    // 监听父组件传递的 analysisLabelId 变化
    analysisLabelId(newVal) {
      if (newVal) {
        this.tableSendParams.analysisId = newVal;
        // 使用 .then() 确保在树构建完成后才执行
        this.loadTreeData().then(() => {
          // 使用 $nextTick 确保 DOM 更新完成（树已渲染）
          this.$nextTick(() => {
            // 手动触发一次表格查询，此时参数已完全正确
            this.handleTreeNodeChange(null);
            // 表格参数准备就绪，允许渲染表格
            this.isTableReady = true;
          });
        }).catch(error => {
          console.error('加载树数据失败:', error);
          this.isTableReady = false;
          this.isTreeLoading = false; // 加载失败也要停止loading
        });
      }
    },
    // 监听树搜索关键词变化
    treeSearchKey(val) {
      if (this.$refs.labelItemTree) {
        this.$refs.labelItemTree.filter(val);
      }
    },
    // 监听要传递给抽屉的ID，如果ID存在，则打开抽屉
    currentAnalysisLabelItemId(newVal) {
      if (newVal && !this.drawerVisible) { // 增加判断，避免重复打开
        this.$nextTick(() => {
          this.drawerVisible = true;
          console.log('通过watch打开抽屉，ID:', newVal); // 增加日志便于调试
        });
      }
    }
  },
  methods: {
    // 版本切换时触发，可以在这里做一些逻辑，比如记录当前查看的版本
    handleVersionClick(version) {
      this.currentVersion = version;
      this.selectedVersion = this.filteredVersionList.find(v => v.version === version) || null;
      // 确保analysisLabelId和tableSendParams.analysisId都有值
      if (this.analysisLabelId && this.tableSendParams.analysisId && (!this.treeData || this.treeData.length === 0)) {
        this.loadTreeData().catch(error => {
          console.error('切换版本时加载树数据失败:', error);
        });
      } else if (!this.tableSendParams.analysisId && this.analysisLabelId) {
        // 同步analysisLabelId到tableSendParams
        this.tableSendParams.analysisId = this.analysisLabelId;
        this.loadTreeData().catch(error => {
          console.error('切换版本时加载树数据失败:', error);
        });
      }
    },

    // 加载树形结构数据
    loadTreeData() {
      // 修复5：设置树加载状态为true
      this.isTreeLoading = true;

      // 如果没有analysisId，则不执行并reject
      if (!this.tableSendParams.analysisId) {
        // 如果analysisId为空，尝试从props获取
        if (this.analysisLabelId) {
          this.tableSendParams.analysisId = this.analysisLabelId;
        } else {
          console.warn('analysisId is not provided.');
          this.isTreeLoading = false; // 停止loading
          return Promise.reject(new Error('analysisId is empty'));
        }
      }

      return new Promise((resolve, reject) => {
        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);
                this.isTreeLoading = false; // 加载完成停止loading
                resolve(); // 数据加载成功，resolve Promise
              }
            } else {
              this.isTreeLoading = false; // 加载失败停止loading
              reject(new Error(`获取树数据失败: ${res.msg || '未知错误'}`));
            }
          }).catch(error => {
            this.isTreeLoading = false; // 异常停止loading
            reject(error); // 网络错误等，reject Promise
          });
        };
        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 && 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];
      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));
          }
        });
      }
      return [...new Set(ids)].join(',');
    },

    // 查看按钮点击事件
    handleView(data) {
      console.log('点击查看，分析标签项ID为:', data.analysisLabelItemId); // 日志调试

      // 1. 先重置抽屉状态（防止重复点击导致的状态异常）
      this.drawerVisible = false;

      // 2. 确保ID赋值（使用$set保证响应式）
      this.$set(this, 'currentAnalysisLabelItemId', data.analysisLabelItemId);

      // 3. 手动触发抽屉打开（不依赖watch，直接控制）
      this.$nextTick(() => {
        this.drawerVisible = true;
        console.log('手动打开抽屉，drawerVisible:', this.drawerVisible);
      });
    },

    // 刷新列表
    handleQuery() {
      if (this.$refs.analysisLabelItemTableRef && this.isTableReady) {
        this.$refs.analysisLabelItemTableRef.getTableList();
      }
    },

    // 格式化日期
    formatDate(dateString, fmt = 'YYYY-MM-DD HH:mm:ss') {
      if (!dateString) return '';
      const date = new Date(dateString);
      if (isNaN(date.getTime())) return '';
      const o = {
        'M+': date.getMonth() + 1,
        'D+': date.getDate(),
        'H+': date.getHours(),
        'm+': date.getMinutes(),
        's+': date.getSeconds(),
        'q+': Math.floor((date.getMonth() + 3) / 3),
        'S': date.getMilliseconds()
      };
      if (/(Y+)/.test(fmt)) {
        fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
      }
      for (const k in o) {
        if (new RegExp('(' + k + ')').test(fmt)) {
          fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (('00' + o[k]).substr(('' + o[k]).length)));
        }
      }
      return fmt;
    }
  },
  mounted() {
    // 组件挂载时，初始化tableSendParams.analysisId
    if (this.analysisLabelId) {
      this.tableSendParams.analysisId = this.analysisLabelId;
    }
  }
}
</script>

<style scoped lang="scss">
.version-content {
  display: flex;
  gap: 30px;
  height: 100%;
  min-height: 600px;
  overflow-y: auto;
  padding-bottom: 20px; /* 底部预留空间 */
}

/* --- 左侧时间线样式 --- */
.version-timeline {
  min-width: 220px;
  flex: 1;
  border-right: 1px solid #ebeef5;
  overflow-y: auto;
  padding-right: 60px;
  min-height: 100%;
}
.timeline-list { position: relative; padding-left: 30px; }
.timeline-item { position: relative; padding-bottom: 25px; cursor: pointer; transition: all 0.3s ease; }
.timeline-item:hover .timeline-content .version-number { color: #409EFF; }
.timeline-dot { position: absolute; left: -29px; top: 4px; width: 12px; height: 12px; border-radius: 50%; background-color: #dcdfe6; transition: all 0.3s ease; z-index: 1; }
.timeline-line { position: absolute; left: -23px; top: 16px; width: 2px; height: calc(100% - 12px); background-color: #ebeef5; z-index: 0; }
.timeline-content { position: relative; z-index: 2; }
.version-number { font-size: 15px; font-weight: 500; color: #303133; transition: color 0.3s ease; }
.version-time { font-size: 12px; color: #909399; margin-top: 4px; }
.empty-version { color: #909399; font-size: 14px; padding: 20px 0; }
.timeline-item.active .timeline-dot { background-color: #409EFF; box-shadow: 0 0 0 4px rgba(64, 158, 255, 0.2); }
.timeline-item.active .timeline-content .version-number { color: #409EFF; }

/* --- 右侧详情区域样式 --- */
.version-detail {
  overflow: hidden;
  max-width: calc(100% - 250px);
  flex: 4;
  padding-left: 10px;
  display: flex;
  flex-direction: column;
}
.section-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 16px;
  padding-bottom: 8px;
  border-bottom: 1px solid #ebeef5;
}
.current-version {
  font-size: 14px;
  color: #409EFF;
  font-weight: normal;
  margin-left: 8px;
}


/* --- 集成的树和表格样式 --- */
.rule-layout {
  display: flex;
  height: 100%;
  min-height: 450px;
}
.rule-layout > .el-col {
  display: flex;
  flex-direction: column;
  min-height: 0;
}
.tree-container {
  margin-top: 6px;
  background: #fff;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  padding: 16px;
  flex-grow: 1; /* 让树容器占满列的高度 */
  display: flex;
  overflow-y: auto;
  flex-direction: column;
  box-sizing: border-box;
  max-height: calc(100vh - 270px);
}

.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);
    }
  }
}
/* 修复6：树容器样式优化 */
.tree-wrapper {
  flex: 1;
  overflow-y: auto;
  position: relative;
  min-height: 300px;
}
.el-tree {
  width: 100%;
  background: transparent;
  &::-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: 36px; &:hover { background-color: #f5f7fa; } }
  ::v-deep .el-tree-node.is-current > .el-tree-node__content { background-color: #e6f7ff; font-weight: 400; font-size: 10px; }
}
.tree-node-content { display: flex; justify-content: space-between; align-items: center; width: 100%; height: 100%; > span:first-child {font-size: 15px !important;
}}

/* 空树状态样式 */
.empty-tree {
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  color: #909399;
  font-size: 14px;
}

/* 表格容器样式 */
.table-wrapper {
  background-color: #fff;
  position: relative;
  padding-bottom: 16px;
  max-height: calc(100vh - 270px);
}

/* 查看按钮样式 */
.action-btn.view-btn {
  color: #409EFF;
}
.action-btn.view-btn:hover {
  color: #66b1ff;
}

::v-deep .table-card {
  height: calc(100vh - 270px) !important;
}

</style>
