import Vue from "vue";
import { createLog } from "@/utils/logger";

Vue.mixin({
  beforeCreate() {
    if (document.getElementById("app-placeholder"))
      document.getElementById("app-placeholder").remove();
  },
  mounted() {
    // console.log("mixin hook called");
    [...document.getElementsByTagName("a")].forEach(e => {
      e.addEventListener("click", function(event) {
        event.preventDefault();
      });
    });
  },
  methods: {
    logger(logs) {
      createLog(logs);
    },
    async serverLog(level, logText) {
      try {
        await this.$http.post(
          "/api/ecs_core/log/studentClient/" + level,
          logText,
          {
            headers: {
              "Content-Type": "text/plain",
            },
          }
        );
      } catch (error) {
        console.log(error);
      }
    },
    async checkExamInProgress() {
      try {
        // 断点续考
        // const examingRes = (await this.$http.get(
        //   "/api/ecs_oe_student/examControl/checkExamInProgress"
        // )).data;

        let examingRes;
        for (let i = 0; i < 4; i++) {
          examingRes = await this.$http.get(
            "/api/ecs_oe_student/examControl/checkExamInProgress"
          );
          if (
            examingRes.status === 503 ||
            examingRes.data.code === "S-101000"
          ) {
            await new Promise(resolve => setTimeout(() => resolve(), 2000));
            continue;
          } else if (examingRes.data.code === "000000") {
            break;
          }
        }
        if (examingRes.status !== 200 || examingRes.data.code !== "000000") {
          window._hmt.push([
            "_trackEvent",
            "断点续考处理异常",
            "调用断点续考接口超过次数",
          ]);
          throw "调用断点续考接口超过次数";
        }

        examingRes = examingRes.data.data; // 保持和原接口一致

        if (examingRes && examingRes.isExceed) {
          // 超出断点续考次数的逻辑，仅此block
          this.$Message.info({
            content: `超出最大断点续考次数(${examingRes.maxInterruptNum})，正在自动交卷...`,
            duration: 15,
            closable: true,
          });
          this.$Spin.show({
            render: () => {
              return (
                <div style="font-size: 24px">
                  超出最大断点续考次数({examingRes.maxInterruptNum}
                  )，正在自动交卷...
                </div>
              );
            },
          });
          // 断点续考消息一闪而过，此处可以加延迟
          // await new Promise(resolve => setTimeout(() => resolve(), 3000));
          const res = await this.$http.get(
            "/api/ecs_oe_student/examControl/endExam"
          );
          this.$Spin.hide();
          if (res.status === 200) {
            this.$router.replace({
              path: `/online-exam/exam/${examingRes.examId}/examRecordData/${examingRes.examRecordDataId}/end`,
            });
          } else {
            window._hmt.push(["_trackEvent", "断点续考处理异常", "交卷失败"]);
            this.$Message.error({
              content: "交卷失败",
              duration: 15,
              closable: true,
            });
            throw "交卷失败";
          }

          return true;
        }

        if (examingRes) {
          this.$Spin.show({
            render: () => {
              return <div style="font-size: 24px">正在进入断点续考...</div>;
            },
          });
          this.$router.push(
            `/online-exam/exam/${examingRes.examId}/examRecordData/${examingRes.examRecordDataId}/order/1`
          );
          setTimeout(() => this.$Spin.hide(), 1000);
          return true;
        }
      } catch (error) {
        this.$Spin.hide();
        window._hmt.push(["_trackEvent", "断点续考处理异常"]);
        this.$Message.error({
          content: "断点续考处理异常",
          duration: 15,
          closable: true,
        });
        throw error;
      }
    },
    logout(cause = "") {
      console.log("退出登录");
      this.logger({ action: "退出登录", cause });
      localStorage.removeItem("phoneVerified");
      window._hmt.push(["_trackEvent", "退出", cause]);
      const redirectUrl = sessionStorage.getItem("redirectUrl");
      if (redirectUrl) {
        this.$Modal.error({
          title: "确认返回",
          content: "",
          onOk: () => {
            window.location = redirectUrl;
          },
        });
      } else {
        this.$router.push("/login/" + localStorage.getItem("domain") + cause);
      }
    },
  },
});
