<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>最近正确率</td>
          <td>平均正确率</td>
          <td>最高正确率</td>
          <td style="max-width: 200px">操作</td>
        </tr>

        <tr v-for="course in courses" :key="course.courseId">
          <td>{{ course.courseName }}</td>
          <td>
            {{ course.startTime }} <br />
            ~ <br />
            {{ course.endTime }}
          </td>
          <td>
            <span v-html="cycleDesc(course)" />
          </td>
          <td>{{ course.practiceCount }}</td>
          <td>{{ course.recentObjectiveAccuracy }}%</td>
          <td>{{ course.aveObjectiveAccuracy }}%</td>
          <td>{{ course.maxObjectiveAccuracy }}%</td>
          <td style="min-width: 180px">
            <div
              style="
                display: grid;
                grid-template-columns: repeat(auto-fit, minmax(100px, 1fr));
                grid-gap: 10px;
              "
            >
              <i-button
                class="qm-primary-button qm-primary-button-padding-fix"
                :disabled="disableTheCourse(course) || enterButtonClicked"
                :title="disableTheCourse(course) ? disableReason(course) : ''"
                @click="enterPractice(course)"
              >
                进入练习
              </i-button>
              <i-button
                class="qm-primary-button qm-primary-button-padding-fix"
                @click="enterPracticeList(course)"
              >
                查看详情
              </i-button>
            </div>
          </td>
        </tr>
      </tbody>
    </table>
  </div>
</template>

<script>
import { createNamespacedHelpers } from "vuex";
import moment from "moment";
import { mapState as globalMapState } from "vuex";
const { mapMutations } = createNamespacedHelpers("examHomeModule");

export default {
  name: "OnlinePracticeList",
  props: {
    courses: {
      type: Array,
      default() {
        return [];
      },
    },
  },
  data() {
    return { now: new Date(), selectedCourse: null, enterButtonClicked: false };
  },
  computed: {
    ...globalMapState(["user", "timeDifference"]),
  },
  created() {
    this.getNow();
    this.intervalID = setInterval(() => this.getNow(), 1000);
  },
  beforeDestroy() {
    clearInterval(this.intervalID);
  },
  methods: {
    ...mapMutations(["toggleFaceCheckModal"]),
    cycleDesc(course) {
      if (!course.examCycleEnabled) {
        return "";
      }
      const weekdayNames = {
        1: "一",
        2: "二",
        3: "三",
        4: "四",
        5: "五",
        6: "六",
        7: "日",
      };
      const weekDesc = course.examCycleWeek.map((v) => "周" + weekdayNames[v]);
      const timeRangeDesc = course.examCycleTimeRange
        .map((v) => v.timeRange)
        .map((v) => v[0] + "~" + v[1])
        .join("<br>");
      return weekDesc + "<br>" + timeRangeDesc;
    },
    getNow() {
      this.now = Date.now() + this.timeDifference;
    },
    courseInBetween(course) {
      return moment(this.now).isBetween(
        moment(course.startTime),
        moment(course.endTime)
      );
    },
    disableReason(course) {
      if (!this.courseInBetween(course)) {
        return "当前时间不在练习开放时间范围";
      } else if (course.allowExamCount < 1) {
        return "无剩余练习次数";
      } else if (this.countdown > 0) {
        return "请稍后点击";
      } else if (!this.courseInCycle(course)) {
        return "不在练习时间周期内";
      } else {
        return "";
      }
    },
    courseInCycle(course) {
      if (!course.examCycleEnabled) {
        return true;
      }
      const weekday = moment(this.now).isoWeekday();
      if (!course.examCycleWeek.includes(weekday)) {
        return false;
      }
      const HHmm = moment(this.now).format("HH:mm");
      const ranges = course.examCycleTimeRange.map((v) => v.timeRange);
      // console.log(HHmm, ranges);
      // console.log(HHmm > "11:00" && HHmm < "23:00");
      const inRange = ranges.some((v) => HHmm >= v[0] && HHmm <= v[1]);
      // console.log(inRange);
      return inRange;
    },
    disableTheCourse(course) {
      return (
        !this.courseInBetween(course) ||
        course.allowExamCount < 1 ||
        this.countdown > 0 ||
        !this.courseInCycle(course)
      );
    },
    async enterPractice(course) {
      this.enterButtonClicked = true;
      try {
        this.logger({
          page: "在线练习页面",
          button: "进入练习按钮",
          action: "点击",
        });
        const alreadyInExam = await this.checkExamInProgress();
        if (alreadyInExam) {
          window._hmt.push(["_trackEvent", "在线练习页面", "断点续考", "进入"]);
          this.logger({ action: "断点续考", detail: "在线练习页面" });
          return;
        }

        window._hmt.push(["_trackEvent", "在线练习页面", "进入练习"]);
        this.$router.push(
          `/online-exam/exam/${course.examId}/overview?examStudentId=${course.examStudentId}`
        );
      } finally {
        this.enterButtonClicked = false;
      }
    },
    async enterPracticeList(course) {
      this.logger({
        page: "在线练习页面",
        button: "查看详情按钮",
        action: "点击",
      });
      this.$router.push(
        `/online-practice/exam/${course.examId}/list?examStudentId=${
          course.examStudentId
        }&examName=${encodeURIComponent(
          course.examName
        )}&courseName=${encodeURIComponent(course.courseName)}`
      );
    },
  },
};
</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>

<style>
.online-exam-list-override-poptip .ivu-poptip-rel {
  width: 100%;
}
</style>
