<template>
  <div>
    <xy-dialog
      ref="dialog"
      :is-show.sync="isShow"
      type="form"
      :title="type === 'add' ? '新增表单' : '编辑表单'"
      :form="form"
      :rules="rules"
      @submit="submit"
    >
      <template v-slot:table_name>
        <div class="xy-table-item">
          <div class="xy-table-item-label">
            <span style="color: red; font-weight: 600; padding-right: 4px"
              >*</span
            >
            表名 ：
          </div>
          <div class="xy-table-item-content">
            <el-input
              v-model="form.table_name"
              clearable
              placeholder="请输入表名"
              style="width: 300px"
            ></el-input>
          </div>
        </div>
      </template>
      <template v-slot:name>
        <div class="xy-table-item">
          <div class="xy-table-item-label">
            <span style="color: red; font-weight: 600; padding-right: 4px"
              >*</span
            >
            名字 ：
          </div>
          <div class="xy-table-item-content">
            <el-input
              v-model="form.name"
              clearable
              placeholder="请输入名字"
              style="width: 300px"
            ></el-input>
          </div>
        </div>
      </template>
    </xy-dialog>
  </div>
</template>

<script>
import { show, save } from "@/api/system/customForm";
export default {
  props: {},
  data() {
    return {
      isShow: false,
      id: "",
      type: "",

      form: {
        table_name: "",
        name: "",
      },
      rules: {
        table_name: [
          {
            required: true,
            message: "请填写表名",
          },
          {
            pattern: /^[a-z_]+$/,
            message: '表名只能包含小写英文字母和下划线'
          },
          {
            validator: (rule, value, callback) => {
              function isPlural(word) {
                if (word.endsWith("s")) {
                  return true;
                } else if (word.endsWith("y")) {
                  const lastButOneChar = word.charAt(word.length - 2);
                  return !isVowel(lastButOneChar) && !lastButOneChar.includes("'");
                } else if (word.endsWith("fe") || word.endsWith("f")) {
                  const wordWithoutEnding = word.endsWith("fe") ? word.slice(0, -2) : word.slice(0, -1);
                  return !isVowel(wordWithoutEnding.charAt(wordWithoutEnding.length - 1));
                } else {
                  // irregular plurals
                  const irregulars = ["child", "children", "mouse", "mice"];
                  return irregulars.includes(word);
                }
              }

              function isVowel(char) {
                return ["a", "e", "i", "o", "u"].includes(char.toLowerCase());
              }
              if(isPlural(value)) {
                callback()
              }else {
                callback(new Error("请输入复数单词"))
              }
            },
            trigger: 'blur'
          }
        ],
        name: [
          {
            required: true,
            message: "请填写名字",
          },
        ],
      },
    };
  },
  methods: {
    show() {
      this.isShow = true;
    },
    hidden() {
      this.isShow = false;
    },
    setId(id) {
      if(typeof id == "number") {
        this.id = id;
      }else {
        console.error("error typeof id: " + typeof id)
      }
    },
    getId() {
      return this.id;
    },
    setType(type = 'add') {
      let types = ['add','editor']
      if(types.includes(type)) {
        this.type = type;
      }else{
        console.warn("Unknown type: " + type)
      }
    },
    init() {
      this.form = {
        table_name: "",
        name: "",
      };
    },
    setForm(key = [], value = []) {
      if (key instanceof Array) {
        key.forEach((key, index) => {
          this.form[key] = value[index] ?? "";
        });
      }
      if (typeof key === "string") {
        this.form[key] = value;
      }
      if (!key) {
        this.init();
      }
    },

    async getDetail() {
      const res = await show({ id: this.id });
      this.$integrateData(this.form, res);
    },

    submit() {
      if (this.type === "add") {
        if (this.form.hasOwnProperty("id")) {
          delete this.form.id;
        }
      }
      if (this.type === "editor") {
        Object.defineProperty(this.form, "id", {
          value: this.id,
          enumerable: true,
          configurable: true,
          writable: true,
        });
      }
      save(this.form).then((res) => {
        this.$message({
          type: "success",
          message: this.type === "add" ? "新增表单" : "编辑表单" + "成功",
        });
        this.isShow = false;
        this.$emit("refresh");
      });
    },
  },
  watch: {
    isShow(val) {
      if (val) {
        if (this.type === "editor") {
          this.getDetail();
        }
      } else {
        this.id = "";
        this.type = "";
        this.init();
        this.$refs["dialog"].clearValidate();
        delete this.form.id;
      }
    },
  },
};
</script>

<style scoped lang="scss">
::v-deep .el-input__inner {
  text-align: left;
}
</style>
