<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"
  >
    <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;"
          @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>
        <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="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 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"
            >{{ column.name }}</el-checkbox
          >
        </el-form-item>
      </div>
      <el-form-item prop="titleRule" label="题卡标题规则：">
        <!-- <el-input
            v-model="modalForm.titleRule"
            :disabled="!editable"
          ></el-input> -->
        <card-title-rule-edit
          v-model="modalForm.titleRule"
          :disabled="!editable"
          :field-sourses="fieldSourses"
          v-if="fieldSourses.length"
          ref="CardTitleRuleEdit"
        ></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="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="orgIds" label="适用机构范围：">
        <select-orgs
          v-model="modalForm.orgIds"
          ref="SelectOrgs"
          :disabled="!editable"
        ></select-orgs>
      </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>
</template>

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

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

export default {
  name: "modify-card-rule",
  components: { SelectOrgs, CardTitleRuleEdit },
  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";
    }
    // fieldSourses() {
    //   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"
          }
        ],
        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"
          }
        ],
        orgIds: [
          {
            required: true,
            validator: (rule, value, callback) => {
              if (value.length) {
                callback();
              } else {
                callback(new Error("请选择适用机构"));
              }
            },
            trigger: "change"
          }
        ]
      },
      fieldSourses: [
        {
          code: "courseName",
          enable: true,
          name: "课程名称"
        },
        {
          code: "schoolName",
          enable: true,
          name: "学校名称"
        }
      ]
    };
  },
  methods: {
    initData(val) {
      this.modalForm = this.$objAssign(initModalForm, val);

      if (val.id) {
        this.modalForm.requiredFields = JSON.parse(val.requiredFields);
        this.modalForm.extendFields = JSON.parse(val.extendFields);
        this.modalForm.orgIds = val.orgs.map(item => item.id);
      } else {
        this.modalForm.orgIds = [];
      }
    },
    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(modals.requiredFields);
      modals.extendFields = JSON.stringify(modals.extendFields);
      const data = await saveCardRule(modals).catch(() => {});
      this.isSubmit = false;
      if (!data) return;

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