<template>
  <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">
          <el-radio label="docx">word</el-radio>
          <el-radio label="zip">zip</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item
        v-if="importType === 'docx'"
        prop="courseId"
        label="课程名称"
      >
        <course-select v-model="modalForm.courseId"> </course-select>
      </el-form-item>
      <el-form-item 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 === 'docx'"
        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>
</template>

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

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

export default {
  name: "QuestionImportDialog",
  components: { ImportFile },
  data() {
    return {
      modalIsShow: false,
      importType: "docx",
      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: "",
      loading: false,
    };
  },
  computed: {
    ...mapState({ user: (state) => state.user }),
    importFileTypes() {
      return this.importType === "docx" ? ["docx", "doc"] : [this.importType];
    },
  },
  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;
      }
    },
  },
  mounted() {
    this.templateUrl = `${QUESTION_API}/import/paper/template?$key=${this.user.key}&$token=${this.user.token}`;
  },
  methods: {
    visibleChange() {
      this.modalForm = { ...initModalForm };
      this.fileData = {};
    },
    cancel() {
      this.modalIsShow = false;
    },
    open() {
      this.modalIsShow = true;
    },
    fileChange(fileData) {
      this.fileData = fileData;
      this.$refs.modalFormComp.validateField("file", (err) => {
        console.log(err);
      });
    },
    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();
      Object.entries(this.modalForm).forEach(([key, val]) => {
        if (val !== null) formData.append(key, val);
      });
      formData.append("file", this.fileData.file);

      const res = await questionImportFileUpload(formData, {
        md5: this.fileData.md5,
      }).catch(() => {});
      this.loading = false;
      this.$refs.ImportFile.setLoading(false);

      if (!res) return;

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