<template>
  <div class="home">
    <header class="header">
      <div class="school-logo">
        <img class="logo-size" :src="this.logoPath" alt="school logo" />
      </div>
      <a
        class="close"
        style="border-bottom-left-radius: 6px;"
        @click="closeApp"
      >
        关闭
      </a>
    </header>

    <div class="center">
      <div class="content">
        <div style="display:flex;">
          <a
            v-if="!LOGIN_ID_DOMAINS.includes(domainInUrl)"
            :class="[
              'qm-big-text',
              'login-type',
              loginType === 'STUDENT_CODE' && 'active-type'
            ]"
            @click="loginType = 'STUDENT_CODE'"
            style="border-top-left-radius: 6px"
          >
            学号登录
          </a>
          <a
            :class="[
              'qm-big-text',
              'login-type',
              loginType !== 'STUDENT_CODE' && 'active-type'
            ]"
            @click="loginType = 'STUDENT_IDENTITY_NUMBER'"
            style="border-top-right-radius: 6px"
          >
            身份证号登录
          </a>
        </div>

        <div class="qm-title-text" style="margin: 40px 0 20px 0">
          {{ productName }}
        </div>

        <div style="margin: 0 40px 40px 40px">
          <i-form ref="loginForm" :model="loginForm" :rules="loginFormRule">
            <i-form-item
              prop="accountValue"
              style="margin-bottom:35px;height:42px"
            >
              <i-input
                type="text"
                size="large"
                v-model="loginForm.accountValue"
                :placeholder="usernameInputPlaceholder"
              >
                <i-icon type="ios-person" slot="prepend"></i-icon>
              </i-input>
            </i-form-item>
            <i-form-item prop="password" style="margin-bottom:35px;height:42px">
              <i-input
                type="password"
                size="large"
                v-model="loginForm.password"
                :placeholder="passwordInputPlaceholder"
                @on-enter="login"
              >
                <i-icon type="ios-lock" slot="prepend"></i-icon>
              </i-input>
            </i-form-item>
            <i-form-item style="position: relative">
              <div
                v-if="errorInfo !== ''"
                style="position: absolute; top: -37px; width: 100%"
              >
                <i-alert type="error" show-icon>{{ errorInfo }}</i-alert>
              </div>
              <i-button
                size="large"
                class="qm-primary-button"
                long
                :disabled="disableLoginBtn"
                @click="login"
              >
                登录
              </i-button>
            </i-form-item>
          </i-form>
        </div>
      </div>
    </div>

    <footer class="footer">
      <div style="position: absolute; right: 20px; bottom: 20px;">
        版本: {{ VUE_APP_GIT_REPO_VERSION }}
      </div>
    </footer>
  </div>
</template>

<script>
import moment from "moment";
import { mapMutations } from "vuex";
/**
 * 在任何组件需要强制退出，做以下步骤
 * 1. this.$Message.info()
 * 2. this.$router.push("/login"+domain);
 * 因为在/login里会删除localStorage的token，而在router.beforeEach会检查是否有token，达到退出的目的。
 */

