<template>
  <el-drawer
    :title="drawerTitle"
    :visible.sync="visible"
    :width="500"
    :before-close="handleBeforeClose"
    class="analysis-label-item-drawer"
  >
    <!-- 标题下方分隔线 -->
    <div class="title-divider"></div>

    <!-- 表单内容区 -->
    <div class="drawer-content">
      <el-form
        ref="labelItemForm"
        :model="formData"
        :rules="formRules"
        label-width="80px"
        class="form-container"
      >
        <el-form-item label="上级标签" prop="parentId">
          <el-popover
            placement="bottom-start"
            width="400"
            trigger="click"
            v-model="treePopoverVisible"
            :disabled="type === 'edit'"
          >
            <div class="tree-container">
              <el-tree
                ref="tree"
                :data="treeOptions"
                :props="treeProps"
                node-key="analysisLabelItemId"
                :default-expanded-keys="defaultExpandedKeys"
                :highlight-current="true"
                :expand-on-click-node="false"
                @node-click="handleTreeNodeClick"
                class="limited-level-tree"
              >
                <span class="custom-tree-node" slot-scope="{ node, data }">
                  <span>{{ node.label }}</span>
                </span>
              </el-tree>
            </div>
            <el-input
              slot="reference"
              v-model="selectedTreeLabel"
              placeholder="请选择上级标签"
              readonly
              clearable
              style="width:100%"
              @clear="handleTreeClear"
            >
              <i slot="suffix" class="el-icon-arrow-down" :class="{ 'is-reverse': treePopoverVisible }"></i>
            </el-input>
          </el-popover>
        </el-form-item>

        <el-form-item label="标签名称" prop="analysisName" required>
          <el-input
            v-model="formData.analysisName"
            placeholder="请输入标签名称"
            maxlength="128"
            clearable
            style="width:100%"
          />
        </el-form-item>

        <el-form-item label="标签值" prop="analysisCode" required>
          <el-input
            v-model="formData.analysisCode"
            placeholder="请输入标签值"
            maxlength="128"
            clearable
            style="width:100%"
          />
        </el-form-item>

        <el-form-item label="排序" prop="analysisSort" required>
          <el-input-number
            v-model="formData.analysisSort"
            :min="0"
            placeholder="请输入排序号"
            controls-position="right"
            style="width:100%"
          />
        </el-form-item>
      </el-form>
    </div>

    <div class="footer-divider"></div>

    <!-- 底部操作栏 -->
    <div class="drawer-footer">
      <el-button @click="handleCancel" :disabled="showSaveAnimation">取消</el-button>
      <el-button
        type="primary"
        @click="handleSave"
        :loading="showSaveAnimation"
      >
        保存
      </el-button>
    </div>

    <!-- 保存动画遮罩 -->
    <div v-if="showSaveAnimation" class="save-animation">
      <div class="animation-mask"></div>
      <div class="animation-content">
        <div class="spinner"></div>
        <div class="animation-text">数据保存中</div>
        <div class="animation-subtext">请稍候，正在处理...</div>
      </div>
    </div>
  </el-drawer>
</template>

<script>
import {
  addAnalysisLabelItem,
  updateAnalysisLabelItem,
  checkLabelItemNameUnique
} from '@/api/template/analysisLabelItem/analysisLabelItem'

