<template>
  <!-- 右侧弹出抽屉 -->
  <el-drawer
    title="规则详情"
    :visible="value"
    :direction="'rtl'"
    :size="800"
    @close="handleClose"
    :append-to-body="true"
  >
    <div class="analysis-rule-container" style="height: calc(100vh - 140px); overflow-y: auto;">
      <el-row :gutter="20">
        <!-- 右侧解析规则配置区域（去除左侧树状图） -->
        <el-col :span="24">
          <div class="rule-config-container">
            <!-- 标签切换（禁用切换功能） -->
            <el-tabs v-model="currentTab" @tab-click.prevent="handleTabClick">
              <el-tab-pane label="规则配置" name="ruleConfig"></el-tab-pane>
              <el-tab-pane label="提示词配置" name="promptConfig"></el-tab-pane>
            </el-tabs>

            <!-- 规则配置内容 -->
            <div v-if="currentTab === 'ruleConfig'">
              <el-form ref="ruleForm" :model="ruleForm" label-width="100px" class="rule-sets">
                <!-- 规则集列表 -->
                <div v-for="(ruleSet, index) in ruleSets" :key="index" class="rule-set-item">
                  <div class="rule-set-header">
                    <span class="rule-set-index">规则 {{ index + 1 }}</span>
                  </div>

                  <div class="rule-set-content">
                    <!-- 内容来源单选（禁用切换） -->
                    <el-form-item label="内容来源">
                      <el-radio-group
                        v-model="ruleSet.selectedCompositionId"
                        class="content-source-radios"
                        @click.prevent
                        @change.prevent
                      >
                        <el-radio
                          v-for="source in contentSources"
                          :key="source.compositionId"
                          :label="source.compositionId"
                        >
                          {{ source.compositionName }}
                        </el-radio>
                      </el-radio-group>
                    </el-form-item>

                    <!-- 定位查询规则 -->
                    <div class="position-rules">
                      <el-form-item label="定位规则查询" class="position-rule-label">
                      </el-form-item>
                      <div v-for="(positionRule, posIndex) in ruleSet.positionRules" :key="posIndex" class="position-rule-item">
                        <el-form-item>
                          <!-- 规则类型选择下拉框（禁用选择） -->
                          <el-select
                            v-model="positionRule.ruleSetType"
                            @change.prevent="handleRuleTypeChange(positionRule, posIndex, index)"
                            placeholder="请选择规则类型"
                            style="width: 280px;"
                            @click.prevent
                          >
                            <el-option
                              v-for="option in ruleSetTypeOptions"
                              :key="option.value"
                              :label="option.label"
                              :value="option.value"
                            ></el-option>
                          </el-select>

                          <!-- 规则类型对应的字段（输入框添加readonly） -->
                          <div class="rule-fields" v-if="positionRule.ruleSetType === 'headSpecifyLength'">
                            <el-input
                              v-model="positionRule.specifiedWordCount"
                              placeholder="指定字数"
                              type="number"
                              style="width: 150px; margin-left: 10px;"
                              readonly
                            ></el-input>
                          </div>

                          <div class="rule-fields" v-if="positionRule.ruleSetType === 'docToSpecifyText'">
                            <el-input
                              v-model="positionRule.specifiedText"
                              placeholder="指定文字"
                              style="width: 200px; margin-left: 10px;"
                              readonly
                            ></el-input>
                          </div>

                          <div class="rule-fields" v-if="positionRule.ruleSetType === 'tailSpecifyLength'">
                            <el-input
                              v-model="positionRule.specifiedWordCount"
                              placeholder="指定字数"
                              type="number"
                              style="width: 150px; margin-left: 10px;"
                              readonly
                            ></el-input>
                          </div>

                          <div class="rule-fields" v-if="positionRule.ruleSetType === 'specifyTextToEnd'">
                            <el-input
                              v-model="positionRule.specifiedText"
                              placeholder="指定文字"
                              style="width: 200px; margin-left: 10px;"
                              readonly
                            ></el-input>
                          </div>

                          <div class="rule-fields" v-if="positionRule.ruleSetType === 'keywordAround'">
                            <el-input
                              v-model="positionRule.beforeCharactersNum"
                              placeholder="前面字数"
                              type="number"
                              style="width: 120px; margin-left: 10px;"
                              readonly
                            ></el-input>
                            <el-input
                              v-model="positionRule.specifiedKeywords"
                              placeholder="指定关键词"
                              style="width: 180px; margin-left: 10px;"
                              readonly
                            ></el-input>
                            <el-input
                              v-model="positionRule.afterCharactersNum"
                              placeholder="后面字数"
                              type="number"
                              style="width: 120px; margin-left: 10px;"
                              readonly
                            ></el-input>
                          </div>

                          <div class="rule-fields" v-if="positionRule.ruleSetType === 'specifyTextToLength'">
                            <el-input
                              v-model="positionRule.specifiedText"
                              placeholder="指定文字"
                              style="width: 200px; margin-left: 10px;"
                              readonly
                            ></el-input>
                            <el-input
                              v-model="positionRule.specifiedWordCountLength"
                              placeholder="指定字数长度"
                              type="number"
                              style="width: 150px; margin-left: 10px;"
                              readonly
                            ></el-input>
                          </div>

                          <div class="rule-fields" v-if="positionRule.ruleSetType === 'specifyTextEndToLength'">
                            <el-input
                              v-model="positionRule.beforeSpecifiedCharactersNum"
                              placeholder="指定文字前方字数"
                              type="number"
                              style="width: 180px; margin-left: 10px;"
                              readonly
                            ></el-input>
                            <el-input
                              v-model="positionRule.specifiedText"
                              placeholder="指定文字"
                              style="width: 200px; margin-left: 10px;"
                              readonly
                            ></el-input>
                          </div>

                          <div class="rule-fields" v-if="positionRule.ruleSetType === 'headTailRange'">
                            <el-input
                              v-model="positionRule.firstText"
                              placeholder="首部文字"
                              style="width: 150px; margin-left: 10px;"
                              readonly
                            ></el-input>
                            <el-input
                              v-model="positionRule.shouldIncludeCharactersNum"
                              placeholder="需要包含的字数"
                              type="number"
                              style="width: 150px; margin-left: 10px;"
                              readonly
                            ></el-input>
                            <el-input
                              v-model="positionRule.endText"
                              placeholder="尾部文字"
                              style="width: 150px; margin-left: 10px;"
                              readonly
                            ></el-input>
                          </div>
                        </el-form-item>
                      </div>
                    </div>
                  </div>
                </div>
              </el-form>
            </div>

            <!-- 提示词配置内容 -->
            <div v-if="currentTab === 'promptConfig'">

              <!-- 提示词文本框（添加readonly） -->
              <el-input
                v-model="promptWord"
                type="textarea"
                rows="15"
                placeholder="请输入提示词内容"
                style="width: 100%;"
                readonly
              ></el-input>
            </div>
          </div>
        </el-col>
      </el-row>
    </div>
    <div class="back-container">
      <el-button
        type="default"
        size="small"
        @click="handleClose"
        class="back-btn"
      >
        关闭
      </el-button>
    </div>
  </el-drawer>
