<template>
  <div class="card-config-prop-edit">
    <el-button @click="open" type="primary"> 配置题卡规则 </el-button>
    <el-drawer
      :visible.sync="drawer"
      :with-header="false"
      append-to-body
      :close-on-press-escape="false"
      :size="820"
      class="card-config-drawer"
    >
      <div class="card-config-edit">
        <div class="card-config-header">
          <h2>配置题卡规则</h2>
        </div>
        <div class="card-config-body">
          <el-form
            ref="modalFormComp"
            label-width="130px"
            :rules="rules"
            :model="modalForm"
          >
            <el-form-item
              prop="examNumberStyle"
              label="学号版式："
              class="inline-block"
            >
              <el-select
                v-model="modalForm.examNumberStyle"
                style="width: 142px"
                placeholder="请选择"
                @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="modalForm.examNumberStyle === 'FILL'"
              prop="fillNumber"
              label="学号位数："
              class="inline-block"
            >
              <el-input-number
                v-model="modalForm.fillNumber"
                :min="5"
                :max="15"
                :step="1"
                step-strictly
                :controls="false"
                style="width: 100px"
              ></el-input-number>
            </el-form-item>
            <el-form-item>
              <el-checkbox v-model="modalForm.examAbsent"
                >启用“缺考填涂”</el-checkbox
              >
              <el-checkbox v-model="modalForm.discipline"
                >启用“违纪填涂”</el-checkbox
              >
              <el-checkbox
                v-model="modalForm.writeSign"
                :disabled="modalForm.examNumberStyle === 'FILL'"
                >启用“手写签名”</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>
            <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"
                  >{{ column.name }}</el-checkbox
                >
              </el-form-item>
              <el-form-item
                v-if="
                  deletedField.requiredFields.length ||
                  deletedField.extendFields.length
                "
                label="通用规则已删除字段："
                label-width="160px"
              >
                <el-checkbox
                  v-for="column in deletedField.requiredFields"
                  :key="column.code"
                  v-model="column.enable"
                  >{{ column.name }}</el-checkbox
                >
                <el-checkbox
                  v-for="column in deletedField.extendFields"
                  :key="column.code"
                  v-model="column.enable"
                  >{{ column.name }}</el-checkbox
                >
              </el-form-item>
            </div>
            <el-form-item prop="attention" label="注意事项：">
              <el-input
                type="textarea"
                :rows="4"
                v-model="modalForm.attention"
              ></el-input>
              <p class="tips-info">
                提示：换行之后，题卡注意事项会展示为多条内容，内容序号会被自动添加。
              </p>
            </el-form-item>
            <el-form-item prop="objectiveAttention" label="客观题注意事项：">
              <el-input v-model.trim="modalForm.objectiveAttention"></el-input>
            </el-form-item>
            <el-form-item prop="subjectiveAttention" label="主观题注意事项：">
              <el-input v-model.trim="modalForm.subjectiveAttention"></el-input>
            </el-form-item>
          </el-form>
        </div>
        <div class="card-config-footer">
          <el-button @click="cancel">取消</el-button>
          <el-button type="primary" @click="submit">确认</el-button>
        </div>
      </div>
    </el-drawer>

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

<script>
import { mapState, mapMutations, mapActions } from "vuex";
import { objAssign } from "../plugins/utils";
import { EXAM_NUMBER_STYLE, PAPER_TYPE } from "@/constants/enumerate";
import { examRuleDetail, getEnums } from "@/modules/base/api";
import ModifyCardRuleUndertaking from "@/modules/base/components/ModifyCardRuleUndertaking.vue";

const initModalForm = {
  examNumberStyle: "",
  fillNumber: 10,
  paperType: "PRINT",
  examAbsent: true,
  discipline: true,
  writeSign: true,
  undertakingEnable: false,
  undertakingBody: "",
  requiredFields: [],
  extendFields: [],
  attention: "",
  objectiveAttention: "",
  subjectiveAttention: "",
};

