<template>
  <div class="login">
    <!-- 左侧 -->
    <div class="leftBox">
      <div class="leftIcon">
        <div class="Icon"></div>
        <div>智慧调解系统</div>
      </div>
      <div class="leftImage"></div>
    </div>
    <!-- 右侧 -->
    <div class="rightBox">
      <el-form
        ref="loginForm"
        :model="loginForm"
        :rules="loginRules"
        class="login-form"
      >
        <h2 class="title">用户登录</h2>
        <el-form-item prop="username">
          <el-input
            v-model="loginForm.username"
            type="text"
            auto-complete="off"
            placeholder="账号"
          >
            <svg-icon
              slot="prefix"
              icon-class="user"
              class="el-input__icon input-icon"
            />
          </el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            v-model="loginForm.password"
            type="password"
            auto-complete="off"
            placeholder="密码"
            @keyup.enter.native="handleLogin"
          >
            <svg-icon
              slot="prefix"
              icon-class="password"
              class="el-input__icon input-icon"
            />
          </el-input>
        </el-form-item>
        <el-form-item prop="code" v-if="captchaEnabled">
          <el-input
            v-model="loginForm.code"
            auto-complete="off"
            placeholder="验证码"
            style="width: 63%"
            @keyup.enter.native="handleLogin"
          >
            <svg-icon
              slot="prefix"
              icon-class="validCode"
              class="el-input__icon input-icon"
            />
          </el-input>
          <div class="login-code">
            <img :src="codeUrl" @click="getCode" class="login-code-img" />
          </div>
        </el-form-item>
        <el-checkbox
          v-model="loginForm.rememberMe"
          style="margin: 0px 0px 25px 0px"
          >记住密码</el-checkbox
        >
        <el-form-item style="width: 100%">
          <el-button
            :loading="loading"
            size="medium"
            type="primary"
            style="width: 100%"
            @click.native.prevent="handleLogin"
          >
            <span v-if="!loading">登 录</span>
            <span v-else>登 录 中...</span>
          </el-button>
          <div style="float: right" v-if="register">
            <!-- <router-link class="link-type" :to="'/register'">立即注册</router-link> -->
            <el-button
              type="text"
              v-if="buttonReg"
              @click="registrationLink('/register')"
              >立即注册</el-button
            >
          </div>
          <div class="registerImg" v-show="closeImgs">
            <div class="closeImg" @click="closeImg">
              <img
                style="width: 25px; height: 25px"
                src="../assets/images/closed.png"
                alt=""
              />
              <span style="padding-left: 100px">扫码人脸核验</span>
            </div>
            <div id="qrcodeImg" style="padding-left: 76px"></div>
          </div>
        </el-form-item>
      </el-form>
    </div>
    <!-- 注册时选择是否 -->
    <div>
      <el-dialog
        title="是否需要人脸核实"
        :visible.sync="centerDialogVisible"
        width="30%"
        center
      >
        <span slot="footer" class="dialog-footer">
          <el-button @click="facialVerification('/register')" type="primary"
            >是</el-button
          >
          <el-button @click="noFacialVerification('/register')" type="primary"
            >否</el-button
          >
        </span>
      </el-dialog>
    </div>
    <!--  底部  -->
    <div class="el-login-footer">
      <div>Copyright © 2023 乙巢（上海）企业管理服务有限公司.</div>
      <div>Version：1.1.3</div>
    </div>
  </div>
</template>

<script>
import {
  getCodeImg,
  selectIdentityAuthenticaEIDtoken,
  selectPCEIDtokenStatus,
} from "@/api/login";
import Cookies from "js-cookie";
import QRCode from "qrcodejs2";
import { encrypt, decrypt } from "@/utils/jsencrypt";

