<template>
  <div>
    <el-dialog
      custom-class="side-dialog"
      :visible.sync="modalIsShow"
      title="试题导入"
      width="500px"
      :modal="true"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      append-to-body
      destroy-on-close
      @open="visibleChange"
    >
      <el-form
        ref="modalFormComp"
        :model="modalForm"
        :rules="rules"
        :label-width="importType == 'zip' ? '142px' : '100px'"
      >
        <el-form-item label="导入类型">
          <el-radio-group v-model="importType" @change="importTypeChange">
            <el-radio
              v-for="item in importTypeList"
              :key="item.name"
              :label="item.name"
              >{{ item.name }}</el-radio
            >
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="importType == 'zip'" label="是否导入到其它课程">
          <el-radio-group v-model="modalForm.toOtherCourse">
            <el-radio :label="true">是</el-radio>
            <el-radio :label="false">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <!-- <el-form-item
          v-if="importType !== 'zip'"
          prop="courseId"
          label="课程名称"
        > -->
        <el-form-item
          v-if="importType !== 'zip' || modalForm.toOtherCourse"
          prop="courseId"
          label="课程名称"
        >
          <course-select v-model="modalForm.courseId" @change="courseChange">
          </course-select>
        </el-form-item>
        <el-form-item v-if="importType !== 'excel'" label="是否使用原卷">
          <el-radio-group v-model="modalForm.useOriginalPaper">
            <el-radio :label="true">是</el-radio>
            <el-radio :label="false">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item
          v-if="modalForm.useOriginalPaper && importType === 'word'"
          prop="name"
          label="试卷名称"
        >
          <el-input
            v-model="modalForm.name"
            placeholder="请输入试卷名称"
            clearable
          >
          </el-input>
        </el-form-item>
        <el-form-item v-if="modalForm.useOriginalPaper" label="总分校验">
          <el-radio-group v-model="modalForm.checkTotalScore">
            <el-radio :label="true">开启</el-radio>
            <el-radio :label="false">关闭</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item
          v-if="modalForm.checkTotalScore && modalForm.useOriginalPaper"
          label="试卷总分"
          prop="totalScore"
        >
          <el-input-number
            v-model="modalForm.totalScore"
            style="width: 125px"
            :min="1"
            :max="1000"
            :step="1"
            step-strictly
            :controls="false"
          ></el-input-number
        ></el-form-item>
        <!-- <el-form-item prop="file" label-width="0px">
          <import-file
            ref="ImportFile"
            :format="importFileTypes"
            :template-url="templateUrl"
            only-fetch-file
            @file-change="fileChange"
            @confirm="confirm"
          ></import-file>
        </el-form-item> -->
      </el-form>
      <div class="upload-gray-box">
        <import-file
          ref="ImportFile"
          :format="importFileTypes"
          :template-url="templateUrl"
          only-fetch-file
          @file-change="fileChange"
          @confirm="confirm"
        ></import-file>
      </div>

      <div slot="footer">
        <el-button
          type="primary"
          @click="confirm"
          :disabled="!this.fileData.file"
          :loading="loading"
          >确认</el-button
        >
        <el-button @click="cancel">取消</el-button>
      </div>
    </el-dialog>

    <el-dialog
      :visible.sync="errorMsgModalIsShow"
      title="错误信息"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      append-to-body
      @closed="excelErrorMsgs = []"
    >
      <div>
        <p v-for="(cont, index) in excelErrorMsgs" :key="index">{{ cont }}</p>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import ImportFile from "@/components/ImportFile.vue";
import {
  questionImportWordFileUpload,
  questionImportExcelFileUpload,
  importQuestionApi,
} from "../api";
import { QUESTION_API } from "@/constants/constants";
import { mapState } from "vuex";

const initModalForm = {
  courseId: null,
  courseName: null,
  name: "",
  checkTotalScore: false,
  useOriginalPaper: false,
  totalScore: 0,
  toOtherCourse: false,
};

