<script>
import { addPromptRule, getRuleDetail, updatePromptRule } from '@/api/rules/index'

export default {
  name: 'EditPromptRule',
  data() {
    return {
      // 规则名称、属性、属性描述、关键词、题词示例、提示词
      form: {
        id: '',
        ruleName: '',
        createdDate: '',
        ruleType: 2,
        ruleList: []
      }
    }
  },
  props: {
    type: {
      type: String,
      default: 'edit'
    }
  },
  inject: ['dialogOptions', 'tableData'],
  methods: {
    handleAdd() {
      const payload = {
        attribute: '',
        attributeDesc: '',
        keyword: '',
        example: '',
        prompt: ''
      }

      this.form.ruleList.push(payload)
    },
    /**
     * 删除数据列表
     * @param index {number} 删除的索引
     */
    handleDelete(index) {
      if (index !== undefined) {
        // 确保 index 是数字
        const numIndex = Number(index)
        if (!isNaN(numIndex)) {
          this.form.ruleList.splice(numIndex, 1)
        }
      }
    },
    save() {
      console.log('save this form ', this.form)

      // 判断是新增还是更新，新增调用 addPromptRule，更新调用 updatePromptRule
      if (this.type === 'add') {
        // 配置对应表单
        // 添加时，需要删除 id
        delete this.form.id
        // 删除 createdDate
        delete this.form.createdDate
        // 更新ruleType
        this.form.ruleType = 2

        addPromptRule(this.form)
          .then(() => {
            this.dialogOptions.visible = false
            // 可以添加成功提示
            this.$message && this.$message.success('保存成功')

            // 向 tableData 最上面添加数据
            this.tableData.unshift(this.form)
          })
          .catch(err => {
            console.error(`add prompt rule failed: ${err}`)
            // 可以添加错误提示
            this.$message && this.$message.error('保存失败')
          })
      } else {
        updatePromptRule(this.form)
          .then(() => {
            console.log('update prompt rule success')
            this.dialogOptions.visible = false
            // 可以添加成功提示
            this.$message && this.$message.success('保存成功')
          })
          .catch(err => {
            console.error(`update prompt rule failed: ${err}`)
            // 可以添加错误提示
            this.$message && this.$message.error('保存失败')
          })
      }
    }
  },
  beforeMount() {
    // 如果是新增，不去请求接口
    if (this.type === 'add') {
      return
    }
    // 获取当前行数据
    const { currentRow } = this.dialogOptions

    // 获取规则详情
    getRuleDetail(currentRow.id)
      .then(res => {
        const { content } = res.content
        console.log('origin query request', content)

        // 一次性设置表单数据，确保响应式更新
        this.form = {
          id: content.id || currentRow.id,
          ruleType: content.ruleType,
          ruleName: content.ruleName,
          createdDate: content.createdDate,
          ruleList: Array.isArray(content.ruleList) ? content.ruleList : []
        }
      })
      .catch(err => {
        console.error('获取规则详情失败:', err)
      })
  }
}
</script>

<template>
  <div>
    <el-form :model="form" label-width="100px">
      <el-form-item label="规则名称">
        <el-input v-model="form.ruleName"></el-input>
      </el-form-item>

      <el-card>
        <el-tabs closable @tab-remove="handleDelete">
          <el-tab-pane
            v-for="(item, index) in form.ruleList"
            :name="index.toString()"
            :key="index"
            :label="item.attribute ? item.attribute : `未命名${index + 1}`"
          >
            <el-form-item label="属性">
              <el-input v-model="item.attribute"></el-input>
            </el-form-item>
            <el-form-item label="属性描述">
              <el-input v-model="item.attributeDesc"></el-input>
            </el-form-item>
            <el-form-item label="关键词">
              <el-input v-model="item.keyword"></el-input>
            </el-form-item>
            <el-form-item label="题词示例">
              <el-input v-model="item.example"></el-input>
            </el-form-item>
            <el-form-item label="提示词">
              <el-input v-model="item.prompt"></el-input>
            </el-form-item>
            <el-form-item label="备注">
              <el-input type="textarea" v-model="item.attributeDesc"></el-input>
            </el-form-item>
          </el-tab-pane>
        </el-tabs>
      </el-card>
    </el-form>
    <div slot="footer" class="dialog-footer flex mt10" style="justify-content: space-between;">
      <div>
        <el-button :size="'mini'" type="primary" @click="handleAdd">+ 新增题词</el-button>
        <el-button type="info" :size="'mini'" @click="handleDelete">- 删除题词</el-button>
      </div>
      <div>
        <el-button :size="'mini'" @click="dialogOptions.visible = false">取 消</el-button>
        <el-button :size="'mini'" type="primary" @click="save">确 定</el-button>
      </div>
    </div>
  </div>
</template>
