<template>
  <div>
    <el-dialog
      class="modify-card-rule"
      :visible.sync="modalIsShow"
      :title="title"
      top="10px"
      width="950px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      append-to-body
      @open="visibleChange"
    >
      <el-form
        ref="modalFormComp"
        label-width="130px"
        :rules="rules"
        :model="modalForm"
      >
        <el-form-item prop="name" label="题卡规则名称：">
          <el-input
            v-model.trim="modalForm.name"
            placeholder="建议不超过30个字，规则名称不允许重复"
            style="width: 100%"
            clearable
            :disabled="!editable"
          ></el-input>
        </el-form-item>
        <el-form-item prop="remark" label="备注：">
          <el-input
            v-model="modalForm.remark"
            type="textarea"
            resize="none"
            :rows="2"
            :maxlength="50"
            :disabled="!editable"
            clearable
            show-word-limit
            placeholder="建议不超过50个字"
          ></el-input>
        </el-form-item>
        <el-form-item
          prop="examNumberStyle"
          label="学号版式："
          class="inline-block"
        >
          <el-select
            v-model="modalForm.examNumberStyle"
            style="width: 142px"
            placeholder="请选择"
            :disabled="!editable"
            @change="numStyleChange"
          >
            <el-option
              v-for="(val, key) in EXAM_NUMBER_STYLE"
              :key="key"
              :value="key"
              :label="val"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          v-if="isFillModel"
          prop="examNumberDigit"
          label="学号位数："
          class="inline-block"
        >
          <el-input-number
            v-model="modalForm.examNumberDigit"
            :min="5"
            :max="15"
            :step="1"
            step-strictly
            :controls="false"
            style="width: 100px"
            disabled
          ></el-input-number>
        </el-form-item>
        <el-form-item prop="paperType" label="AB卷版式：">
          <el-select
            v-model="modalForm.paperType"
            style="width: 142px"
            placeholder="请选择"
            :disabled="!editable || modalForm.examNumberStyle !== 'PASTE'"
          >
            <el-option
              v-for="(val, key) in PAPER_TYPE"
              :key="key"
              :value="key"
              :label="val"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-checkbox v-model="modalForm.examAbsent" :disabled="!editable"
            >启用“缺考填涂”</el-checkbox
          >
          <el-checkbox v-model="modalForm.discipline" :disabled="!editable"
            >启用“违纪填涂”</el-checkbox
          >
          <el-checkbox
            v-model="modalForm.writeSign"
            :disabled="isFillModel || !editable"
            >启用“手写签名”</el-checkbox
          >
          <el-checkbox v-model="modalForm.undertakingEnable"
            >启用“考生承诺书”</el-checkbox
          >
          <el-button
            v-if="modalForm.undertakingEnable"
            type="text"
            class="btn-primary ml-2"
            @click="toEditUndertaking"
            >编辑</el-button
          >
        </el-form-item>
        <el-form-item
          prop="defaultOptionNumber"
          label="单选题/多选题选项默认个数："
          label-width="220px"
        >
          <el-input-number
            style="width: 125px"
            v-model="modalForm.defaultOptionNumber"
            :min="2"
            :max="22"
            :step="1"
            step-strictly
            :controls="false"
          ></el-input-number>
        </el-form-item>
        <div class="part-box part-box-pad part-box-border">
          <h4 class="part-box-tips">题卡版头变量印刷字段配置：</h4>
          <el-form-item label="必选字段：" label-width="115px" required>
            <el-checkbox
              v-for="column in modalForm.requiredFields"
              :key="column.code"
              v-model="column.enable"
              disabled
              >{{ column.name }}</el-checkbox
            >
          </el-form-item>
          <el-form-item label="扩展字段：" label-width="115px">
            <el-checkbox
              v-for="column in modalForm.extendFields"
              :key="column.code"
              v-model="column.enable"
              :disabled="!editable"
              @change="updateFillFields"
              >{{ column.name }}</el-checkbox
            >
          </el-form-item>
          <el-form-item
            v-if="isFillModel"
            label="变量填充字段："
            label-width="115px"
          >
            <el-checkbox-group v-model="modalForm.fillFields">
              <el-checkbox
                v-for="column in selectedFields"
                :key="column.code"
                :label="column.code"
                >{{ column.name }}</el-checkbox
              >
            </el-checkbox-group>
          </el-form-item>
        </div>
        <el-form-item prop="titleRule" label="题卡标题规则：">
          <card-title-rule-edit
            v-model="modalForm.titleRule"
            :disabled="!editable"
            :field-sourses="fieldSourses"
          ></card-title-rule-edit>
        </el-form-item>
        <el-form-item prop="firstLevelSubheading" label="一级副标题：">
          <card-title-rule-edit
            v-model="modalForm.firstLevelSubheading"
            :disabled="!editable"
            :field-sourses="subTitleFieldSources"
          ></card-title-rule-edit>
        </el-form-item>
        <el-form-item prop="secondLevelSubheading" label="二级副标题：">
          <card-title-rule-edit
            v-model="modalForm.secondLevelSubheading"
            :disabled="!editable"
            :field-sourses="subTitleFieldSources"
          ></card-title-rule-edit>
        </el-form-item>
        <el-form-item prop="attention" label="注意事项：">
          <el-input
            type="textarea"
            :rows="4"
            v-model="modalForm.attention"
            :disabled="!editable"
          ></el-input>
          <p class="tips-info">
            提示：换行之后，题卡注意事项会展示为多条内容，内容序号会被自动添加。
          </p>
        </el-form-item>
        <el-form-item prop="objectiveAttention" label="客观题注意事项：">
          <el-input
            v-model.trim="modalForm.objectiveAttention"
            :disabled="!editable"
          ></el-input>
        </el-form-item>
        <el-form-item prop="subjectiveAttention" label="主观题注意事项：">
          <el-input
            v-model.trim="modalForm.subjectiveAttention"
            :disabled="!editable"
          ></el-input>
        </el-form-item>
      </el-form>

      <div slot="footer">
        <el-button
          v-if="editable"
          type="primary"
          :disabled="isSubmit"
          @click="submit"
          >确认</el-button
        >
        <el-button @click="cancel">取消</el-button>
      </div>
    </el-dialog>

    <!-- ModifyCardRuleUndertaking -->
    <modify-card-rule-undertaking
      ref="ModifyCardRuleUndertaking"
      v-model="modalForm.undertakingBody"
    ></modify-card-rule-undertaking>
  </div>
