<template>
  <div class="edit-explain">
    <el-form
      ref="modalFormComp"
      :model="modalForm"
      :rules="rules"
      :key="modalForm.id"
      label-width="100px"
    >
      <el-form-item prop="topicName" label="题目名称：">
        <el-input
          v-model.trim="modalForm.topicName"
          type="textarea"
          :autosize="{ minRows: 2, maxRows: 5 }"
          resize="none"
          placeholder="请输入题目名称"
          clearable
        ></el-input>
      </el-form-item>
      <el-form-item prop="startEnd" label="起止题号：">
        <el-input-number
          style="width:40px;"
          v-model="modalForm.startNumber"
          :min="0"
          :max="999"
          :step="1"
          step-strictly
          :controls="false"
        ></el-input-number>
        <span class="el-input-split"></span>
        <el-input-number
          style="width:40px;"
          v-model="modalForm.endNumber"
          :min="0"
          :max="999"
          :step="1"
          step-strictly
          :controls="false"
        ></el-input-number>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
const initModalForm = {
  id: "",
  topicName: "",
  startNumber: 1,
  endNumber: 4,
  questionsCount: 4
};

export default {
  name: "edit-explain",
  props: {
    instance: {
      type: Object,
      default() {
        return {};
      }
    }
  },
  data() {
    const numberRangeValidater = (rule, value, callback) => {
      if (!this.modalForm.startNumber || !this.modalForm.endNumber) {
        return callback(new Error("请输入起止题号"));
      }
      if (this.modalForm.startNumber > this.modalForm.endNumber) {
        callback(new Error("开始题号不能大于结束题号"));
      } else {
        callback();
      }
    };
    return {
      modalForm: { ...initModalForm },
      rules: {
        topicName: [
          {
            required: true,
            message: "请输入题目名称",
            trigger: "change"
          }
        ],
        endNumber: [
          {
            required: true,
            message: "请输入起止题号",
            trigger: "change"
          },
          {
            type: "number",
            validator: numberRangeValidater,
            trigger: "change"
          }
        ]
      }
    };
  },
  mounted() {
    this.initData(this.instance);
  },
  methods: {
    initData(val) {
      const valInfo = val.parent || val;
      this.modalForm = { ...valInfo };
      this.modalForm.endNumber =
        this.modalForm.startNumber + this.modalForm.questionsCount - 1;
    },
    async submit() {
      const valid = await this.$refs.modalFormComp.validate().catch(() => {});
      if (!valid) return;

      this.modalForm.questionsCount =
        this.modalForm.endNumber - this.modalForm.startNumber + 1;
      console.log(this.modalForm);
      this.$emit("modified", this.modalForm);
    }
  }
};
</script>
