<template>
  <div class="edit-paper-props">
    <el-form
      v-if="modalForm"
      ref="modalFormComp"
      :key="modalForm.id"
      :model="modalForm"
      :rules="rules"
      label-width="100px"
    >
      <el-form-item
        v-for="item in instance.props"
        :key="item.field"
        :label="`${item.name}：`"
        :prop="item.field"
      >
        <el-checkbox v-model="modalForm[item.field].enable"> 启用 </el-checkbox>
        <el-input
          v-if="modalForm[item.field].enable && item.field === 'paperType'"
          v-model.trim="modalForm[item.field].optionContent"
          maxlength="5"
          placeholder="请输入分类信息"
        ></el-input>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
export default {
  name: "EditPaperProps",
  props: {
    instance: {
      type: Object,
      default() {
        return {};
      },
    },
  },
  data() {
    return {
      modalForm: null,
      rules: {
        paperType: {
          validator: (rule, value, callback) => {
            if (!this.modalForm.paperType.enable) return callback();

            const optionContent = this.modalForm.paperType.optionContent;
            if (optionContent && /^[A-Z]{1,5}$/.test(optionContent)) {
              const optionSet = new Set(optionContent.split(""));
              if (optionSet.size !== optionContent.length) {
                return callback(new Error("试卷类型字母重复"));
              } else {
                return callback();
              }
            }

            return callback(
              new Error("试卷类型只能是大写字母，数量不能超过5个")
            );
          },
          trigger: "change",
        },
      },
    };
  },
  mounted() {
    let modalForm = {};
    this.instance.props.forEach((item) => {
      modalForm[item.field] = {
        ...item,
        optionContent: item.options && item.options.join(""),
      };
    });
    this.modalForm = modalForm;
  },
  methods: {
    async submit() {
      const valid = await this.$refs.modalFormComp.validate().catch(() => {});
      if (!valid) return;

      let data = { ...this.instance };
      data.props = data.props.map((item) => {
        let nitem = this.$objAssign(item, this.modalForm[item.field]);
        if (item.options)
          nitem.options = this.modalForm[item.field].optionContent.split("");
        return nitem;
      });
      this.$emit("modified", data);
    },
  },
};
</script>
