<template>
  <el-dialog
    class="modify-template"
    :visible.sync="modalIsShow"
    :title="title"
    width="700px"
    top="10px"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    append-to-body
    @open="visibleChange"
  >
    <el-form
      ref="modalFormComp"
      label-width="140px"
      :rules="rules"
      :model="modalForm"
    >
      <el-form-item prop="name" label="模板名称：">
        <el-input
          v-model.trim="modalForm.name"
          placeholder="建议不超过30个字，规则名称不允许重复"
          style="width: 100%"
          clearable
        ></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"
          clearable
          show-word-limit
          placeholder="建议不超过50个字"
        ></el-input>
      </el-form-item>
      <el-form-item prop="classify" label="分类：">
        <el-select v-model="modalForm.classify" placeholder="请选择" clearable>
          <el-option
            v-for="(val, key) in categories"
            :key="key"
            :value="key"
            :label="val"
          ></el-option>
        </el-select>
      </el-form-item>
      <template v-if="modalForm.classify === 'SIGN'">
        <el-form-item prop="testDesc" label="文字说明：">
          <el-input
            v-model="modalForm.textDesc"
            type="textarea"
            resize="none"
            :rows="2"
            :maxlength="500"
            clearable
            show-word-limit
            placeholder="建议不超过500个字"
          ></el-input>
        </el-form-item>
        <el-form-item label="显示字段：" prop="fields">
          <el-checkbox
            v-for="field in signDatas.basic"
            :key="field.code"
            v-model="field.enable"
            >{{ field.name }}</el-checkbox
          >
          <el-divider></el-divider>
          <el-checkbox
            v-for="field in signDatas.table"
            :key="field.code"
            v-model="field.enable"
            :disabled="field.code === 'studentSign'"
            @change="signFieldChange"
            >{{ field.name }}</el-checkbox
          >
        </el-form-item>
        <el-divider content-position="left">签到表页面设置</el-divider>
        <el-form-item
          label="考生数据显示方式："
          prop="diallel"
          style="margin-bottom: 0"
        >
          <el-radio-group v-model="modalForm.diallel">
            <el-radio :label="false">单列</el-radio>
            <el-radio :label="true">双列</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item
          label="是否增加空白页："
          prop="addBlankPage"
          style="margin-bottom: 0"
        >
          <el-radio-group v-model="modalForm.addBlankPage">
            <el-radio :label="false">否</el-radio>
            <el-radio :label="true">是</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item
          label="考生信息行间距："
          prop="lineHeightTimes"
          style="margin-bottom: 0"
        >
          <el-radio-group v-model="modalForm.lineHeightTimes">
            <el-radio :label="1">1倍</el-radio>
            <el-radio :label="1.5">1.5倍</el-radio>
            <el-radio :label="2">2倍</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item
          label="考生信息字号："
          prop="fontSize"
          style="margin-bottom: 0"
        >
          <el-radio-group v-model="modalForm.fontSize">
            <el-radio label="SMALL">小</el-radio>
            <el-radio label="MEDIUM">中</el-radio>
            <el-radio label="LARGE">大</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="信息宽度设置：" prop="fieldWidth">
          <el-table :data="signTableDatas" border>
            <el-table-column prop="name" label="列名"></el-table-column>
            <el-table-column label="宽度" width="200px">
              <template slot-scope="scope">
                <el-input-number
                  v-model="scope.row.rate"
                  :min="1"
                  :max="100"
                  :step="1"
                  step-strictly
                  :controls="false"
                ></el-input-number>
                <span class="ml-1">%</span>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
      </template>
      <el-form-item
        v-else-if="modalForm.classify === 'PACKAGE'"
        label="显示字段："
        prop="fields"
      >
        <el-checkbox
          v-for="field in packageDatas.title"
          :key="field.code"
          v-model="field.enable"
          >{{ field.name }}</el-checkbox
        >
        <el-divider></el-divider>
        <el-checkbox
          v-for="field in packageDatas.basic"
          :key="field.code"
          v-model="field.enable"
          >{{ field.name }}</el-checkbox
        >
      </el-form-item>
      <el-form-item
        v-else-if="modalForm.classify === 'CHECK_IN'"
        prop="attachmentId"
        label="上传模板文件："
      >
        <upload-file-view
          :upload-data="uploadData"
          :upload-url="uploadUrl"
          :format="format"
          @valid-error="validError"
          @upload-success="uploadSuccess"
          ref="UploadFileView"
        ></upload-file-view>
      </el-form-item>
    </el-form>

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