</template>

<script>
import { EXAM_NUMBER_STYLE, PAPER_TYPE } from "@/constants/enumerate";
import { saveCardRule } from "../api";
import CardTitleRuleEdit from "./CardTitleRuleEdit";
import ModifyCardRuleUndertaking from "./ModifyCardRuleUndertaking.vue";
import { UNDERTAKING_BODY } from "../../../../card/enumerate";

const initModalForm = {
  id: null,
  name: "",
  remark: "",
  examNumberStyle: "",
  examNumberDigit: 10,
  containsLetter: false,
  relationList: "[]",
  defaultOptionNumber: 4,
  paperType: "PRINT",
  examAbsent: true,
  discipline: true,
  writeSign: true,
  undertakingEnable: false,
  undertakingBody: UNDERTAKING_BODY,
  requiredFields: [],
  extendFields: [],
  fillFields: [],
  titleRule: "",
  firstLevelSubheading: "",
  secondLevelSubheading: "",
  attention: "",
  objectiveAttention: "",
  subjectiveAttention: "",
};

export default {
  name: "modify-card-rule",
  components: { CardTitleRuleEdit, ModifyCardRuleUndertaking },
  props: {
    instance: {
      type: Object,
      default() {
        return {};
      },
    },
    editType: {
      type: String,
      default: "ADD",
      validator: (val) => ["ADD", "PREVIEW", "EDIT"].includes(val),
    },
  },
  computed: {
    title() {
      const names = {
        ADD: "新增题卡规则",
        PREVIEW: "题卡规则详情",
        EDIT: "编辑题卡规则",
      };
      return names[this.editType];
    },
    editable() {
      return this.editType !== "PREVIEW";
    },
    isFillModel() {
      return this.modalForm.examNumberStyle === "FILL";
    },
    selectedFields() {
      return [
        ...this.modalForm.requiredFields,
        ...this.modalForm.extendFields,
      ].filter((item) => item.enable);
    },
  },
  data() {
    return {
      modalIsShow: false,
      isSubmit: false,
      modalForm: { ...initModalForm },
      EXAM_NUMBER_STYLE,
      PAPER_TYPE,
      dataReady: false,
      rules: {
        name: [
          {
            required: true,
            message: "题卡规则名称不能超过30个字",
            max: 30,
            trigger: "change",
          },
        ],
        examNumberStyle: [
          {
            required: true,
            message: "请选择学号版式",
            trigger: "change",
          },
        ],
        examNumberDigit: [
          {
            required: true,
            message: "请输入学号位数",
            trigger: "change",
          },
        ],
        paperType: [
          {
            required: true,
            message: "请选择AB卷版式",
            trigger: "change",
          },
        ],
        defaultOptionNumber: [
          {
            required: true,
            message: "请输入默认选项个数",
            trigger: "change",
          },
        ],
        titleRule: [
          {
            required: true,
            message: "请输入题卡标题规则",
            trigger: "change",
          },
        ],
        attention: [
          {
            required: true,
            message: "请输入注意事项",
            trigger: "change",
          },
          {
            validator: (rule, value, callback) => {
              const val = value.replace(/\n/g, "");
              if (val.length > 200) {
                callback(new Error("注意事项最多只能输入200个字符"));
              } else {
                callback();
              }
            },
            trigger: "change",
          },
        ],
        firstLevelSubheading: [
          {
            required: false,
            max: 52,
            message: "一级副标题最多只能输入52个字符",
            trigger: "change",
          },
        ],
        secondLevelSubheading: [
          {
            required: false,
            max: 52,
            message: "二级副标题最多只能输入52个字符",
            trigger: "change",
          },
        ],
        objectiveAttention: [
          {
            required: false,
            message: "请输入客观题注意事项",
            trigger: "change",
          },
          {
            max: 26,
            message: "客观题注意事项最多只能输入26个字符",
            trigger: "change",
          },
        ],
        subjectiveAttention: [
          {
            required: false,
            message: "请输入主观题注意事项",
            trigger: "change",
          },
          {
            max: 26,
            message: "主观题注意事项最多只能输入26个字符",
            trigger: "change",
          },
        ],
      },
      fieldSourses: [
        {
          code: "courseName",
          enable: true,
          name: "课程名称",
        },
        {
          code: "schoolName",
          enable: true,
          name: "学校名称",
        },
      ],
      subTitleFieldSources: [
        {
          code: "courseName",
          enable: true,
          name: "课程名称",
        },
      ],
    };
  },
  methods: {
    initData(val) {
      this.modalForm = this.$objAssign(initModalForm, val);
      this.modalForm.examNumberDigit =
        this.modalForm.examNumberDigit || initModalForm.examNumberDigit;

      if (val.id) {
        this.modalForm.requiredFields = JSON.parse(val.requiredFields);
        this.modalForm.extendFields = JSON.parse(val.extendFields);
        this.modalForm.fillFields = val.fillFields
          ? val.fillFields.split(",")
          : [];
      }
    },
    visibleChange() {
      this.initData(this.instance);

      this.$nextTick(() => {
        this.$refs.modalFormComp.clearValidate();
      });
    },
    cancel() {
      this.modalIsShow = false;
    },
    open() {
      this.modalIsShow = true;
    },
    numStyleChange() {
      this.modalForm.writeSign = this.modalForm.examNumberStyle !== "FILL";
      if (this.modalForm.examNumberStyle !== "FILL") {
        this.modalForm.examNumberDigit = 10;
        this.modalForm.fillFields = [];
      }

      if (this.modalForm.examNumberStyle === "FILL") {
        this.modalForm.paperType = "FILL";
      } else if (this.modalForm.examNumberStyle === "PRINT") {
        this.modalForm.paperType = "PRINT";
      }
    },
    toEditUndertaking() {
      this.$refs.ModifyCardRuleUndertaking.open();
    },
    updateFillFields() {
      const fields = this.selectedFields.map((item) => item.code);
      this.modalForm.fillFields = this.modalForm.fillFields.filter((item) =>
        fields.includes(item)
      );
    },
    async submit() {
      const valid = await this.$refs.modalFormComp.validate().catch(() => {});
      if (!valid) return;

      if (this.isSubmit) return;
      this.isSubmit = true;
      this.updateFillFields();
      const modals = {
        ...this.modalForm,
      };
      modals.requiredFields = JSON.stringify(modals.requiredFields);
      modals.extendFields = JSON.stringify(modals.extendFields);
      modals.fillFields = modals.fillFields.join();
      const data = await saveCardRule(modals).catch(() => {});
      this.isSubmit = false;
      if (!data) return;

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