<template>
  <div>
    <el-dialog
      custom-class="side-dialog"
      :visible.sync="modalIsShow"
      title="试题导入"
      width="700px"
      :modal="false"
      :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="120px"
      >
        <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'"
          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">
          <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 slot="footer"></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,
};

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) {
      if (val === "zip") {
        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}?$key=${this.user.key}&$token=${this.user.token}`;
    },
    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) => {
        if (error.response?.data.desc) {
          this.errorMsgModalIsShow = true;
          this.excelErrorMsgs = error.response.data.desc.split("\n");
          if (
            this.excelErrorMsgs.some(
              (item) =>
                item.includes("no login") || item.includes("token is wrong")
            )
          ) {
            this.excelErrorMsgs = ["登陆失效，请重新登录！"];
          }
        }
      });
      this.loading = false;
      this.$refs.ImportFile.setLoading(false);

      if (!res) return;

      // this.$message.success("导入成功！");
      this.$emit("modified", {
        ...res.data,
        importData: this.modalForm,
        importType: this.importType,
        importFileTypes: this.importFileTypes,
      });
      this.cancel();
    },
  },
};
</script>