<script>
import { templateDetail, updateTemplate, examRuleDetail } from "../api";
import { attachmentDetail } from "../../login/api";
import UploadFileView from "@/components/UploadFileView";
import { calcSum } from "@/plugins/utils";

const initModalForm = {
  id: null,
  name: "",
  type: "",
  remark: "",
  classify: "",
  diallel: true,
  addBlankPage: true,
  lineHeightTimes: 1,
  textDesc: "",
  attachmentId: "",
  fontSize: "SMALL",
};

export default {
  name: "modify-print-template",
  components: { UploadFileView },
  props: {
    instance: {
      type: Object,
      default() {
        return {};
      },
    },
  },
  computed: {
    isEdit() {
      return !!this.instance.id;
    },
    title() {
      return (this.isEdit ? "编辑" : "新增") + "模板";
    },
    signTableDatas() {
      return this.signDatas.table.filter((item) => item.enable);
    },
  },
  data() {
    const fieldsValidator = (rule, value, callback) => {
      if (this.modalForm.classify === "PACKAGE") {
        if (!this.packageDatas.basic.some((item) => item.enable)) {
          return callback(new Error("请选择显示字段"));
        }
        return callback();
      } else {
        if (
          !this.signDatas.basic.some((item) => item.enable) ||
          !this.signDatas.table.some((item) => item.enable)
        ) {
          return callback(new Error("请选择显示字段"));
        }
        return callback();
      }
    };
    const fieldsWidthValidator = (rule, value, callback) => {
      if (this.signTableDatas.some((item) => !item.rate)) {
        return callback(new Error("请完成设置"));
      }
      const rateSum = calcSum(this.signTableDatas.map((item) => item.rate));
      if (rateSum !== 100) {
        return callback(
          new Error(`宽度总和需要等于100，当前总和为 ${rateSum}`)
        );
      }
      return callback();
    };

    return {
      modalIsShow: false,
      isSubmit: false,
      PACKAGE_DATA: [],
      SIGN_DATA: {},
      modalForm: {},
      attachment: {},
      format: ["ftl", "html", "pdf"],
      categories: {
        SIGN: "签到表",
        PACKAGE: "卷袋贴",
        CHECK_IN: "考试情况登记表",
      },
      rules: {
        name: [
          {
            required: true,
            message: "题卡规则名称不能超过30个字",
            max: 30,
            trigger: "change",
          },
        ],
        classify: [
          {
            required: true,
            message: "请选择分类",
            trigger: "change",
          },
        ],
        attachmentId: [
          {
            required: true,
            message: "请上传模板文件",
            trigger: "change",
          },
        ],
        fields: [
          {
            required: true,
            validator: fieldsValidator,
            trigger: "change",
          },
        ],
        fieldWidth: [
          {
            required: true,
            validator: fieldsWidthValidator,
            trigger: "change",
          },
        ],
      },
      packageDatas: { title: [], basic: [] },
      signDatas: { basic: [], table: [] },
      // upload
      uploadUrl: "/api/admin/common/file/upload",
      uploadData: {
        type: "UPLOAD",
      },
    };
  },
  created() {
    this.getScopeField();
  },
  methods: {
    async getScopeField() {
      const examRule = await examRuleDetail();
      this.PACKAGE_DATA = examRule.packageScope
        ? JSON.parse(examRule.packageScope)
        : { title: [], basic: [] };
      this.SIGN_DATA = examRule.signScope
        ? JSON.parse(examRule.signScope)
        : { basic: [], table: [] };
    },
    async initData(val) {
      if (val.id) {
        const data = await templateDetail(val.id);
        this.modalForm = this.$objAssign(initModalForm, data);

        const unAttachmentTemps = ["SIGN", "PACKAGE"];
        if (unAttachmentTemps.includes(this.modalForm.classify)) {
          this.initEditFieldData(data);
        } else {
          this.getAttachment();
        }
      } else {
        this.modalForm = this.$objAssign(initModalForm, val);
        this.getDefaultFieldData();
      }
    },
    getDefaultFieldData() {
      this.packageDatas.title = this.PACKAGE_DATA.title.map((item) => {
        return { ...item, enable: false };
      });
      this.packageDatas.basic = this.PACKAGE_DATA.basic.map((item) => {
        return { ...item, enable: false };
      });
      this.packageDatas.basic.push(
        ...[
          {
            code: "paperCount",
            name: "试卷数量",
            enable: false,
          },
          {
            code: "examCount",
            name: "应考人数",
            enable: false,
          },
          {
            code: "actualExamCount",
            name: "实考人数",
            enable: false,
          },
        ]
      );
      this.signDatas.basic = this.SIGN_DATA.basic.map((item) => {
        return { ...item, enable: false };
      });
      this.signDatas.basic.push(
        ...[
          {
            code: "examCount",
            name: "应考人数",
            enable: false,
          },
          {
            code: "actualExamCount",
            name: "实考人数",
            enable: false,
          },
        ]
      );
      this.signDatas.table = this.SIGN_DATA.table.map((item) => {
        return { ...item, rate: undefined, enable: false };
      });
      this.signDatas.table.push({
        code: "studentSign",
        name: "签名",
        rate: undefined,
        enable: true,
      });
    },
    initEditFieldData(data) {
      const displayRange = data.displayRange
        ? JSON.parse(data.displayRange)
        : null;
      if (!displayRange) {
        this.getDefaultFieldData();
        return;
      }

      if (data.classify === "PACKAGE") {
        this.packageDatas = displayRange;
      } else {
        this.signDatas = displayRange;
      }
    },
    async getAttachment() {
      if (!this.instance.attachmentId) return;
      const data = await attachmentDetail(this.instance.attachmentId);
      this.attachment = data;

      this.$nextTick(() => {
        this.$refs.UploadFileView.setAttachmentName(`${data.name}${data.type}`);
      });
    },
    signFieldChange() {
      this.$refs.modalFormComp.validateField("fieldWidth", () => {});
    },
    visibleChange() {
      this.initData(this.instance);

      this.$nextTick(() => {
        this.$refs.modalFormComp.clearValidate();
      });
    },
    cancel() {
      this.modalIsShow = false;
    },
    open() {
      this.modalIsShow = true;
    },
    async submit() {
      const valid = await this.$refs.modalFormComp.validate().catch(() => {});
      if (!valid) return;

      if (this.isSubmit) return;
      this.isSubmit = true;
      let datas = {
        ...this.modalForm,
      };
      if (this.modalForm.classify === "PACKAGE") {
        datas.displayRange = this.packageDatas;
      } else if (this.modalForm.classify === "SIGN") {
        let signTableRates = {};
        this.signTableDatas.forEach((item) => {
          signTableRates[item.code] = item.rate;
        });
        this.signDatas.table.forEach((item) => {
          item.rate = signTableRates[item.code] || 0;
        });
        datas.displayRange = this.signDatas;
      }
      const data = await updateTemplate(datas).catch(() => {});
      this.isSubmit = false;
      if (!data) return;

      this.$message.success("保存成功！");
      this.$emit("modified");
      this.cancel();
    },
    validError(errorData) {
      this.$message.error(errorData.message);
    },
    uploadSuccess(data) {
      this.$message.success("上传成功！");

      this.modalForm.attachmentId = data.id;
      this.$refs.modalFormComp.validateField("attachmentId");
    },
  },
};
</script>