export default {
  name: "Login",
  data() {
    return {
      codeUrl: "",
      closeImgs: false,
      centerDialogVisible: false,
      buttonReg: true,
      eidTokens: {},
      timer: null,
      pathVal: "",
      loginForm: {
        username: "admin",
        password: "admin123",
        rememberMe: false,
        code: "",
        uuid: "",
      },
      loginRules: {
        username: [
          { required: true, trigger: "blur", message: "请输入您的账号" },
        ],
        password: [
          { required: true, trigger: "blur", message: "请输入您的密码" },
        ],
        code: [{ required: true, trigger: "change", message: "请输入验证码" }],
      },
      loading: false,
      // 验证码开关
      captchaEnabled: true,
      // 注册开关
      register: true,
      redirect: undefined,
    };
  },
  watch: {
    $route: {
      handler: function (route) {
        this.redirect = route.query && route.query.redirect;
      },
      immediate: true,
    },
  },
  created() {
    this.getCode();
    this.getCookie();
  },
  methods: {
    getCode() {
      getCodeImg().then((res) => {
        this.captchaEnabled =
          res.captchaEnabled === undefined ? true : res.captchaEnabled;
        if (this.captchaEnabled) {
          this.codeUrl = "data:image/gif;base64," + res.img;
          this.loginForm.uuid = res.uuid;
        }
      });
    },
    getCookie() {
      const username = Cookies.get("username");
      const password = Cookies.get("password");
      const rememberMe = Cookies.get("rememberMe");
      this.loginForm = {
        username: username === undefined ? this.loginForm.username : username,
        password:
          password === undefined ? this.loginForm.password : decrypt(password),
        rememberMe: rememberMe === undefined ? false : Boolean(rememberMe),
      };
    },
    handleLogin() {
      this.$refs.loginForm.validate((valid) => {
        if (valid) {
          this.loading = true;
          if (this.loginForm.rememberMe) {
            Cookies.set("username", this.loginForm.username, { expires: 30 });
            Cookies.set("password", encrypt(this.loginForm.password), {
              expires: 30,
            });
            Cookies.set("rememberMe", this.loginForm.rememberMe, {
              expires: 30,
            });
          } else {
            Cookies.remove("username");
            Cookies.remove("password");
            Cookies.remove("rememberMe");
          }
          this.$store
            .dispatch("Login", this.loginForm)
            .then(() => {
              this.$router.push({ path: this.redirect || "/" }).catch(() => {});
            })
            .catch(() => {
              this.loading = false;
              if (this.captchaEnabled) {
                this.getCode();
              }
            });
        }
      });
    },
    // 生成二维码
    qrcode(url) {
      // 前端根据 URL 生成微信支付二维码
      document.getElementById("qrcodeImg").innerHTML = "";
      return new QRCode("qrcodeImg", {
        width: 200,
        height: 200,
        text: url,
        colorDark: "#000",
        colorLight: "#fff",
      });
    },
    registrationLink(path) {
      this.centerDialogVisible = true;
    },
    // 是人脸核实
    facialVerification(path) {
      this.centerDialogVisible = false;
      this.pathVal = path;
      // clearInterval(this.timer);
      selectIdentityAuthenticaEIDtoken().then((res) => {
        this.closeImgs = true;
        this.buttonReg = false;
        let url = res.data.Url;
        this.eidTokens = {
          eidToken: res.data.EidToken,
        };
        this.timer = setInterval(() => {
          this.getSelectPCEIDtokenStatus(this.eidTokens);
        }, 10000);
        this.qrcode(url);
      });
    },
    // 不用人脸核实
    noFacialVerification(path) {
      this.$router.push(path);
    },
    // H5轮询获取E证通Token状态
    getSelectPCEIDtokenStatus(data) {
      selectPCEIDtokenStatus(data).then((res) => {
        if (res.data.certificationStatus == 0) {
          // this.$router.push(this.pathVal);
          this.$router.push({
            path:this.pathVal,
            query:{
              identityNo:res.data.identityNo,
              name:res.data.name
            }
          })
        }
      });
    },
    // 关闭弹框
    closeImg() {
      clearInterval(this.timer);
      this.closeImgs = false;
      this.buttonReg = true;
    },
  },
  beforeDestroy() {
    // 清除计时器
    if (this.timer) {
      clearInterval(this.timer);
    }
  },
};
</script>

<style rel="stylesheet/scss" lang="scss">
.login {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;

  .leftBox {
    width: 50%;
    height: 90%;

    .leftIcon {
      height: 20%;
      width: 100%;
      margin: 0% 10% 1% 15%;

      .Icon {
        width: 100px;
        height: 105px;
        background-image: url("../assets/images/logos.png");
        background-size: cover;
      }

      div {
        font-size: 18px;
      }
    }

    .leftImage {
      width: 100%;
      height: 90%;
      margin-left: 10%;
      margin-top: -15%;
      background-image: url("../assets/images/login.svg");
      background-size: cover;
    }
  }

  .rightBox {
    width: 50%;
    height: 90%;
    display: flex;
    justify-content: center;
    align-items: center;
  }
}

.title {
  margin: 0px auto 30px auto;
  text-align: center;
  color: #1296db;
  font-weight: 600;
}

.login-form {
  border-radius: 6px;
  background: #ffffff;
  width: 400px;
  padding: 25px 25px 5px 25px;

  .el-input {
    height: 38px;

    input {
      height: 38px;
    }
  }

  .input-icon {
    height: 39px;
    width: 14px;
    margin-left: 2px;
  }
}

.login-tip {
  font-size: 13px;
  text-align: center;
  color: #bfbfbf;
}

.login-code {
  width: 33%;
  height: 38px;
  float: right;

  img {
    cursor: pointer;
    vertical-align: middle;
  }
}

.el-login-footer {
  background-color: rgb(126, 131, 135);
  height: 55px;
  line-height: 55px;
  position: fixed;
  bottom: 0;
  width: 100%;
  text-align: center;
  color: #fff;
  font-family: Arial;
  font-size: 12px;
  letter-spacing: 1px;

  div {
    height: 30%;
  }
}

.registerImg {
  border: 1px solid #c0c0c0;
  width: 350px;
  height: 250px;
}
.login-code-img {
  height: 38px;
}
</style>