export default {
  name: 'AnalysisLabelItemForm',
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    type: {
      type: String,
      default: 'add' // 'add' 新增 / 'edit' 编辑
    },
    rowData: {
      type: Object,
      default: () => ({})
    },
    treeData: {
      type: Array,
      default: () => [] // 树形结构数据（用于上级标签选择）
    }
  },
  data() {
    return {
      showSaveAnimation: false, // 保存动画状态
      treePopoverVisible: false, // 树形选择器弹窗状态
      selectedTreeLabel: '', // 选中的树节点显示文本
      defaultExpandedKeys: [], // 默认展开的节点keys
      formData: {
        analysisLabelItemId: null, // 标签项ID
        analysisId: '', // 关联的标签组ID
        parentId: null, // 上级标签ID（字符串或null，最终提交给后端）
        analysisName: '', // 标签名称
        analysisCode: '', // 标签值
        analysisSort: 0, // 排序号
        analysisLevel: 1 // 层级，默认为1级
      },
      formRules: {
        analysisName: [
          { required: true, message: '请输入标签名称', trigger: ['change', 'blur'] },
          { max: 128, message: '标签名称长度不能超过128个字符', trigger: 'blur' }
        ],
        analysisCode: [
          { required: true, message: '请输入标签值', trigger: ['change', 'blur'] },
          { max: 128, message: '标签值长度不能超过128个字符', trigger: 'blur' }
        ],
        analysisSort: [
          { required: true, message: '请输入排序号', trigger: ['change', 'blur'] },
          { type: 'number', message: '排序号必须为数字', trigger: 'blur' }
        ]
      },
      treeProps: {
        label: 'analysisName',
        children: 'children'
      }
    }
  },

  computed: {
    // 动态设置抽屉标题
    drawerTitle() {
      return this.type === 'add' ? '新增标签项' : '编辑标签项'
    },
    // 处理树形数据，添加根节点并限制层级显示
    treeOptions() {
      const rootData = [{
        analysisLabelItemId: null,
        analysisName: '根节点',
        analysisLevel: 0,
        children: this.filterTreeLevel(this.treeData, 1) // 从一级节点开始处理
      }]
      return rootData
    }
  },

  watch: {
    type: {
      handler() {
        this.initFormData()
      },
      immediate: true
    },
    treeData: {
      handler() {
        if (this.type === 'edit' && this.formData.parentId !== null) {
          this.setTreeSelectedValue()
        }
        // 无论新增还是编辑，都设置默认展开第一层节点
        this.setDefaultExpandedKeys()
      },
      deep: true
    },
    treePopoverVisible: {
      handler(newVal) {
        if (newVal) {
          // 弹窗打开时，确保树形结构正确展开
          this.$nextTick(() => {
            this.setDefaultExpandedKeys()
          })
        }
      }
    }
  },

  methods: {
    // 设置默认展开的节点（第一层节点）
    setDefaultExpandedKeys() {
      const expandedKeys = []

      // 始终展开根节点
      expandedKeys.push(null)

      // 展开所有一级节点
      if (this.treeData && this.treeData.length > 0) {
        this.treeData.forEach(node => {
          expandedKeys.push(node.analysisLabelItemId)
        })
      }

      this.defaultExpandedKeys = expandedKeys
    },

    // 过滤树形结构：显示一级、二级节点，隐藏三级及以上节点
    filterTreeLevel(tree, level) {
      return tree.map(node => {
        const newNode = { ...node };
        if (newNode.children && newNode.children.length > 0) {
          if (level === 1) {
            // 一级节点：显示二级子节点，但不显示三级子节点
            newNode.children = this.filterTreeLevel(newNode.children, level + 1);
          } else if (level === 2) {
            // 二级节点：清空子节点，不显示三级
            newNode.children = [];
          }
        }
        return newNode;
      });
    },

    // 查找节点的层级
    findNodeLevel(tree, targetId) {
      for (const node of tree) {
        if (node.analysisLabelItemId === targetId) {
          return node.analysisLevel;
        }
        if (node.children && node.children.length) {
          const level = this.findNodeLevel(node.children, targetId);
          if (level !== null) return level;
        }
      }
      return null;
    },

    // 查找节点路径
    findNodePath(tree, targetId, path = []) {
      for (const node of tree) {
        if (node.analysisLabelItemId === targetId) {
          return [...path, node.analysisLabelItemId];
        }
        if (node.children && node.children.length) {
          const result = this.findNodePath(node.children, targetId, [...path, node.analysisLabelItemId]);
          if (result) return result;
        }
      }
      return null;
    },

    // 根据节点ID查找节点
    findNodeById(tree, targetId) {
      for (const node of tree) {
        if (node.analysisLabelItemId === targetId) {
          return node;
        }
        if (node.children && node.children.length) {
          const result = this.findNodeById(node.children, targetId);
          if (result) return result;
        }
      }
      return null;
    },

    // 设置树形选择器的值（编辑时回显）
    setTreeSelectedValue() {
      if (this.formData.parentId === null) {
        this.selectedTreeLabel = '根节点';
        this.formData.analysisLevel = 1;
        return;
      }

      const node = this.findNodeById(this.treeOptions, this.formData.parentId);
      if (node) {
        this.selectedTreeLabel = node.analysisName;
        const parentLevel = node.analysisLevel || 0;
        this.formData.analysisLevel = parentLevel + 1;

        // 设置默认展开的节点（包括选中节点的路径）
        const path = this.findNodePath(this.treeOptions, this.formData.parentId);
        if (path) {
          this.defaultExpandedKeys = [...new Set([...this.defaultExpandedKeys, ...path])];
        }
      }
    },

    // 初始化表单数据
    initFormData() {
      if (this.type === 'add') {
        this.formData = {
          analysisLabelItemId: null,
          analysisId: this.rowData.analysisId || '',
          parentId: null,
          analysisName: '',
          analysisCode: '',
          analysisSort: 0,
          analysisLevel: 1
        };

        // 设置新增时的默认选中
        if (this.rowData.parentId) {
          const node = this.findNodeById(this.treeOptions, this.rowData.parentId);
          if (node) {
            this.selectedTreeLabel = node.analysisName;
            const parentLevel = node.analysisLevel || 0;
            this.formData.analysisLevel = parentLevel + 1;
          }
        } else {
          this.selectedTreeLabel = '根节点';
        }
      } else {
        this.formData = { ...this.rowData };
        if (this.formData.parentId !== null) {
          this.formData.parentId = this.formData.parentId.toString();
        }
        this.setTreeSelectedValue();
      }

      // 设置默认展开的节点
      this.setDefaultExpandedKeys();

      this.$nextTick(() => {
        if (this.$refs.labelItemForm) {
          this.$refs.labelItemForm.resetFields();
        }
      });
    },

    // 处理树节点点击
    handleTreeNodeClick(data, node) {
      // 检查层级限制
      const currentLevel = data.analysisLevel || 0;
      if (currentLevel > 2) {
        this.$message.error('最多只能选择二级标签作为父级');
        return;
      }

      this.selectedTreeLabel = data.analysisName;
      this.formData.parentId = data.analysisLabelItemId !== null ? data.analysisLabelItemId.toString() : null;
      this.formData.analysisLevel = currentLevel + 1;

      // 关闭弹窗
      this.treePopoverVisible = false;
    },

    // 清除树选择
    handleTreeClear() {
      this.selectedTreeLabel = '';
      this.formData.parentId = null;
      this.formData.analysisLevel = 1;
      if (this.$refs.tree) {
        this.$refs.tree.setCurrentKey(null);
      }
    },

    // 保存表单
    async handleSave() {
      this.$refs.labelItemForm.validate(async (valid) => {
        if (!valid) return;

        this.showSaveAnimation = true;
        try {
          // 检查名称唯一性
          const uniqueParams = {
            analysisName: this.formData.analysisName,
            analysisId: this.formData.analysisId,
            analysisLabelItemId: this.type === 'edit' ? this.formData.analysisLabelItemId : ''
          };
          const uniqueRes = await checkLabelItemNameUnique(uniqueParams);
          // if (uniqueRes.data > 0) {
          //   this.$message.error('当前标签组下标签名称已存在');
          //   return;
          // }

          if (this.type === 'add') {
            await addAnalysisLabelItem(this.formData);
            this.$message.success('新增标签项成功');
          } else {
            await updateAnalysisLabelItem(this.formData);
            this.$message.success('编辑标签项成功');
          }

          this.$emit('save-success');
          this.$emit('refresh-tree');
          this.$emit('close');
        } catch (error) {
          this.$message.error(error.message || '操作失败，请重试');
        } finally {
          this.showSaveAnimation = false;
        }
      });
    },

    handleCancel() {
      this.$emit('close');
    },

    handleBeforeClose() {
      this.$emit('close');
    }
  }
}
</script>