export default {
  name: "QuestionImportDialog",
  components: { ImportFile },
  data() {
    return {
      modalIsShow: false,
      importTypeList: [
        {
          name: "word",
          format: ["docx", "doc"],
        },
        {
          name: "excel",
          format: ["xlsx", "xls"],
        },
        {
          name: "zip",
          format: ["zip"],
        },
      ],
      importType: "word",
      modalForm: {
        ...initModalForm,
      },
      rules: {
        courseId: [
          {
            required: true,
            message: "请选择课程",
            trigger: "change",
          },
        ],
        name: [
          {
            required: true,
            message: "请输入试卷名称",
            trigger: "change",
          },
        ],
        totalScore: [
          {
            required: true,
            message: "请输入试卷总分",
            trigger: "change",
          },
        ],
        file: [
          {
            validate: (rule, value, callback) => {
              if (!this.fileData.file) {
                return callback(new Error(`请输入选择文件`));
              }
              callback();
            },
            trigger: "change",
          },
        ],
      },
      fileData: {},
      templateUrl: "",
      errorMsgModalIsShow: false,
      excelErrorMsgs: [],
      loading: false,
    };
  },
  computed: {
    ...mapState({ user: (state) => state.user }),
    importFileTypes() {
      const types = this.importTypeList.find(
        (item) => item.name === this.importType
      );
      return types ? types.format : [];
    },
  },
  watch: {
    "modalForm.useOriginalPaper": {
      handler(val) {
        if (!val) {
          this.modalForm.name = "";
          this.modalForm.totalScore = 0;
        }
      },
    },
    "modalForm.checkTotalScore": {
      handler(val) {
        if (!val) {
          this.modalForm.totalScore = 0;
        }
      },
    },
    importType(val) {
      this.modalForm.toOtherCourse = false;
      if (val === "zip") {
        this.modalForm.courseId = null;
      }
    },
    "modalForm.toOtherCourse"(val) {
      !val && (this.modalForm.courseId = null);
    },
  },
  methods: {
    visibleChange() {
      this.modalForm = { ...initModalForm };
      this.fileData = {};
      this.importTypeChange();
    },
    cancel() {
      this.modalIsShow = false;
    },
    open() {
      this.modalIsShow = true;
    },
    importTypeChange() {
      this.modalForm.checkTotalScore = false;
      this.modalForm.useOriginalPaper = false;
      const urlBody =
        this.importType === "excel"
          ? "word/parse/excel_template_download"
          : "import/paper/template";
      this.templateUrl = `${QUESTION_API}/${urlBody}`;
      if (this.importType === "zip") {
        this.templateUrl = "";
      }

      this.$nextTick(() => {
        this.$refs.modalFormComp.clearValidate();
      });
    },
    fileChange(fileData) {
      this.fileData = fileData;
      this.$refs.modalFormComp.validateField("file", (err) => {
        console.log(err);
      });
    },
    courseChange(val) {
      this.modalForm.courseName = val ? val.name : "";
    },
    async confirm() {
      const valid = await this.$refs.modalFormComp.validate().catch(() => {});
      if (!valid) return;

      if (this.loading) return;
      this.loading = true;
      this.$refs.ImportFile.setLoading(true);

      let formData = new FormData();
      formData.append("file", this.fileData.file);
      if (this.importType !== "zip") {
        formData.append("courseId", this.modalForm.courseId);
      } else {
        Object.entries(this.modalForm).forEach(([key, val]) => {
          if (val !== null) formData.append(key, val);
        });
      }

      const uploadApi =
        this.importType === "zip"
          ? importQuestionApi
          : this.importType === "word"
          ? questionImportWordFileUpload
          : questionImportExcelFileUpload;

      const res = await uploadApi(formData, {
        md5: this.fileData.md5,
      }).catch((error) => {
        const status = error.response?.status;
        if ([403, 401, 405, 502].includes(status)) return;
        if (error.response?.data.desc) {
          this.errorMsgModalIsShow = true;
          this.excelErrorMsgs = error.response.data.desc.split("\n");
        }
      });
      this.loading = false;
      this.$refs.ImportFile.setLoading(false);

      if (!res) return;

      // this.$message.success("导入成功！");
      console.log("upload res", res);
      if (this.importType !== "word" && res.data) {
        this.$confirm(
          "系统正在计算试题情况，请在后续检查试题查重与试题审核数据。",
          "系统通知",
          {
            type: "warning",
          }
        );
      }
      this.$emit("modified", {
        ...res.data,
        importData: this.modalForm,
        importType: this.importType,
        importFileTypes: this.importFileTypes,
      });
      this.cancel();
    },
  },
};
</script>
