<template>
  <el-dialog
    class="upload-paper-answer-dialog"
    :visible.sync="modalIsShow"
    title="上传试卷结构文档/标答PDF文档"
    top="10vh"
    width="740px"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    append-to-body
    destroy-on-close
    @open="visibleChange"
  >
    <el-form ref="modalFormComp" :model="infos" label-width="130px">
      <div v-for="paperType in paperTypes" :key="paperType" class="part-box">
        <h3 class="mb-2">卷型{{ paperType }}</h3>
        <el-form-item
          v-for="(val, key) in fileTypes"
          :key="key"
          :prop="`${paperType}.${key}`"
          :label="`${val.name}：`"
        >
          <select-file
            :format="val.format"
            :disabled="isSubmit"
            @file-change="data => fileChange(paperType, key, data)"
          ></select-file>
          <el-button
            v-if="val.downloadUrl"
            type="success"
            icon="el-icon-download"
          >
            <a :href="val.downloadUrl" :download="val.downloadName">模板下载</a>
          </el-button>
        </el-form-item>
      </div>
    </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 { examStructureUpload } from "../api";
import SelectFile from "./SelectFile.vue";

export default {
  name: "upload-paper-answer-dialog",
  components: { SelectFile },
  props: {
    instance: {
      type: Object,
      default() {
        return {};
      }
    }
  },
  data() {
    return {
      modalIsShow: false,
      isSubmit: false,
      infos: {},
      paperTypes: [],
      fileTypes: {
        objectiveQuestion: {
          name: "客观题试卷结构",
          downloadUrl: "/temps/objectiveQuestionTemplate.xlsx",
          downloadName: "客观题导入模板.xlsx",
          format: ["xlsx", "xls"]
        },
        subjectiveQuestion: {
          name: "主观题试卷结构",
          downloadUrl: "/temps/subjectiveQuestionTemplate.xlsx",
          downloadName: "主观题导入模板.xlsx",
          format: ["xlsx", "xls"]
        },
        standardAnswer: {
          name: "标答",
          format: ["pdf"]
        }
      },
      fileTypeSerial: [
        "objectiveQuestion",
        "subjectiveQuestion",
        "standardAnswer"
      ]
    };
  },
  methods: {
    initData() {
      this.paperTypes = this.instance.paperType.split(",");
      let infos = {};
      this.paperTypes.forEach(paperType => {
        let item = {};
        Object.keys(this.fileTypes).map(typeKey => {
          item[typeKey] = {
            file: null,
            md5: null,
            errorMsg: null
          };
        });
        infos[paperType] = item;
      });
      this.infos = infos;
    },
    visibleChange() {
      this.initData();
    },
    cancel() {
      this.modalIsShow = false;
    },
    open() {
      this.modalIsShow = true;
    },
    fileChange(paperType, typeKey, data) {
      if (data.errorMsg) {
        this.infos[paperType][typeKey].file = null;
        this.infos[paperType][typeKey].md5 = null;
        this.infos[paperType][typeKey].errorMsg = data.errorMsg;
      } else {
        this.infos[paperType][typeKey].file = data.file;
        this.infos[paperType][typeKey].md5 = data.md5;
        this.infos[paperType][typeKey].errorMsg = null;
      }
      // this.$refs.modalFormComp.validateField(`${paperType}.${typeKey}`);
    },
    fileValidator(rule, value, callback) {
      // const [paperType, typeKey] = rule.field.split(".");
      // const val = this.infos[paperType][typeKey];

      // if (val.errorMsg) {
      //   return callback(new Error(val.errorMsg));
      // } else {
      //   if (!val.file) {
      //     return callback(new Error("请选择文件"));
      //   }
      // }
      const [paperType] = rule.field.split(".");
      const paperTypeVals = this.infos[paperType];
      const kvs = Object.vals(paperTypeVals);
      const valid = kvs.some(val => !!val.file);
      if (!valid) {
        return callback(new Error(`卷型${paperType}至少要上传一种文件`));
      }

      callback();
    },
    async submit() {
      const valid = await this.$refs.modalFormComp.validate().catch(() => {});
      if (!valid) return;

      if (this.isSubmit) return;
      this.isSubmit = true;

      let formData = new FormData();
      formData.append("examPaperStructure", JSON.stringify(this.instance));
      let md5s = [];
      let keys = [];
      Object.entries(this.infos).forEach(([paperType, vals]) => {
        this.fileTypeSerial.forEach(typeKey => {
          if (!vals[typeKey].file) return;
          formData.append(`files`, vals[typeKey].file);
          md5s.push(vals[typeKey].md5);
          keys.push(`${paperType}-${typeKey}`);
        });
      });
      formData.append(`md5`, md5s.join());
      formData.append(`keys`, keys.join());

      // Object.entries(this.infos).forEach(([paperType, vals], index) => {
      //   const indexName = `files[${index}]`;
      //   formData.append(`${indexName}.paperType`, paperType);
      //   this.fileTypeSerial.forEach(typeKey => {
      //     formData.append(`${indexName}.${typeKey}File`, vals[typeKey].file);
      //     formData.append(`${indexName}.${typeKey}Md5`, vals[typeKey].md5);
      //   });
      // });
      const data = await examStructureUpload(formData).catch(() => {});
      this.isSubmit = false;
      if (!data) return;

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