<template>
  <section class="content">
    <!-- 正文信息 -->
    <div
      v-loading.body="fileLoading"
      class="part-box"
      element-loading-text="试题上传中,请稍后..."
    >
      <h2 class="part-box-title">文件上传</h2>

      <el-form class="padding-tb-20" :model="formSearch" label-width="100px">
        <el-form-item label="导入类型">
          <el-radio v-model="importType" label="word">word</el-radio>
          <el-radio v-model="importType" label="zip">zip</el-radio>
        </el-form-item>
        <el-form-item v-show="importType == 'word'" label="课程名称">
          <el-select
            v-model="formSearch.courseNo"
            class="form_width"
            filterable
            :remote-method="getCourses"
            remote
            clearable
            placeholder="请选择"
            @change="searchCourseName"
            @clear="getCourses('')"
          >
            <el-option
              v-for="item in courseInfoSelect"
              :key="item.courseNo"
              :label="item.courseInfo"
              :value="item.courseNo"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-show="importType == 'word'" label="试卷名称">
          <el-input
            v-model="formSearch.name"
            placeholder="试卷名称"
            style="width: 223px"
          ></el-input>
        </el-form-item>
        <el-form-item label="总分校验">
          <el-radio v-model="scoreCheck" label="1">开启</el-radio>
          <el-radio v-model="scoreCheck" label="0">关闭</el-radio>
        </el-form-item>
        <el-form-item v-if="scoreCheck == 1" label="试卷总分">
          <el-input
            v-model="formSearch.totalScore"
            placeholder="试卷总分"
            class="form_width"
          ></el-input>
        </el-form-item>
        <!--
              <el-row>
                  <el-form-item label="相同大题名称" label-width="120px" class="pull-left">
                      <el-radio  v-model="formSearch.sameName"  label="1">合并</el-radio>
                      <el-radio  v-model="formSearch.sameName"  label="0">不合并</el-radio>
                  </el-form-item>
              </el-row>
            -->
        <el-form-item class="padding-tb-20">
          <el-upload
            ref="upload"
            :accept="importFileType"
            :action="uploadAction"
            :headers="uploadHeaders"
            :data="uploadData"
            :before-upload="beforeUpload"
            :on-progress="uploadProgress"
            :on-success="uploadSuccess"
            :on-error="uploadError"
            :file-list="fileList"
            :auto-upload="false"
            :multiple="false"
          >
            <el-button
              slot="trigger"
              type="primary"
              icon="icon icon-search-white"
              >选择文件</el-button
            >
            <el-button
              type="primary"
              icon="icon icon-save-white"
              @click="submitUpload"
              >确认上传
            </el-button>
            <el-button
              type="info"
              plain
              icon="icon el-icon-download"
              @click="donwTemplate"
              >下载word模板
            </el-button>
            <el-button
              type="danger"
              plain
              icon="icon icon-delete"
              @click="removeFile"
              >清空文件
            </el-button>
            <el-button type="danger" plain icon="icon icon-back" @click="back"
              >返回</el-button
            >
            <div slot="tip" class="el-upload__tip">只能上传docx和zip文件</div>
          </el-upload>
        </el-form-item>
      </el-form>

      <el-dialog title="错误提示" :visible.sync="errDialog" append-to-body>
        <span style="font-size: large">{{ errMessage }}</span>
        <span slot="footer" class="dialog-footer">
          <el-button @click="errDialog = false">确定</el-button>
        </span>
      </el-dialog>
    </div>
  </section>
</template>
<script>
import { QUESTION_API } from "@/constants/constants";
import { mapState } from "vuex";

