<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="
                    () => {
                      logger({
                        page: '离线考试页',
                        button: '下载作答按钮',
                        action: '点击',
                      });
                      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="
                    () => {
                      logger({
                        page: '离线考试页面',
                        button: '下载试卷按钮',
                        action: '点击',
                      });
                      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"
      @reload-list="$emit('reload-list')"
    ></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,
      downloadIds: new Set(),
      selectedCourse: null,
    };
  },
  computed: {
    ...globalMapState(["user", "timeDifference"]),
    ...mapGetters(["isCug"]),
    // enableFeFeature() {
    //   return !!!this.FE_FEATURE_IMAGE_PDF;
    // },
  },
  methods: {
    async enterExam(course) {
      this.logger({
        page: "离线考试页面",
        button: "抽取试卷按钮",
        action: "点击",
        examStudentId: course.examStudentId,
      });
      // 若出错，直接报网络异常
      await this.$http.get(
        "/api/branch_ecs_oe_admin/offlineExam/startOfflineExam",
        {
          params: { examStudentId: course.examStudentId },
        }
      );
      this.$emit("reload-list");
    },
    previewPaper(course) {
      window._hmt.push(["_trackEvent", "离线考试页面", "预览"]);
      this.logger({
        page: "离线考试页面",
        button: "查看试卷按钮",
        action: "点击",
      });
      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();
        // delete the internal blob reference, to let the browser clear memory from it
        URL.revokeObjectURL(a.href);
        document.body.removeChild(a);
      } else {
        window.location.href = url;
      }
    },
    tempDisableBtnAndDownloadPaper(course) {
      window._hmt.push(["_trackEvent", "离线考试页面", "下载试卷"]);
      this.downloadIds.add(course.examStudentId);
      this.downloadIds = new Set(this.downloadIds);
      // this.$forceUpdate();
      // this.disableDownloadPaperBtn = true;
      setTimeout(() => {
        // this.disableDownloadPaperBtn = false;
        this.downloadIds.delete(course.examStudentId);
        this.downloadIds = new Set(this.downloadIds);
        // set 并不能正常的reactive
        // this.$forceUpdate();
      }, 10 * 1000);

      window.location.href =
        "/api/branch_ecs_ques/paper/export/" +
        course.paperId +
        "/PAPER/offLine?$key=" +
        this.user.key +
        "&$token=" +
        this.user.token;
    },
    downloadingCourse(course) {
      return this.downloadIds.has(course.examStudentId);
    },
    uploadHandler(course) {
      this.logger({
        page: "离线考试页面",
        button: "上传答案按钮",
        action: "点击",
      });
      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>