</template>

<script>
import {
  listAnalysisRuleSetHistory  // 替换为历史版本接口
} from '@/api/template/analysisRuleSet/analysisRuleSet'
import { getTemplateInfoDetail } from '@/api/template/templateInfo/templateInfo'

export default {
  name: 'RuleDetailDrawer',
  props: {
    // 控制抽屉显示/隐藏
    value: {
      type: Boolean,
      default: false
    },
    // 从父组件接收的分析标签项ID（来自树状图点击）
    analysisLabelItemId: {
      type: [String, Number],
      default: ''
    },
    // 当前选中的版本号
    currentVersion: {
      type: String,
      default: ''
    },
    // 模板ID
    templateId: {
      type: [String, Number],
      default: ''
    }
  },
  data() {
    return {
      promptWord: '',
      ruleForm: {},

      // 标签页状态
      currentTab: 'ruleConfig',

      // 内容来源列表
      contentSources: [],

      // 规则集数据
      ruleSets: [],
      // 规则类型选项
      ruleSetTypeOptions: []
    }
  },
  watch: {
    // 当抽屉显示时，检查并加载数据
    value(newVal) {
      console.log('newVal', newVal)
      if (newVal) {
        // 使用 $nextTick 确保所有 props 都已同步更新
        this.$nextTick(() => {
          if (this.analysisLabelItemId && this.currentVersion && this.templateId) {
            console.log('开始加载规则详情数据')
            this.loadData();
          } else {
            console.warn('打开抽屉失败：缺少必要的参数。', {
              analysisLabelItemId: this.analysisLabelItemId,
              currentVersion: this.currentVersion,
              templateId: this.templateId
            });
          }
        });
      } else {
        // 当抽屉关闭时，保持数据（下次打开可快速显示）
      }
    },
    // 监听所有props变化，确保参数更新时重新加载数据
    '$props': {
      handler() {
        if (this.value && this.analysisLabelItemId && this.currentVersion && this.templateId) {
          this.loadData();
        }
      },
      deep: true
    }
  },
  methods: {
    // 关闭抽屉
    handleClose() {
      this.$emit('input', false);
      this.$emit('update:visible', false);
      this.$emit('close');
    },

    // 加载数据
    loadData() {
      // 先加载模板信息获取内容来源
      this.loadTemplateInfo().then(() => {
        // 再加载历史规则集数据
        this.loadRuleSets();
      });

      // 加载规则类型字典
      this.loadRuleSetTypeDict();
    },

    // 加载规则类型字典表数据
    loadRuleSetTypeDict() {
      this.getDicts('rule_set_type').then(response => {
        this.ruleSetTypeOptions = response.data.map(item => ({
          label: item.dictLabel,
          value: item.dictValue
        }));
      }).catch(error => {
        console.error('加载查询规则类型字典失败：', error);
      });
    },

    // 加载模板信息获取内容来源
    loadTemplateInfo() {
      return new Promise((resolve) => {
        if (this.templateId) {
          getTemplateInfoDetail({ templateId: this.templateId })
            .then(res => {
              if (res.code === 200) {
                const compositionList = res.data.compositionList || [];

                // 去重处理内容来源
                const uniqueSources = [];
                const seenIds = new Set();
                compositionList.forEach(source => {
                  if (source.compositionId && !seenIds.has(source.compositionId)) {
                    seenIds.add(source.compositionId);
                    uniqueSources.push({
                      compositionId: source.compositionId,
                      compositionName: source.fileName
                    });
                  }
                });
                this.contentSources = uniqueSources;
              }
              resolve();
            })
            .catch(err => {
              console.error('加载模板信息失败:', err);
              resolve();
            });
        } else {
          resolve();
        }
      });
    },

    // 加载历史规则集（核心修改：使用历史版本接口）
    loadRuleSets() {
      if (this.analysisLabelItemId && this.templateId && this.currentVersion) {
        console.log('currentVersion', this.currentVersion)
        listAnalysisRuleSetHistory({
          templateId: this.templateId,
          analysisLabelItemId: this.analysisLabelItemId,
          currentVersion: this.currentVersion  // 增加版本号参数
        }).then(res => {
          console.log('历史规则集数据:', res);
          if (res.code === 200) {
            this.ruleSets = [];
            this.promptWord = res.rows.length > 0 ? (res.rows[0].promptWord || '') : '';

            res.rows.forEach(ruleSet => {
              (ruleSet.subRules || []).forEach(subRule => {
                let sourceObj = { compositionId: '', compositionName: '' };
                if (subRule.compositionId) {
                  const foundSource = this.contentSources.find(
                    s => s.compositionId === subRule.compositionId
                  );
                  sourceObj = foundSource ? foundSource : {
                    compositionId: subRule.compositionId,
                    compositionName: subRule.compositionName || '未知来源'
                  };
                } else if (this.contentSources.length > 0) {
                  sourceObj = this.contentSources[0];
                }

                // 过滤出当前子规则的定位规则
                const subRulePositions = (ruleSet.positions || []).filter(
                  pos => pos.subRuleId === subRule.subRuleId
                );

                const ruleSetItem = {
                  ruleSetId: ruleSet.ruleSetId,
                  subRuleId: subRule.subRuleId,
                  ruleResourceId: subRule.ruleResourceId,
                  contentSource: sourceObj,
                  selectedCompositionId: subRule.compositionId,
                  positionRules: subRulePositions.length > 0
                    ? subRulePositions.map(pos => ({ ...pos }))
                    : []
                };

                this.ruleSets.push(ruleSetItem);
              });
            });
          }
        }).catch(err => {
          console.error('加载历史规则集失败:', err);
        });
      }
    },

    // 规则类型改变事件（仅用于初始化数据格式）
    handleRuleTypeChange(positionRule) {
      const allFields = [
        'specifiedWordCount', 'specifiedText', 'specifiedKeywords',
        'beforeCharactersNum', 'afterCharactersNum', 'specifiedWordCountLength',
        'beforeSpecifiedCharactersNum', 'firstText', 'shouldIncludeCharactersNum', 'endText'
      ];

      allFields.forEach(field => {
        if (!positionRule.hasOwnProperty(field)) {
          this.$set(positionRule, field, '');
        }
      });
    },

    // 标签切换事件处理（因@tab-click.prevent，实际不会触发切换）
    handleTabClick(tab) {
      this.currentTab = tab.name;
    },

    // 以下方法仅保留空实现（按钮点击被prevent）
    handleLabelIdClick() {},
    handleLabelNameClick() {},
    handleSegmentIdClick() {},
    handleSegmentNameClick() {},
    handleExtractedContentClick() {}
  }
}
</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-rule-container {
  height: calc(100vh - 250px);
  overflow: hidden;
  padding: 16px;
}

