<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="this.$route.params.domain !== 'cugr.ecs.qmth.com.cn'" :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">
          远程教育网络考试
        </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('loginForm')">
                <i-icon type="ios-lock" slot="prepend"></i-icon>
              </i-input>
            </i-form-item>
            <i-form-item>
              <div v-if="errorInfo !== ''">
                <i-alert type="error" show-icon>{{errorInfo}}</i-alert>
              </div>
              <i-button size="large" class="qm-primary-button" long :disabled="disableLoginBtn" @click="login('loginForm')">登录</i-button>
            </i-form-item>
          </i-form>
        </div>
      </div>
    </div>

    <footer class="footer"></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 {
  data() {
    return {
      logoPath: "/api/ecs_core/org/logo?domain=" + 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
    };
  },
  async created() {
    if (this.$route.params.domain === "cugr.ecs.qmth.com.cn") {
      this.loginType = "STUDENT_IDENTITY_NUMBER";
    }
    this.$Message.config({
      duration: 15,
      size: "large",
      closable: true
    });

    try {
      const res = await this.$http.get(
        "/api/ecs_core/org/getRootOrgByCode?code=" + this.$route.params.domain
      );
      const productName = res.data.examSysName;
      this.productName = productName || "远程教育网络考试";
    } catch (e) {
      this.productName = "远程教育网络考试";
    }
    window.localStorage.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 (typeof nodeRequire != "undefined") {
      var that = this;
      var fs = window.nodeRequire("fs");
      var 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
            });
          } else {
            that.disableLoginBtn = false;
          }
        });
      } else {
        that.disableLoginBtn = false;
      }
    } else {
      this.disableLoginBtn = false;
    }
  },
  methods: {
    ...mapMutations(["updateUser"]),
    async login(name) {
      if (this.disableLoginBtn) {
        return;
      }
      this.disableLoginBtn = true;
      setTimeout(() => (this.disableLoginBtn = false), 5000);
      const valid = await this.$refs[name].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.$route.params.domain
      });
      let data = response.data;
      if (Math.abs(moment(response.headers.date).diff(moment())) > 30 * 1000) {
        this.$Message.error({
          content: "与服务器时间差异超过30秒，请校准本机时间之后再重试！",
          duration: 30
        });
        throw "与服务器时间差异超过30秒，请校准本机时间之后再重试！";
      }
      if (data.token) {
        this.errorInfo = "";
        //缓存用户信息
        window.sessionStorage.setItem("token", data.token);
        window.localStorage.setItem("key", data.key);
        window.localStorage.setItem("domain", this.$route.params.domain);

        try {
          const student = (await this.$http.get(
            "/api/ecs_core/student/getStudentInfoBySession"
          )).data;
          const user = { ...data, ...student };
          this.updateUser(user);
          window.localStorage.setItem("user-for-reload", JSON.stringify(user));
          this.$router.push("/online-exam");
        } catch (error) {
          this.$Message.error({
            content: "获取学生信息失败，请重试！",
            duration: 30
          });
        }
      } else {
        this.errorInfo = data.desc;
      }
    },
    closeApp() {
      window.close();
    }
  },
  computed: {
    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 {
  margin-left: -600px;
}

.logo-size {
  height: 100px;
  width: 300px;
  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>