export default {
  name: "Login",
  data() {
    return {
      LOGIN_ID_DOMAINS: ["cugr.ecs.qmth.com.cn", "cugbr.ecs.qmth.com.cn"],
      domainInUrl: this.$route.params.domain,
      productName: "",
      loginType: "STUDENT_CODE",
      errorInfo: "",
      loginForm: {
        accountValue: "",
        password: ""
      },
      loginFormRule: {
        accountValue: [
          {
            required: true,
            message: "请填写登录账号",
            trigger: "blur"
          }
        ],
        password: [
          {
            required: true,
            message: "请填写密码",
            trigger: "blur"
          }
        ]
      },
      disableLoginBtn: true,
      VUE_APP_GIT_REPO_VERSION: process.env.VUE_APP_GIT_REPO_VERSION
    };
  },
  async mounted() {
    await this.checkNewVersion();
  },
  async created() {
    if (this.LOGIN_ID_DOMAINS.includes(this.schoolDomain)) {
      this.loginType = "STUDENT_IDENTITY_NUMBER";
    }
    this.$Message.config({
      duration: 15,
      size: "large",
      closable: true // 没有影响到所有的组件。。。  https://github.com/iview/iview/issues/2962
    });

    try {
      const res = await this.$http.get(
        "/api/ecs_core/org/propertyNoSession/OE_STUDENT_SYS_NAME?domainName=" +
          this.schoolDomain
      );
      const productName = res.data;
      this.productName = productName || "远程教育网络考试";
    } catch (e) {
      this.productName = "远程教育网络考试";
    }
    window.sessionStorage.removeItem("token");
    window.localStorage.removeItem("key");
    if (localStorage.getItem("user-for-reload")) {
      this.loginForm.accountValue = JSON.parse(
        localStorage.getItem("user-for-reload")
      ).studentCode;
      this.loginForm.password =
        process.env.NODE_ENV === "production" ? "" : "180613";
    }

    if (
      this.$route.path.includes("xjtu.ecs.qmth.com.cn") ||
      this.$route.path.includes("snnu.ecs.qmth.com.cn") ||
      this.$route.path.includes("cup.ecs.qmth.com.cn")
    ) {
      this.disableLoginBtn = true;
      if (
        typeof nodeRequire == "undefined" ||
        !window.nodeRequire("fs").existsSync("multiCamera.exe")
      ) {
        this.$Message.error({
          content: "请与学校申请最新的客户端，进行考试！",
          duration: 2 * 24 * 60 * 60
        });

        return; // 避免 disableLoginBtn 被覆盖
      }
    }

    if (typeof nodeRequire != "undefined") {
      var that = this;
      var fs = window.nodeRequire("fs");
      var config;
      try {
        config = fs.readFileSync(process.cwd() + "/" + "config.js", "utf-8");
        console.log("使用旧客户端");
      } catch (error) {
        console.log("尝试使用新客户端");
        config = fs.readFileSync("config.js", "utf-8");
      }
      var nameJson = JSON.parse(config);

      let electronConfig = null;
      try {
        electronConfig = (await this.$http.get(
          "https://ecs.qmth.com.cn:8878/electron-config/" +
            nameJson.name +
            ".js"
        )).data;
      } catch (error) {
        this.$Message.error("获取机构的客户端设置失败，请退出后重试！");
        return;
      }

      //如果配置中配置了  checkRemoteControl:true
      if (electronConfig.otherConfig.checkRemoteControl) {
        window.nodeRequire("node-cmd").get("Project1.exe", function() {
          var applicationNames = fs.readFileSync(
            "remoteApplication.txt",
            "utf-8"
          );
          if (applicationNames && applicationNames.trim()) {
            that.disableLoginBtn = true;
            that.$Message.info({
              content:
                "在考试期间，请关掉" +
                applicationNames.trim() +
                "软件，诚信考试。",
              duration: 30,
              closable: true
            });
          } else {
            that.disableLoginBtn = false;
          }
        });
      } else {
        that.disableLoginBtn = false;
      }
    } else {
      this.disableLoginBtn = false;
    }
  },
  methods: {
    ...mapMutations(["updateUser", "updateTimeDifference"]),
    async login() {
      if (this.disableLoginBtn) {
        return;
      }
      await this.checkNewVersion();
      this.disableLoginBtn = true;
      setTimeout(() => (this.disableLoginBtn = false), 5000);
      // https://www.cnblogs.com/weiqinl/p/6708993.html
      const valid = await this.$refs.loginForm.validate();
      if (valid) {
        console.log("form validated. start login...");
      } else {
        return;
      }

      let repPara = this.loginForm;
      // 以下网络请求失败，直接报网络异常错误
      const response = await this.$http.post("/api/ecs_core/auth/login", {
        ...repPara,
        accountType: this.loginType,
        domain: this.schoolDomain,
        alwaysOK: true
      });
      let data = response.data;
      // if (
      //   Math.abs() >
      //   5 * 60 * 1000
      // ) {
      //   window._hmt.push(["_trackEvent", "登录页面", "本机时间误差过大"]);
      //   this.$Message.error({
      //     content: "与服务器时间差异超过5分钟，请校准本机时间之后再重试！",
      //     duration: 30
      //   });
      //   throw "与服务器时间差异超过5分钟，请校准本机时间之后再重试！";
      // }

      this.updateTimeDifference(moment(response.headers.date).diff(moment()));
      if (data.code == "200") {
        data = data.content;
        this.errorInfo = "";
        //缓存用户信息
        window.sessionStorage.setItem("token", data.token);
        window.localStorage.setItem("key", data.key);
        window.localStorage.setItem("domain", this.schoolDomain);

        try {
          const student = (await this.$http.get(
            "/api/ecs_core/student/getStudentInfoBySession"
          )).data;
          const specialty = (await this.$http.get(
            "/api/ecs_exam_work/exam_student/specialtyNameList/"
          )).data;
          const user = { ...data, ...student, specialty: specialty.join() };
          this.updateUser(user);
          window.localStorage.setItem("user-for-reload", JSON.stringify(user));

          window._hmt.push([
            "_trackEvent",
            "登录页面",
            "登录",
            this.$route.query.LogoutReason
          ]);
          await this.checkExamInProgress();
          window._hmt.push(["_trackEvent", "登录页面", "登录成功"]);
        } catch (error) {
          window._hmt.push([
            "_trackEvent",
            "登录页面",
            "登录失败",
            "getStudentInfoBySession失败"
          ]);
          this.$Message.error({
            content: "获取学生信息失败，请重试！",
            duration: 30,
            closable: true
          });
        }
      } else {
        window._hmt.push(["_trackEvent", "登录页面", "登录失败", data.desc]);
        this.errorInfo = data.desc;
      }
    },
    async checkExamInProgress() {
      try {
        // 断点续考
        const examingRes = (await this.$http.get(
          "/api/ecs_oe_student/examControl/checkExamInProgress"
        )).data;
        if (examingRes.isExceed) {
          // 超出断点续考次数的逻辑，仅此block
          this.$Spin.show({
            render: () => {
              return (
                <div style="font-size: 24px">
                  `超出最大断点续考次数(${examingRes.maxInterruptNum}
                  )，正在自动交卷...`
                </div>
              );
            }
          });
          const res = await this.$http.get(
            "/api/ecs_oe_student/examControl/endExam"
          );
          if (res.status === 200) {
            this.$router.replace({
              path: `/online-exam/exam/${examingRes.examId}/examRecordData/${
                examingRes.examRecordDataId
              }/end`
            });
            this.$Spin.hide();
          } else {
            this.$Message.error("交卷失败");
          }
          return;
        }
        if (examingRes) {
          this.$Spin.show({
            render: () => {
              return <div style="font-size: 24px">正在进入断点续考...</div>;
            }
          });
          window._hmt.push(["_trackEvent", "登录页面", "断点续考", "重新登录"]);
          this.$router.push(
            `/online-exam/exam/${examingRes.examId}/examRecordData/${
              examingRes.examRecordDataId
            }/order/1` +
              (examingRes.faceVerifyMinute
                ? `?faceVerifyMinute=${examingRes.faceVerifyMinute}`
                : "")
          );
          setTimeout(() => this.$Spin.hide(), 1000);
          return;
        }
        this.$router.push("/online-exam");
      } catch (error) {
        this.$Message.error("获取断点续考信息异常，退出登录");
        this.logout("?LogoutReason=登录页面获取断点续考信息异常");
        return;
      }
    },
    async checkNewVersion() {
      let myHeaders = new Headers();
      myHeaders.append("Content-Type", "application/javascript");
      myHeaders.append("Cache-Control", "no-cache");
      const response = await fetch(
        document.scripts[document.scripts.length - 1].src,
        {
          headers: myHeaders
        }
      );
      if (!response.ok) {
        window._hmt.push([
          "_trackEvent",
          "登录页面",
          "新版本发布后，客户端自动刷新"
        ]);
        location.reload(true);
      }
    },
    closeApp() {
      window.close();
    }
  },
  computed: {
    logoPath() {
      return "/api/ecs_core/org/logo?domain=" + this.domainInUrl;
    },
    schoolDomain() {
      const domain = this.domainInUrl;
      if (!domain || !domain.includes("qmth.com.cn")) {
        this.$Message.error("机构地址出错，请关闭程序后再登录。");
      }
      return domain;
    },
    usernameInputPlaceholder() {
      if (this.loginType === "STUDENT_CODE") {
        return "请输入学号";
      } else {
        return "请输入身份证号";
      }
    },
    passwordInputPlaceholder() {
      if (this.loginType === "STUDENT_CODE") {
        return "初始密码为身份证号后6位";
      } else {
        return "初始密码为身份证号后6位";
      }
    }
  }
};
</script>