// 规则配置区域样式
.rule-config-container {
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  padding: 20px;
  height: calc(100% - 40px);
  overflow-y: auto;
  box-sizing: border-box;
}

.rule-sets {
  ::v-deep .el-form-item {
    margin-bottom: 15px;
  }

  ::v-deep .el-form-item__label {
    text-align: left;
    color: #303133 !important; // 确保标签文字颜色正常
  }
}

.rule-set-item {
  background: #fff;
  border-radius: 6px;
  padding: 15px;
  margin-bottom: 20px;
  position: relative;
  border: 1px solid #f0f0f0;
}

.rule-set-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px dashed #e0e0e0;

  .rule-set-index {
    font-weight: bold;
    color: #333;
  }
}

.rule-set-content {
  margin-top: 15px;
}

.content-source-radios {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
  margin-top: 5px;
}

// 确保单选框样式正常
::v-deep .el-radio {
  cursor: default !important; // 鼠标指针改为默认，提示不可交互
}
::v-deep .el-radio__label {
  color: #303133 !important;
  opacity: 1 !important;
}
::v-deep .el-radio__input.is-checked .el-radio__inner {
  background-color: #409EFF !important;
  border-color: #409EFF !important;
}

// 确保下拉框样式正常
::v-deep .el-select {
  cursor: default !important;
}
::v-deep .el-select__inner {
  color: #303133 !important;
  border-color: #dcdfe6 !important;
  background-color: #fff !important;
  opacity: 1 !important;
}
::v-deep .el-select__icon {
  color: #c0c4cc !important;
}

// 确保输入框（readonly）样式正常
::v-deep .el-input__inner[readonly] {
  color: #303133 !important;
  border-color: #dcdfe6 !important;
  background-color: #fff !important;
  opacity: 1 !important;
  cursor: default !important;
}

.position-rules {
  margin-top: 15px;
}

.position-rule-item {
  margin-bottom: 15px;
  background: #fff;
  padding: 10px;
  border-radius: 4px;
}

.position-rule-item ::v-deep .el-form-item__content {
  margin-left: 0 !important;
}

.rule-fields {
  display: inline-flex;
  align-items: center;
  margin-top: 10px;
}

.button-group {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  padding: 10px 0;
  margin-bottom: 15px;
}

.info-button {
  min-width: 120px;
  cursor: default !important; // 鼠标指针改为默认
  background-color: #ecf5ff !important;
  border-color: #b3d8ff !important;
  color: #409EFF !important;
}
// 禁用按钮hover效果（可选）
::v-deep .el-button.info-button:hover {
  background-color: #ecf5ff !important;
  border-color: #b3d8ff !important;
  color: #409EFF !important;
}
</style>
