<template>
  <div class="list">
    <table>
      <tbody class="list-row">
        <tr class="list-header qm-primary-strong-text">
          <td>课程</td>
          <td>专业</td>
          <td>考试开放时间</td>
          <td>状态</td>
          <td style="max-width: 200px;">操作</td>
        </tr>

        <tr v-for="(course, courseIndex) in courses" :key="courseIndex">
          <td>{{ course.courseName }}</td>
          <td>{{ course.specialtyName }}</td>
          <td>
            {{ course.startTime }} <br />
            ~ <br />
            {{ course.endTime }}
          </td>
          <td>
            <div v-if="course.offlineFiles">
              <div v-for="(file, index) in course.offlineFiles" :key="index">
                <a
                  :href="file.offlineFileUrl"
                  download
                  :title="file.originalFileName"
                  ondragstart="return false;"
                  @click="
                    () =>
                      downloadOfflineFile(
                        file.offlineFileUrl,
                        file.originalFileName
                      )
                  "
                >
                  <i-icon type="ios-cloud-download"></i-icon>下载作答
                </a>
              </div>
            </div>
            <div v-else>未上传</div>
          </td>
          <td style="min-width: 180px;">
            <template v-if="!course.isvalid">
              <div v-if="course.paperId" style="display: grid; grid-gap: 10px;">
                <i-button
                  class="qm-primary-button"
                  @click="previewPaper(course)"
                >
                  查看试卷
                </i-button>
                <a
                  v-show="!downloadingCourse(course)"
                  class="qm-primary-button"
                  href="#"
                  download
                  ondragstart="return false;"
                  @click="() => tempDisableBtnAndDownloadPaper(course)"
                >
                  下载试卷
                </a>
                <i-button
                  v-if="downloadingCourse(course)"
                  class="qm-primary-button"
                >
                  下载中
                </i-button>
                <i-button
                  class="qm-primary-button"
                  @click="uploadHandler(course)"
                >
                  上传答案
                </i-button>
              </div>

              <div v-else style="display: grid; grid-gap: 10px;">
                <div
                  v-if="
                    new Date(course.startTime) - Date.now() > timeDifference
                  "
                >
                  未开始
                </div>
                <div
                  v-else-if="
                    new Date(course.endTime) - Date.now() < timeDifference
                  "
                >
                  已结束
                </div>
                <div v-else>
                  <i-button
                    class="qm-primary-button"
                    @click="enterExam(course)"
                  >
                    抽取试卷
                  </i-button>
                </div>
              </div>
            </template>
          </td>
        </tr>
      </tbody>
    </table>
    <ecs-offline-exam-modal
      v-if="selectedCourse"
      ref="uploadModal"
      :course="selectedCourse"
      @reloadList="$emit('reloadList')"
    ></ecs-offline-exam-modal>
  </div>
</template>

<script>
import { mapState as globalMapState, mapGetters } from "vuex";
import { TK_SERVER_HTML_URL } from "@/constants/constants.js";
import OfflineExamModal from "./OfflineExamModal.vue";

export default {
  name: "EcsOfflineList",
  components: {
    "ecs-offline-exam-modal": OfflineExamModal,
  },
  props: {
    courses: {
      type: Array,
      default() {
        return [];
      },
    },
  },
  data() {
    return {
      disableDownloadPaperBtn: false,
      downloadPaperIds: new Set(),
      selectedCourse: null,
    };
  },
  computed: {
    ...globalMapState(["user", "timeDifference"]),
    ...mapGetters(["isCug"]),
    // enableFeFeature() {
    //   return !!!this.FE_FEATURE_IMAGE_PDF;
    // },
  },
  methods: {
    async enterExam(course) {
      // 若出错，直接报网络异常
      await this.$http.get("/api/ecs_oe_admin/offlineExam/startOfflineExam", {
        params: { examStudentId: course.examStudentId },
      });
      this.$emit("reloadList");
    },
    previewPaper(course) {
      window._hmt.push(["_trackEvent", "离线考试页面", "预览"]);
      var user = {
        loginName: course.examStudentId,
        backUrl: window.document.location.href,
        isOnlineExam: true,
      };
      window.name = JSON.stringify(user);
      window.location.href =
        TK_SERVER_HTML_URL +
        "/admin/preview_paper/" +
        course.paperId +
        "?isback=true";
    },
    async downloadOfflineFile(url, name) {
      window._hmt.push(["_trackEvent", "离线考试页面", "下载作答"]);
      function toDataURL(url) {
        return fetch(url)
          .then((response) => {
            return response.blob();
          })
          .then((blob) => {
            return URL.createObjectURL(blob);
          });
      }
      if ([".png", ".jpg", ".jpeg"].some((v) => name.endsWith(v))) {
        const a = document.createElement("a");
        a.href = await toDataURL(url);
        a.download = name;
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
      } else {
        window.location.href = url;
      }
    },
    tempDisableBtnAndDownloadPaper(course) {
      window._hmt.push(["_trackEvent", "离线考试页面", "下载试卷"]);
      this.downloadPaperIds.add(course.paperId);
      this.downloadPaperIds = new Set(this.downloadPaperIds);
      // this.$forceUpdate();
      // this.disableDownloadPaperBtn = true;
      setTimeout(() => {
        // this.disableDownloadPaperBtn = false;
        this.downloadPaperIds.delete(course.paperId);
        this.downloadPaperIds = new Set(this.downloadPaperIds);
        // set 并不能正常的reactive
        // this.$forceUpdate();
      }, 10 * 1000);

      window.location.href =
        "/api/ecs_ques/paper/export/" +
        course.paperId +
        "/PAPER/" +
        this.user.rootOrgId +
        "/" +
        course.paperId +
        "/offLine?$key=" +
        this.user.key +
        "&$token=" +
        this.user.token;
    },
    downloadingCourse(course) {
      return this.downloadPaperIds.has(course.paperId);
    },
    uploadHandler(course) {
      this.selectedCourse = course;
      // setTimeout(() => {
      //   console.log(this.$refs);
      // }, 1000);
      this.$nextTick(() => {
        // console.log(this.$refs.uploadModal.$refs.uploadModal);
        this.$refs.uploadModal.$refs.uploadModal.visible = true;
      });
    },
  },
};
</script>

<style scoped>
.list {
  border: 1px solid #eeeeee;
  border-radius: 6px;
}

.list table {
  width: 100%;
  border-collapse: collapse !important;
  border-spacing: 0;
}
.list td {
  border: 1px solid #eeeeee;
  border-radius: 6px;
  border-collapse: separate !important;
  padding: 10px;
}
</style>
