<template>
  <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"
  >
    <div class="part-box part-box-pad part-box-border">
      <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.trim="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;"
            @change="numStyleChange"
            placeholder="请选择"
            :disabled="!editable"
          >
            <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 prop="paperType" label="AB卷版式：" class="inline-block">
          <el-select
            v-model="modalForm.paperType"
            style="width: 142px;"
            placeholder="请选择"
            :disabled="!editable"
          >
            <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 class="inline-block" label-width="30px">
          <el-checkbox v-model="modalForm.examAbsent" :disabled="!editable"
            >启用“缺考填涂”</el-checkbox
          >
        </el-form-item>
        <el-form-item class="inline-block" label-width="30px">
          <el-checkbox
            v-model="modalForm.writeSign"
            :disabled="modalForm.examNumberStyle === 'FILL' || !editable"
            >启用“手写签名”</el-checkbox
          >
        </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 requiredFields"
              :key="column.code"
              v-model="column.enable"
              :disabled="!editable"
              >{{ column.name }}</el-checkbox
            >
          </el-form-item>
          <el-form-item label="扩展字段：" label-width="115px">
            <el-checkbox
              v-for="column in extendFields"
              :key="column.code"
              v-model="column.enable"
              :disabled="!editable"
              >{{ column.name }}</el-checkbox
            >
          </el-form-item>
        </div>
        <el-form-item prop="titleRule" label="题卡标题规则：">
          <el-input
            v-model="modalForm.titleRule"
            :disabled="!editable"
          ></el-input>
        </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="modalForm.objectiveAttention"
            :disabled="!editable"
          ></el-input>
        </el-form-item>
        <el-form-item prop="subjectiveAttention" label="主观题注意事项：">
          <el-input
            v-model="modalForm.subjectiveAttention"
            :disabled="!editable"
          ></el-input>
        </el-form-item>
        <el-form-item prop="orgs" label="适用学院范围：">
          <select-orgs v-model="modalForm.orgs" ref="SelectOrgs"></select-orgs>
        </el-form-item>
      </el-form>
    </div>

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

<script>
import { EXAM_NUMBER_STYLE, PAPER_TYPE } from "@/constants/enumerate";
import { saveCardRule } from "../api";
import SelectOrgs from "./SelectOrgs";

const initModalForm = {
  id: null,
  name: "",
  remark: "",
  examNumberStyle: "",
  paperType: "",
  examAbsent: true,
  writeSign: true,
  requiredFields: "",
  extendFields: "",
  titleRule: "",
  attention: "",
  objectiveAttention: "",
  subjectiveAttention: "",
  orgs: []
};

export default {
  name: "modify-card-rule",
  components: { SelectOrgs },
  props: {
    instance: {
      type: Object,
      default() {
        return {};
      }
    },
    editable: {
      type: Boolean,
      default: true
    }
  },
  computed: {
    isEdit() {
      return !!this.instance.id;
    },
    title() {
      return (this.isEdit ? "编辑" : "新增") + "题卡规则";
    }
  },
  data() {
    return {
      modalIsShow: false,
      isSubmit: false,
      modalForm: {},
      EXAM_NUMBER_STYLE,
      PAPER_TYPE,
      dataReady: false,
      requiredFields: [],
      extendFields: [],
      rules: {
        name: [
          {
            required: true,
            message: "题卡规则名称不能超过30个字",
            max: 30,
            trigger: "change"
          }
        ],
        examNumberStyle: [
          {
            required: true,
            message: "请选择考号版式",
            trigger: "change"
          }
        ],
        paperType: [
          {
            required: true,
            message: "请选择AB卷版式",
            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"
          }
        ],
        objectiveAttention: [
          {
            required: true,
            message: "请输入客观题注意事项",
            trigger: "change"
          },
          {
            max: 26,
            message: "客观题注意事项最多只能输入26个汉字",
            trigger: "change"
          }
        ],
        subjectiveAttention: [
          {
            required: true,
            message: "请输入主观题注意事项",
            trigger: "change"
          },
          {
            max: 26,
            message: "主观题注意事项最多只能输入26个汉字",
            trigger: "change"
          }
        ],
        orgs: [
          {
            required: true,
            validator: (rule, value, callback) => {
              if (value.length) {
                callback();
              } else {
                callback(new Error("请选择适用学院"));
              }
            },
            trigger: "change"
          }
        ]
      }
    };
  },
  methods: {
    initData(val) {
      this.modalForm = this.$objAssign(initModalForm, val);
      this.requiredFields = val.requiredFields;
      this.extendFields = val.extendFields;
      if (val.id) {
        this.modalForm.examAbsent = Boolean(val.examAbsent);
        this.modalForm.writeSign = Boolean(val.writeSign);
        this.modalForm.orgs = val.orgs.map(item => item.id);
      }
    },
    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";
    },
    async submit() {
      const valid = await this.$refs.modalFormComp.validate().catch(() => {});
      if (!valid) return;

      if (this.isSubmit) return;
      this.isSubmit = true;
      let modals = {
        ...this.modalForm
      };
      modals.requiredFields = JSON.stringify(this.requiredFields);
      modals.extendFields = JSON.stringify(this.extendFields);
      modals.examAbsent = Number(modals.examAbsent);
      modals.writeSign = Number(modals.writeSign);
      const data = await saveCardRule(modals).catch(() => {});
      this.isSubmit = false;
      if (!data) return;

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