export default {
  name: "card-config-prop-edit",
  components: { ModifyCardRuleUndertaking },
  data() {
    return {
      modalForm: { ...initModalForm },
      deletedField: {
        requiredFields: [],
        extendFields: [],
      },
      EXAM_NUMBER_STYLE,
      PAPER_TYPE,
      drawer: false,
      rules: {
        examNumberStyle: [
          {
            required: true,
            message: "请选择学号版式",
            trigger: "change",
          },
        ],
        fillNumber: [
          {
            required: true,
            message: "请输入学号位数",
            trigger: "change",
          },
        ],
        paperType: [
          {
            required: true,
            message: "请选择AB卷版式",
            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: false,
            message: "请输入客观题注意事项",
            trigger: "change",
          },
          {
            max: 26,
            message: "客观题注意事项最多只能输入26个汉字",
            trigger: "change",
          },
        ],
        subjectiveAttention: [
          {
            required: false,
            message: "请输入主观题注意事项",
            trigger: "change",
          },
          {
            max: 26,
            message: "主观题注意事项最多只能输入26个汉字",
            trigger: "change",
          },
        ],
      },
      examRule: {},
    };
  },
  computed: {
    ...mapState("card", ["cardConfig"]),
  },
  mounted() {
    this.getExamRule();
  },
  methods: {
    ...mapMutations("card", ["setCardConfig"]),
    ...mapActions("card", ["rebuildPages"]),
    async getExamRule() {
      const examRequiredFields = await getEnums("REQUIRED_FIELDS");
      const cardRequiredFields = await getEnums("CARD_REQUIRED_FIELDS");
      const cardRequiredFieldCodes = cardRequiredFields.map(
        (item) => item.code
      );
      const extendFields = examRequiredFields
        .filter(
          (field) =>
            !cardRequiredFieldCodes.includes(field.code) && field.enable
        )
        .map((item) => {
          return {
            code: item.code,
            name: item.name,
          };
        });
      let examRule = await examRuleDetail();
      const cardExtendFields = [
        ...extendFields,
        ...JSON.parse(examRule.extendFields).filter((item) => item.enable),
      ];

      this.examRule = {
        requiredFields: cardRequiredFields.map((item) => {
          return {
            code: item.code,
            name: item.name,
            enable: true,
          };
        }),
        extendFields: cardExtendFields.map((item) => {
          return {
            code: item.code,
            name: item.name,
            enable: false,
          };
        }),
      };
    },
    initData() {
      this.modalForm = objAssign(initModalForm, this.cardConfig);
      this.updateField("requiredFields");
      this.updateField("extendFields");
    },
    updateField(type) {
      const examRuleFieldCodes = this.examRule[type].map((item) => item.code);
      this.deletedField[type] = this.modalForm[type].filter(
        (field) => !examRuleFieldCodes.includes(field.code)
      );
      this.modalForm[type] = this.modalForm[type].filter((field) =>
        examRuleFieldCodes.includes(field.code)
      );
      const modalFormFieldCodes = this.modalForm[type].map((item) => item.code);
      this.examRule[type].forEach((field) => {
        if (modalFormFieldCodes.includes(field.code)) return;
        this.modalForm[type].push({ ...field });
      });
    },
    toEditUndertaking() {
      this.$refs.ModifyCardRuleUndertaking.open();
    },
    open() {
      this.drawer = true;
      this.initData();
    },
    cancel() {
      this.drawer = false;
    },
    numStyleChange() {
      this.modalForm.writeSign = this.modalForm.examNumberStyle !== "FILL";
      if (this.modalForm.examNumberStyle !== "FILL") {
        this.modalForm.examNumberDigit = 10;
      }
    },
    async submit() {
      const valid = await this.$refs.modalFormComp.validate().catch(() => {});
      if (!valid) return;

      const data = { ...this.modalForm };
      this.deletedField.requiredFields.forEach((item) => {
        if (item.enable) {
          data.requiredFields.push({ ...item });
        }
      });
      this.deletedField.extendFields.forEach((item) => {
        if (item.enable) {
          data.extendFields.push({ ...item });
        }
      });

      this.setCardConfig(data);
      this.cancel();

      this.$nextTick(() => {
        this.rebuildPages();
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.card-config-edit {
  display: flex;
  flex-direction: column;
  height: 100%;
}
.card-config-header {
  padding: 15px 20px;
  line-height: 20px;
  border-bottom: 1px solid #f0f0f0;
}

.card-config-body {
  flex: 1;
  padding: 15px 20px;
}
.card-config-footer {
  padding: 15px 20px;
  text-align: right;
}
</style>
