<script>
import { addSplitRule, getRuleDetail, updateSplitRule } from "@/api/rules/index";

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);
    },
    handleDelete() {
      // TODO: 删除数据到后端
      if (this.form.ruleList.length > 0) {
        this.form.ruleList.pop();
      }
    },
    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((res) => {
            this.dialogOptions.visible = false;

            // if (res.code >= 300) return;

            // 可以添加成功提示
            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 v-for="(item, index) in form.ruleList" :key="index" class="mt10">
        <template #header>
          <span>拆分规则 {{ index + 1 }}</span>
        </template>

        <el-form-item label="样式">
          <el-input v-model="item.titleLevel"></el-input>
        </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-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>