export default {
  name: "ImportPaperInfo",
  data() {
    return {
      importType: "word",
      scoreCheck: "0",
      formSearch: {
        courseNo: "",
        couresName: "",
        name: "",
        totalScore: "",
        courseLevel: "",
        sameName: "0",
      },
      courseList: [],
      uploadAction: "",
      errMessage: "",
      uploadData: {},
      fileLoading: false,
      button_tpye: false,
      errDialog: false,
      fileList: [],
      uploadHeaders: {},
    };
  },
  computed: {
    ...mapState({ user: (state) => state.user }),
    courseInfoSelect() {
      var courseList = [];
      for (let course of this.courseList) {
        var courseInfo = course.name + "(" + course.code + ")";
        var courseNo = course.code;
        courseList.push({ courseNo: courseNo, courseInfo: courseInfo });
      }
      return courseList;
    },
    importFileType() {
      if (this.importType == "word") {
        return ".docx";
      } else if (this.importType == "zip") {
        return ".zip";
      }
      return ".docx";
    },
  },
  watch: {
    scoreCheck: function () {
      if (this.scoreCheck == 0) {
        this.formSearch.totalScore = "";
      }
    },
  },
  created() {
    this.uploadAction = QUESTION_API + "/importPaper";
    this.uploadData = { name: this.formSearch.name };
    this.uploadHeaders = {
      key: this.user.key,
      token: this.user.token,
    };
    this.getCourses("");
  },
  mounted() {
    setTimeout(() => {
      this.$store.commit("UPDATE_CURRENT_PATHS", [
        "题库管理",
        "题库列表",
        "文件上传",
      ]);
    }, 200);
    this.getCourses("");
  },
  methods: {
    searchCourseName() {
      for (let course of this.courseList) {
        if (course.code == this.formSearch.courseNo) {
          this.formSearch.courseName = course.name;
          this.formSearch.courseLevel = course.level;
          console.log(this.formSearch.courseLevel);
        }
      }
    },
    beforeUpload(file) {
      console.log(file);
    },
    uploadProgress() {
      console.log("uploadProgress");
    },
    uploadSuccess(res) {
      this.fileLoading = false;
      sessionStorage.setItem("question_back", "true");
      if ("PASS" == res) {
        this.$notify({
          message: "上传成功",
          type: "success",
        });
        this.$router.push({ path: "/questions/import_paper/0" });
      } else {
        this.$confirm("已开启审核功能.是否跳转到待审列表？", "上传成功", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
            this.$router.push({ path: "/questions/paper_pending_trial/0" });
          })
          .catch(() => {
            this.$router.push({ path: "/questions/import_paper/0" });
          });
      }
    },
    uploadError(err) {
      var result = err.message.match(/\{.+}/);
      var errMessage = JSON.parse(result[0]).desc;
      var code = JSON.parse(result[0]).code;
      if (code == 403 || code == 401) {
        this.$alert("登录失效，请重新登录！", "提示", {
          confirmButtonText: "确定",
          callback: () => {
            this.$router.push({
              name: "Login",
              query: { orgId: this.user.rootOrgId },
            });
          },
        });
        return;
      }

      this.errDialog = true;
      this.errMessage = errMessage;
      this.fileLoading = false;
    },
    initUpload() {
      this.fileList = [];
      this.formSearch.name = "";
      this.formSearch.courseNo = "";
    },
    checkUpload() {
      if (this.importType == "word" && !this.formSearch.courseNo) {
        this.$notify({
          message: "课程名称不能为空",
          type: "error",
        });
        return false;
      } else {
        this.uploadData.courseNo = this.formSearch.courseNo;
        this.uploadData.courseName = this.formSearch.courseName;
        this.uploadData.level = this.formSearch.courseLevel;
        this.uploadData.sameName = this.formSearch.sameName;
      }
      if (this.importType == "word" && !this.formSearch.name) {
        this.$notify({
          message: "试卷名称不能为空",
          type: "error",
        });
        return false;
      } else {
        this.uploadData.name = this.formSearch.name;
      }
      if (this.scoreCheck == 1 && !this.formSearch.totalScore) {
        this.$notify({
          message: "试卷总分不能为空",
          type: "error",
        });
        return false;
      } else {
        this.uploadData.totalScore = this.formSearch.totalScore;
      }
      var fileList = this.$refs.upload.uploadFiles;
      if (fileList.length == 0) {
        this.$notify({
          message: "上传文件不能为空",
          type: "error",
        });
        return false;
      }
      if (fileList.length > 1) {
        this.$notify({
          message: "每次只能上传一个word或zip文件",
          type: "error",
        });
        return false;
      }
      for (let file of fileList) {
        if (!file.name.endsWith(".docx") && !file.name.endsWith(".zip")) {
          this.$notify({
            message: "上传文件必须为docx或zip格式",
            type: "error",
          });
          this.initUpload();
          return false;
        }
      }
      return true;
    },
    donwTemplate() {
      window.location.href =
        QUESTION_API +
        "/import/paper/template?$key=" +
        this.user.key +
        "&$token=" +
        this.user.token;
    },
    //确定上传
    submitUpload() {
      console.log("this form:", this.formSearch);
      if (!this.checkUpload()) {
        return false;
      }
      this.$refs.upload.submit();
      this.fileLoading = true;
    },
    //清空文件
    removeFile() {
      // this.fileList = [];
      this.$refs.upload.clearFiles();
    },
    //返回
    back() {
      this.$router.push({ path: "/questions/import_paper/0" });
    },
    //查询所有课程
    getCourses(query) {
      query = query.trim();
      this.courseLoading = true;
      this.$http
        .get(QUESTION_API + "/course/query?name=" + query + "&enable=true")
        .then((response) => {
          this.courseList = response.data;
          this.courseLoading = false;
        });
    },
  },
};
</script>
