<template>
  <main-layout>
    <Breadcrumb
      style="text-align: left; padding-left: 20px; height: 40px; line-height: 40px; 
                       background-color: #fafafa;"
    >
      当前所在位置：
      <BreadcrumbItem>{{ locationTitle }}</BreadcrumbItem>
    </Breadcrumb>

    <div class="home">
      <ecs-online-list :courses="courses"></ecs-online-list>
    </div>

    <PhoneVerifyForDD />
  </main-layout>
</template>

<script>
import EcsOnlineList from "./OnlineExamList.vue";
import PhoneVerifyForDD from "./PhoneVerifyForDD.vue";
import { mapMutations, mapState, mapGetters } from "vuex";

export default {
  name: "OnlineExamHome",
  components: {
    "ecs-online-list": EcsOnlineList,
    PhoneVerifyForDD,
  },
  props: {
    examType: {
      type: String,
      default: "ONLINE",
    },
  },
  data() {
    return {
      previousUrl: "",
      autoCloseModal: 10,
      courses: [],
    };
  },
  computed: {
    ...mapState(["user", "siteMessagesTimeStamp", "menus"]),
    ...mapGetters(["isEpcc"]),
    locationTitle() {
      return (
        this.menus.find(
          v => v.link.toUpperCase() === this.$route.path.toUpperCase()
        ) || {}
      ).name;
    },
  },
  beforeRouteEnter(to, from, next) {
    next(vm => {
      vm.previousUrl = from.path;
      if (
        from.path.includes("/online-homework") ||
        from.path.includes("/online-exam")
      ) {
        vm.getData();
      }
    });
  },
  watch: {
    menus() {
      if (this.menus[0]) {
        if (this.menus[0].link.toUpperCase() !== "/online-exam".toUpperCase()) {
          this.$router.push(this.menus[0].link);
          return;
        }
      } else {
        this.$Message.error({
          content: "无可用菜单",
          duration: 15,
          closable: true,
        });
        this.logout();
      }
    },
  },
  beforeMount() {
    this.$nextTick(() => {
      if (
        this.previousUrl.startsWith("/login/") &&
        process.env.NODE_ENV !== "development"
      ) {
        const os = window.navigator.userAgent.match(
          /Intel Mac OS X (\d+)_(\d+)_(\d+)/
        );

        let macosVersionTooLow = false;
        if (os && +(os[2] + "." + os[3]) < 14.6) {
          macosVersionTooLow = true;
        }
        this.$Modal.info({
          render: () => (
            <div class="welcome-modal">
              <div class="smile-png" />
              <div style="margin-left: 20px; flex: 1">
                <div style="margin-bottom: 1.5em">
                  欢迎使用考试系统，祝顺利完成考试！
                </div>
                <div style="font-weight:bold; line-height: 25px;">
                  姓名：{this.$store.state.user.name} -{" "}
                  {this.$store.state.user.studentCodeList.join(",")}
                </div>
                {!this.isEpcc && (
                  <div style="font-weight:bold; line-height: 25px;">
                    专业：{this.$store.state.user.specialty}
                  </div>
                )}
                {macosVersionTooLow && (
                  <div style="font-weight:bold; line-height: 25px; color: red">
                    您的操作系统版本过低，为保证考试过程顺利完成，请更新操作系统到
                    macOS Mojave (10.14.5) 以上！
                  </div>
                )}
              </div>
            </div>
          ),
          onOk: () => {
            clearInterval(this.interval);
          },
        });
        this.interval = setInterval(() => {
          this.autoCloseModal--;
          if (this.autoCloseModal <= 0) {
            this.$Modal.remove();
            clearInterval(this.interval);
          }
        }, 1000);
      }
    });
  },
  async mounted() {
    let page;
    if (this.examType === "ONLINE") {
      page = "在线考试列表页面";
    } else if (this.examType === "ONLINE_HOMEWORK") {
      page = "在线练习列表页面";
    }
    window._hmt.push(["_trackEvent", page, "进入页面"]);
    this.logger({ page, action: "进入页面" });

    await this.getData();
  },
  beforeDestroy() {
    clearInterval(this.interval);
  },
  methods: {
    ...mapMutations(["updateSiteMessages"]),
    async getData() {
      this.courses = [];
      let examListRes;
      for (let i = 0; i < 4; i++) {
        let url;
        if (this.examType === "ONLINE") {
          url = "/api/ecs_oe_admin/examControl/queryExamList";
        } else if (this.examType === "ONLINE_HOMEWORK") {
          url = "/api/ecs_oe_admin/examControl/queryHomeworkList";
        }
        examListRes = await this.$http.get(url);
        if (examListRes.status === 503) {
          await new Promise(resolve => setTimeout(() => resolve(), 2000));
          continue;
        } else if (examListRes.status === 200) {
          break;
        }
      }

      if (examListRes.status !== 200) {
        window._hmt.push([
          "_trackEvent",
          "待考列表获取失败",
          "调用待考列表获取接口超过失败次数",
        ]);
        this.$Message.error({
          content: "服务器繁忙(503)！请稍后重试。",
          duration: 15,
          closable: true,
        });
        return;
      } else {
        this.courses = examListRes.data || [];
      }

      try {
        const noticeRes = (await this.$http.get(
          "/api/ecs_exam_work/notice/getUserNoticeList?" +
            this.user.id +
            this.siteMessagesTimeStamp
        )).data;
        // const noticeRes = [
        //   {
        //     content: "<div>公告<img src='./svgs/sms-read.svg' /></div>",
        //     hasRead: true,
        //     id: 0,
        //     publishTime: "2019-07-08T11:23:34.646Z",
        //     publisher: "string",
        //     title: "string",
        //   },
        // ];
        // noticeRes.forEach(
        //   v =>
        //     (v.publishTime = moment(v.publishTime).format("YYYY-MM-DD hh:mm:ss"))
        // );
        this.updateSiteMessages(noticeRes);
      } catch (error) {
        console.log(error);
        this.$Message.error({
          content: "获取公告通知异常",
          duration: 15,
          closable: true,
        });
      }
    },
  },
};
</script>

<style scoped>
.home {
  margin: 20px;
}
.welcome-modal {
  display: flex;
  margin-top: 26px;
  margin-left: 20px;
}
.smile-png {
  width: 40px;
  height: 40px;
  background: url(./smile-icon.png);
}
</style>
