<script>
import { addSplitRule, getRuleDetail, updateSplitRule } from '@/api/rules'

export default {
  name: 'EditSplitRule',
  data() {
    return {
      // 表单数据有：规则名称、样式、提示词、备注
      form: {
        id: '',
        ruleName: '',
        ruleType: 1,
        ruleList: []
      }
    }
  },
  props: {
    type: {
      type: String,
      default: 'edit'
    }
  },
  inject: ['dialogOptions', 'tableData'],
  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,
          ruleName: content.ruleName,
          ruleType: content.ruleType,
          ruleList: Array.isArray(content.ruleList) ? content.ruleList : []
        }
      })
      .catch(err => {
        console.error('获取规则详情失败:', err)
      })
  },

  methods: {
    handleAdd() {
      // TODO: 新增数据到后端
      const payload = {
        titleLevel: '',
        ruleRegex: '',
        description: ''
      }

      // 使用数组方法添加元素，确保响应式更新
      this.form.ruleList.push(payload)
    },
    /**
     * 删除拆分规则
     * @param index 拆分规则的索引, 默认删除最后一个
     */
    handleDelete(index) {
      // TODO: 删除数据到后端
      if (index !== undefined) {
        // 确保 index 是数字
        const numIndex = Number(index)
        if (!isNaN(numIndex)) {
          console.log(numIndex)
          const payload = this.form.ruleList.splice(numIndex, 1)
          console.log(...payload)
        }
      }
    },

    /**
     * 保存拆分规则
     */
    handleSave() {
      // 使用正确的API保存数据到后端
      console.log(`this.form`, this.form)

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

        addSplitRule(this.form)
          .then(() => {
            this.dialogOptions.visible = false

            // 可以添加成功提示
            this.$message && this.$message.success('保存成功')
            // 向 tableData 最上面添加数据
            this.tableData.unshift(this.form)
          })
          .catch(err => {
            console.error(`add split rule failed: ${err}`)
            // 可以添加错误提示
            this.$message && this.$message.error('保存失败')
          })
      } else {
        updateSplitRule(this.form)
          .then(() => {
            console.log('update split rule success')
            this.dialogOptions.visible = false
            // 可以添加成功提示
            this.$message && this.$message.success('保存成功')
          })
          .catch(err => {
            console.error(`update split rule failed: ${err}`)
            // 可以添加错误提示
            this.$message && this.$message.error('保存失败')
          })
      }
    }
  }
}
</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 shadow="hover" v-if="form.ruleList.length > 0">
        <el-tabs closable @tab-remove="handleDelete">
          <el-tab-pane
            v-for="(item, index) in form.ruleList"
            :name="index.toString()"
            :key="index"
            :label="item.ruleRegex ? item.ruleRegex : `未命名${index + 1}`"
          >
            <el-form-item label="样式">
              <el-select v-model="item.titleLevel" placeholder="请选择">
                <el-option v-for="level in 6" :key="level" :label="level" :value="level" />
              </el-select>
            </el-form-item>
            <el-form-item label="规则">
              <el-input v-model="item.ruleRegex"></el-input>
            </el-form-item>
            <el-form-item label="备注">
              <el-input type="textarea" v-model="item.description"></el-input>
            </el-form-item>
          </el-tab-pane>
        </el-tabs>
      </el-card>
    </el-form>
    <div slot="footer" class="dialog-footer flex mt15" style="justify-content: space-between;">
      <!-- 只有当点击保存的时候才能和服务端通信新增和删除 -->
      <div>
        <el-button type="primary" @click="handleAdd">+ 新增拆分</el-button>
        <el-button type="info" @click="handleDelete">- 删除拆分</el-button>
      </div>
      <div>
        <el-button @click="dialogOptions.visible = false">取 消</el-button>
        <el-button type="primary" @click="handleSave">确 定</el-button>
      </div>
    </div>
  </div>
</template>

<style lang="css" scoped></style>