<style scoped lang="scss">
.analysis-label-item-drawer {
  .el-drawer__header {
    padding: 16px 24px;
    margin: 0;
    font-size: 16px;
    font-weight: 600;
  }

  .el-drawer__body {
    padding: 0;
    overflow: hidden;
    display: flex;
    flex-direction: column;
    height: calc(100% - 56px);
  }

  .title-divider {
    height: 1px;
    background-color: #e8e8e8;
    width: 100%;
  }

  .footer-divider {
    height: 1px;
    background-color: #e8e8e8;
    width: 100%;
    margin-top: 480px;
  }

  .drawer-content {
    flex: 1;
    padding: 24px;
    overflow-y: auto;

    .form-container {
      margin-top: 8px;

      .el-form-item {
        margin-bottom: 20px;
      }
    }
  }

  .drawer-footer {
    padding: 20px 24px;
    display: flex;
    justify-content: flex-end;
    gap: 12px;
    background-color: #fff;
  }

  .tree-container {
    max-height: 300px;
    overflow: auto;
    padding: 8px 0;

    .limited-level-tree {
      // 隐藏三级节点的展开箭头
      ::v-deep .el-tree-node__children {
        .el-tree-node__children {
          .el-tree-node__expand-icon {
            display: none;
          }
        }
      }
    }
  }
}

// 下拉箭头旋转动画
.el-icon-arrow-down {
  transition: transform 0.3s;

  &.is-reverse {
    transform: rotate(180deg);
  }
}

.save-animation {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 100;
  display: flex;
  align-items: center;
  justify-content: center;

  .animation-mask {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(255, 255, 255, 0.7);
    backdrop-filter: blur(2px);
  }

  .animation-content {
    position: relative;
    text-align: center;
    background: #fff;
    padding: 30px 40px;
    border-radius: 12px;
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);

    .spinner {
      width: 40px;
      height: 40px;
      margin: 0 auto 16px;
      border: 4px solid #f3f3f3;
      border-top: 4px solid #1F72EA;
      border-radius: 50%;
      animation: spin 1s linear infinite;
    }

    .animation-text {
      font-size: 16px;
      color: #1F72EA;
      margin-bottom: 8px;
      font-weight: 500;
    }

    .animation-subtext {
      font-size: 14px;
      color: #666;
    }
  }
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}
</style>
