<template>
  <div class="rule-exam part-box part-box-pad part-box-border">
    <h4 class="part-box-tips">变量印刷考务字段配置：</h4>
    <el-form
      ref="modalFormComp"
      :model="modalForm"
      :rules="rules"
      label-width="170px"
    >
      <el-form-item label="必选字段：" required>
        <el-checkbox
          v-for="field in modalForm.requiredFields"
          :key="field.code"
          v-model="field.enable"
          disabled
          >{{ field.name }}</el-checkbox
        >
      </el-form-item>
      <el-form-item label="扩展字段：">
        <div class="part-box part-box-pad part-box-border">
          <div class="label-edit">
            <div
              v-for="field in modalForm.extendFields"
              :key="field.code"
              class="label-item"
            >
              <el-checkbox
                v-model="field.enable"
                class="label-item-content"
                @change="validateExtendFields"
                >{{ field.name }}</el-checkbox
              >
              <i
                class="label-item-delete el-icon-error"
                @click="deleteField(field)"
              ></i>
            </div>
            <div class="label-add" @click="toAddField">
              <i class="el-icon-plus"></i><i>添加</i>
            </div>
          </div>
        </div>
      </el-form-item>
      <el-form-item prop="examNumberDigit" label="考号位数：" required>
        <el-input-number
          v-model="modalForm.examNumberDigit"
          :min="5"
          :max="15"
          :step="1"
          step-strictly
          :controls="false"
          style="width: 100px;"
        ></el-input-number>
      </el-form-item>
      <el-form-item label="是否启用入库审核：" required>
        <el-switch v-model="modalForm.review" inactive-color="#dcdfe6">
        </el-switch>
      </el-form-item>
      <el-form-item label="入库强制包含试卷：" required>
        <el-switch v-model="modalForm.includePaper" inactive-color="#dcdfe6">
        </el-switch>
        <p class="tips-info">
          注意：若入库时非强制包含试卷，适用于同时有课程要求打印试卷，有的课程不打印试卷的场景。因此，印刷计划里即使勾选了“试卷”，有试卷则打印，否则不打印。
        </p>
      </el-form-item>
      <el-form-item label="提交印刷方式：" required>
        <el-radio-group v-model="modalForm.printMethod">
          <el-radio
            v-for="(val, key) in CONFIRM_PRINT_TYPE"
            :key="key"
            :label="key"
            >{{ val }}</el-radio
          >
        </el-radio-group>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          :disabled="isSubmit"
          style="width: 140px"
          @click="submit"
          >保存</el-button
        >
      </el-form-item>
    </el-form>

    <!-- ModifyField -->
    <modify-field ref="ModifyField" @confirm="addField"></modify-field>
  </div>
</template>

<script>
import ModifyField from "../components/ModifyField";
import { CONFIRM_PRINT_TYPE } from "@/constants/enumerate";
import { examRuleDetail, saveExamRule } from "../api";
import { getEnums } from "../../login/api";

const initModalForm = {
  id: null,
  review: true,
  includePaper: true,
  examNumberDigit: 8,
  printMethod: "AUTO",
  requiredFields: "[]",
  extendFields: "[]"
};

export default {
  name: "rule-exam",
  components: { ModifyField },
  data() {
    return {
      modalForm: { ...initModalForm },
      isSubmit: false,
      CONFIRM_PRINT_TYPE,
      rules: {
        examNumberDigit: [
          {
            required: true,
            message: "请输入考号位数",
            trigger: "change"
          }
        ]
      }
    };
  },
  mounted() {
    this.init();
  },
  methods: {
    async init() {
      const requiredFields = await getEnums("REQUIRED_FIELDS");
      const examRule = await examRuleDetail();
      this.modalForm = Object.assign({}, initModalForm, examRule || {});
      this.modalForm.examNumberDigit =
        this.modalForm.examNumberDigit || initModalForm.examNumberDigit;

      this.modalForm.requiredFields = requiredFields.map(item => {
        return {
          code: item.code,
          name: item.desc,
          enable: true
        };
      });
      // console.log(this.modalForm.extendFields);
      this.modalForm.extendFields = JSON.parse(this.modalForm.extendFields);
    },
    validateRequiredFields() {
      this.$refs.modalFormComp.validateField("requiredFields");
    },
    validateExtendFields() {
      this.$refs.modalFormComp.validateField("extendFields");
    },
    toAddField() {
      this.$refs.ModifyField.open();
    },
    addField(field) {
      this.modalForm.extendFields.push({ ...field });
    },
    deleteField(field) {
      const index = this.modalForm.extendFields.findIndex(
        item => item.code === field.code
      );
      if (index !== -1) this.modalForm.extendFields.splice(index, 1);
      this.validateExtendFields();
    },
    async submit() {
      const valid = await this.$refs.modalFormComp.validate().catch(() => {});
      if (!valid) return;

      if (this.isSubmit) return;
      this.isSubmit = true;
      let datas = {
        ...this.modalForm
      };
      datas.requiredFields = JSON.stringify(datas.requiredFields);
      datas.extendFields = JSON.stringify(datas.extendFields);
      const data = await saveExamRule(datas).catch(() => {});
      this.isSubmit = false;
      if (!data) return;

      this.modalForm.id = data;

      this.$message.success("保存成功！");
    }
  }
};
</script>
