<template>
  <div>
    <!-- 添加预处理结果预览对话框 -->
    <el-drawer
      :title="currentId ? (isPreview ? '预览' : '编辑') + '知识题词规则' : '新增知识题词规则'"
      :visible.sync="dialogVisible"
      size="40%"
      :before-close="handleClose"
    >
      <div class="content">
        <el-form ref="ruleForm" :model="form" :rules="rules" label-width="100px">
          <div class="form-section">
            <div class="section-title">基本信息</div>
            <el-row :gutter="20">
              <el-col :span="isPreview ? 24 : 12">
                <el-form-item label="规则名称" prop="ruleName">
                  <el-input :disabled="isPreview" v-model="form.ruleName" placeholder="请输入规则名称"></el-input>
                </el-form-item>
              </el-col>
              <el-col v-if="!isPreview" :span="12">
                <el-select v-model="searchValue" @change="queryExistingRules" filterable clearable placeholder="查询并导入现有规则">
                  <el-option v-for="item in ruleList" :key="item.id" :label="item.ruleName" :value="item.id"> </el-option>
                </el-select>
              </el-col>
            </el-row>
            <p v-if="!isPreview" class="tips">支持中文、英文、数字、下划线(_)，50个字符以内，不能以下划线为开头</p>
            <el-form-item label="备注" prop="description">
              <el-input :disabled="isPreview" v-model="form.description" placeholder="请输入规则备注" type="textarea" />
            </el-form-item>
          </div>

          <div class="form-section" v-for="(rule, index) in form.ruleList" :key="index">
            <div class="section-title">
              拆分规则 {{ index + 1 }}
              <div>
                <el-button v-if="!isPreview && form.ruleList.length > 1" type="text" class="delete-btn" @click="removeRule(index)">
                  <i class="el-icon-delete"></i> 删除
                </el-button>
                <el-button v-if="!isPreview" type="text" class="copy-btn" @click="addValidationRules(index)">
                  <i class="el-icon-copy-document"></i> 复制
                </el-button>
              </div>
            </div>
            <el-form-item label="属性" :prop="'ruleList.' + index + '.attribute'">
              <el-input v-model="rule.attribute" placeholder="请输入属性" :disabled="isPreview"></el-input>
            </el-form-item>
            <el-form-item label="属性描述" :prop="'ruleList.' + index + '.attributeDesc'">
              <el-input v-model="rule.attributeDesc" placeholder="请输入属性描述" :disabled="isPreview"></el-input>
            </el-form-item>
            <el-form-item label="关键词" :prop="'ruleList.' + index + '.keyword'">
              <el-input v-model="rule.keyword" placeholder="请输入关键词" :disabled="isPreview"></el-input>
            </el-form-item>
            <el-form-item label="题词示例" :prop="'ruleList.' + index + '.example'">
              <el-input v-model="rule.example" placeholder="请输入题词示例" :disabled="isPreview"></el-input>
            </el-form-item>
            <el-form-item label="提示词" :prop="'ruleList.' + index + '.prompt'">
              <el-input v-model="rule.prompt" placeholder="请输入提示词" :disabled="isPreview"></el-input>
            </el-form-item>
          </div>
          <div class="add-rule-btn" v-if="!isPreview">
            <el-button type="primary" size="medium" @click="addSplitRule"> <i class="el-icon-plus"></i> 新增题词规则 </el-button>
          </div>
        </el-form>
      </div>
      <div class="drawer-footer" v-if="!isPreview">
        <el-button size="medium" @click="handleClose">取 消</el-button>
        <el-button type="primary" size="medium" @click="handleSubmit">保 存</el-button>
      </div>
    </el-drawer>
  </div>
</template>

<script>
import { addRuleExtract, getRuleDetail, updateRuleExtractSplit, getRulesList } from '@/api/generatedApi'