<style scoped>
.home {
  display: flex;
  flex-direction: column;
  height: 100vh;
}

.school-logo {
  justify-self: flex-start;
  margin-left: 100px;
}

.logo-size {
  height: 100px;
  width: 400px;
  object-fit: cover;
}

.header {
  min-height: 120px;
  display: grid;
  align-items: center;
  justify-items: center;
}

.center {
  background-image: url("./bg.jpg");
  background-position: center;
  background-repeat: no-repeat;
  background-size: cover;
  width: 100vw;
  min-height: 600px;
}

.content {
  margin-top: 100px;
  margin-left: 65%;
  width: 300px;
  border-radius: 6px;
  background-color: white;
  display: grid;
  grid-template-areas: "";
}

.login-type {
  flex: 1;
  line-height: 40px;
  background-color: #eeeeee;
}

.active-type {
  background-color: #ffffff;
}

.close {
  position: absolute;
  top: 0;
  right: 0;
  background-color: #eeeeee;
  color: #999999;
  width: 80px;
  height: 40px;
  line-height: 40px;
}

.close:hover {
  color: #444444;
}
</style>

<style>
.ivu-message-notice-content-text {
  font-size: 32px;
}
.ivu-message-notice-content-text i.ivu-icon {
  font-size: 32px;
}
</style>