export default {
  name: 'AddRule',
  data() {
    return {
      isPreview: false,
      dialogVisible: false,
      currentId: null, // 当前编辑的规则ID
      form: {
        ruleName: '',
        ruleType: 2,
        ruleList: [
          {
            attribute: '',
            attributeDesc: '',
            keyword: '',
            example: '',
            prompt: ''
          }
        ]
      },
      ruleList: [],
      searchValue: '',
      options: [
        {
          value: 1,
          label: '一级标题'
        },
        {
          value: 2,
          label: '二级标题'
        },
        {
          value: 3,
          label: '三级标题'
        },
        {
          value: 4,
          label: '四级标题'
        },
        {
          value: 5,
          label: '五级标题'
        },
        {
          value: 6,
          label: '六级标题'
        }
      ],
      rules: {
        ruleName: [
          { required: true, message: '请输入规则名称', trigger: 'blur' },
          { max: 50, message: '长度不能超过50个字符', trigger: 'blur' },
          { pattern: /^(?!_)[a-zA-Z0-9\u4e00-\u9fa5_]+$/, message: '支持中文、英文、数字、下划线(_)，不能以下划线为开头', trigger: 'blur' }
        ],
        'ruleList.0.attribute': [{ required: true, message: '请输入属性' }],
        'ruleList.0.attributeDesc': [{ required: true, message: '请输入属性描述' }],
        'ruleList.0.keyword': [{ required: true, message: '请输入关键词' }],
        'ruleList.0.example': [{ required: true, message: '请输入题词示例' }],
        'ruleList.0.prompt': [{ required: true, message: '请输入提示词' }]
      }
    }
  },
  methods: {
    init(id, options = { preview: false }) {
      this.isPreview = options.preview

      this.dialogVisible = true
      this.getRuleList()
      this.currentId = id
      // 如果有id，则获取详情
      if (id) {
        this.getDetail(id)
      } else {
        // 重置表单
        this.$nextTick(() => {
          this.$refs.ruleForm && this.$refs.ruleForm.resetFields()
          this.form = {
            ruleName: '',
            ruleType: 2,
            ruleList: [
              {
                attribute: '',
                attributeDesc: '',
                keyword: '',
                example: '',
                prompt: ''
              }
            ]
          }
        })
      }
    },
    async getRuleList() {
      let res = await getRulesList({ ruleType: 2 })
      this.ruleList = res.content.content
    },
    // 获取详情
    getDetail(id) {
      getRuleDetail(id).then(res => {
        this.form = res.content.content
        // !this.currentId即新增
        if (!this.currentId) {
          this.form.ruleList.forEach(item => {
            Object.keys(item).forEach(key => {
              if (key !== 'attribute' && key !== 'attributeDesc' && key !== 'keyword' && key !== 'example' && key !== 'prompt') {
                delete item[key]
              }
            })
          })
        }
        // 为每个规则项添加验证规则
        this.form.ruleList.forEach((_, index) => {
          this.addValidationRules(index)
        })
      })
    },
    queryExistingRules(val) {
      // 查询并导入现有规则的逻辑
      if (val) {
        this.getDetail(val)
      }
    },
    // 动态添加验证规则
    addValidationRules(index) {
      const rules = this.rules
      rules[`ruleList.${index}.attribute`] = [{ required: true, message: '请输入属性', trigger: 'change' }]
      rules[`ruleList.${index}.attributeDesc`] = [{ required: true, message: '请输入属性描述', trigger: 'blur' }]
      rules[`ruleList.${index}.keyword`] = [{ required: true, message: '请输入关键词', trigger: 'change' }]
      rules[`ruleList.${index}.example`] = [{ required: true, message: '请输入题词示例', trigger: 'blur' }]
      rules[`ruleList.${index}.prompt`] = [{ required: true, message: '请输入提示词', trigger: 'change' }]
      this.rules = { ...rules }
    },
    // 复制
    copyRule(index) {
      const currentRule = this.form.ruleList[index]
      this.form.ruleList.push({
        ...currentRule
      })
      this.addValidationRules(this.form.ruleList.length - 1)
    },
    // 新增
    addSplitRule() {
      this.form.ruleList.push({
        ruleName: '',
        titleLevel: '',
        ruleRegex: '',
        description: ''
      })
      this.addValidationRules(this.form.ruleList.length - 1)
    },
    removeRule(index) {
      this.form.ruleList.splice(index, 1)
      // 重新生成所有验证规则
      const newRules = {
        ruleName: this.rules.ruleName
      }
      // 重新生成验证规则
      this.form.ruleList.forEach((_, newIndex) => {
        newRules[`ruleList.${newIndex}.attribute`] = [{ required: true, message: '请输入属性', trigger: 'change' }]
        newRules[`ruleList.${newIndex}.attributeDesc`] = [{ required: true, message: '请输入属性描述', trigger: 'blur' }]
        newRules[`ruleList.${newIndex}.keyword`] = [{ required: true, message: '请输入关键词', trigger: 'change' }]
        newRules[`ruleList.${newIndex}.example`] = [{ required: true, message: '请输入题词示例', trigger: 'blur' }]
        newRules[`ruleList.${newIndex}.prompt`] = [{ required: true, message: '请输入提示词', trigger: 'change' }]
      })
      this.rules = newRules
    },
    handleSubmit() {
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          // 表单验证通过，根据是否有id调用新增还是编辑接口
          const api = this.currentId ? updateRuleExtractSplit : addRuleExtract
          const params = {
            ...this.form,
            id: this.currentId // 编辑时带上id
          }
          api(params)
            .then(() => {
              this.$message.success(this.currentId ? '修改成功' : '新增成功')
              this.dialogVisible = false
              this.$emit('getDataList')
            })
            .catch(err => {
              this.$message.error((this.currentId ? '修改' : '新增') + '失败：' + err.message)
            })
        } else {
          this.$message.error('请填写完整所有必填项')
          return false
        }
      })
    },
    handleClose() {
      this.searchValue = ''
      this.$refs.ruleForm.resetFields()
      this.dialogVisible = false
    }
  }
}
</script>

<style scoped lang="scss">
.content {
  padding: 20px;
  height: calc(100vh - 120px);
  overflow-y: auto;

  .form-section {
    margin-bottom: 24px;
    padding: 16px;
    background: #f8f9fa;
    border-radius: 4px;

    .section-title {
      font-size: 16px;
      font-weight: 500;
      margin-bottom: 16px;
      color: #303133;
      display: flex;
      justify-content: space-between;
      align-items: center;

      .delete-btn {
        color: #f56c6c;
        font-size: 14px;

        &:hover {
          color: #f78989;
        }
      }
      .copy-btn {
        color: #70b936;
        font-size: 14px;

        &:hover {
          color: #70b936;
        }
      }
    }
  }

  .tips {
    font-size: 14px;
    color: #999;
    margin-left: 100px;
    margin-bottom: 20px;
  }

  .w100 {
    width: 300px;
  }

  .add-rule-btn {
    text-align: center;
    margin-top: 20px;
  }
}

.drawer-footer {
  position: absolute;
  bottom: 0;
  width: 100%;
  border-top: 1px solid #e8e8e8;
  padding: 10px 20px;
  text-align: right;
  background: #fff;
}
</style>
