<template>
  <div :style="{'background':backgroundImg ? 'url('+backgroundImg+')' :'url('+defaultBgImg+')'}" class="login-container">
    <el-form ref="loginForm" :model="loginForm" :rules="loginRules" class="login-form" auto-complete="on" label-position="left">
      <div class="title-container flex-wrap">
        <el-avatar :size="36" :src="imgSrc" @error="errorHandler">
          <img src="@/assets/logo/error.png">
        </el-avatar>
        <!-- <el-divider direction="vertical"></el-divider> -->
        <div class="content-box">
          <div class="title">{{ pageTitle }}</div>
        </div>
      </div>

      <el-form-item prop="username">
        <el-input ref="username" v-model="loginForm.username" placeholder="用户名" name="username" type="text" tabindex="1" auto-complete="on" />
      </el-form-item>

      <el-form-item prop="password">
        <el-input ref="password" v-model="loginForm.password" show-password placeholder="密码" name="password" tabindex="2" auto-complete="on" />
      </el-form-item>

      <div v-if="isCode" class="flex-wrap">
        <el-form-item class="flex1" prop="identify">
          <el-input ref="identify" v-model="loginForm.identify" placeholder="请输入验证码" name="identify" tabindex="3" auto-complete="on" @keyup.enter.native="handleLogin" />
        </el-form-item>
        <img @click="changeCode" style="width: 116px;height: 40px;margin-left: 18px;cursor: pointer;" :src="baseImg" alt="验证码">
      </div>

      <el-button :loading="loading" type="primary" style="width: 100%;margin-top: 18px;height: 42px;border-radius: 2px;" @click.native.prevent="handleLogin">登录</el-button>
    </el-form>
  </div>
</template>

<script>
import { isValue } from "@/utils/validate";
import { getVCode, getToken, getKey, forceLogin } from "@/api/login";
import { setToken, TokenKey, getUserId, setCodeToken } from '@/utils/auth';
import MD5 from 'blueimp-md5'
import JSEncrypt from "jsencrypt";
const defaultBgImg = require('@/assets/loginpage/bg.jpg')
export default {
  name: "Login",
  data () {
    return {
      flag: false,
      PwdMessage: null,
      loginForm: {
        username: "",
        password: "",
        identify: "",
      },
      loginRules: {
        username: [
          { required: true, trigger: "blur", message: "请输入用户名" },
        ],
        password: [{ required: true, trigger: "blur", message: "请输入密码" }],
        identify: [
          { required: true, trigger: "blur", message: "请输入验证码" },
        ],
      },
      loading: false,
      passwordType: "password",
      redirect: undefined,
      isCode: false,
      pageTitle: '',
      imgSrc: '',
      baseImg: '',
      appId: '',
      backgroundImg: '',
      defaultBgImg
    };
  },
  async created () {
    try {
      const { code, returnData, message } = await getToken({
        'appid': PLATFROM_CONFIG.appId,
        'appsecret': PLATFROM_CONFIG.appKeyString
      })
      if (code == 0 && isValue(returnData)) {
        const { appname, background, logo, securitycoderule, smalllogo, token } = returnData;
        this.imgSrc = logo
        this.pageTitle = appname ?? '行李全流程跟踪系统'
        this.isCode = securitycoderule
        this.backgroundImg = background
        setToken(TokenKey, token);
        sessionStorage.setItem('appConfig', JSON.stringify({ ...returnData }))
        // setToken('active_duration', active_duration);
        sessionStorage.setItem('appLog', logo)
        sessionStorage.setItem('appName', this.pageTitle)
        if (securitycoderule) {
          this.getCheckCode()
        }
      } else {
        this.$router.push('/404')
      }
    } catch (error) {
      this.$message.error(error.message);
    }
  },
  methods: {
    showPwd () {
      if (this.passwordType === "password") {
        this.passwordType = "";
      } else {
        this.passwordType = "password";
      }
      this.$nextTick(() => {
        this.$refs.password.focus();
      });
    },
    // 登录前获取公匙
    handleLogin () {
      this.$refs.loginForm.validate(async (valid) => {
        if (valid) {
          const { code, message, returnData } = await getKey();
          if (code == 0 && isValue(returnData)) {
            const { pubKeyStr } = returnData
            sessionStorage.setItem('pubKeyStr', pubKeyStr)
            this.qdLogin(pubKeyStr)
          } else {
            this.$message.error(message);
          }

        } else {
          return false;
        }
      });
    },
    //确认登录
    qdLogin (pubKeyStr) {
      this.loading = true;
      const jse = new JSEncrypt()
      jse.setPublicKey(pubKeyStr)
      const params = {
        account: this.loginForm.username.replace(/\s+/g, ""),
        password: jse.encrypt(this.loginForm.password.replace(/\s+/g, "")),
      };
      if (this.isCode) {
        params.verifycode = jse.encrypt(this.loginForm.identify.replace(/\s+/g, ""))
      }
      this.$store
        .dispatch("user/login", params)
        .then(async (res) => {
          if (res==1) {
            this.dialogOpen()
          } else {
            this.userLogin()
          }
          this.loading = false;
        })
        .catch(() => {
          this.getCheckCode();
          this.loading = false;
        });
    },
    //账号已经登录弹框
    dialogOpen () {
      this.$confirm('该账号已登录, 是否强制登录?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.userLogin()
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消登录'
        });
      });
    },
    //账号强制登录
    async userLogin () {
      const { code, message, returnData } = await forceLogin({
        userid: getUserId()
      });
      if (code == 0 && isValue(returnData)) {
        setToken('usertoken', returnData.usertoken)
        setCodeToken(returnData.usertoken)
        this.$store.dispatch("app/toggleOutcheck", false);
        sessionStorage.setItem("userName", this.loginForm.username.replace(/\s+/g, ""));
        this.$router.push({ path: this.redirect || "/" });
      } else {
        this.$message.error(message);
      }
    },
    //获取动态验证码
    async getCheckCode () {
      const { code, message, returnData } = await getVCode();
      if (code == 0 && isValue(returnData)) {
        const { verifyCodeImage } = returnData;
        this.loginForm.identify="";
        this.baseImg = verifyCodeImage;
      } else {
        this.$message.error(message);
      }
    },
    //验证码重新获取
    changeCode () {
      this.getCheckCode();
    },
    errorHandler () {
      return true
    }
  },
};
</script>

<style lang="scss" scoped>
$bg: #2d3a4b;
$dark_gray: #889aa4;
$light_gray: #eee;

.login-container {
  min-height: 100%;
  width: 100%;
  background-color: $bg;
  overflow: hidden;
  //background-image: url("../../assets/loginpage/bg.jpg");
  background-repeat: no-repeat;
  background-size: cover;
  display: flex;
  justify-content: center;
  align-items: center;
  ::v-deep .login-form {
    position: relative;
    width: 416px;
    height: 424px;
    background: #ffffff;
    box-shadow: 0px 7px 18px 0px rgba(0, 0, 0, 0.5);
    border-radius: 8px;
    padding: 40px 48px 27px 48px;
    .el-form-item__content {
      height: 40px;
      background: #fff;
      border-radius: 6px;
      .el-input {
        height: 40px;
        border-radius: 2px;
        input {
          height: 40px;
          border: 1px solid #d2d6df;
          color: #303133;
        }
      }
    }
  }
  .forgetPwd {
    display: flex;
    justify-content: flex-end;
    margin-top: 22px;
    font-size: 14px;
    font-family: Microsoft YaHei;
    font-weight: 400;
    text-decoration: underline;
    color: #2d67e3;
    .fpwd {
      cursor: pointer;
    }
  }
  .tips {
    font-size: 14px;
    color: #fff;
    margin-bottom: 10px;

    span {
      &:first-of-type {
        margin-right: 16px;
      }
    }
  }

  .svg-container {
    vertical-align: middle;
    width: 55px;
    display: inline-block;
    text-align: center;
  }

  .title-container {
    position: relative;
    margin-bottom: 39px;
    line-height: 32px;
    .title {
      // height: 16px;
      font-size: 16px;
      font-family: Microsoft YaHei;
      font-weight: bold;
      color: #303133;
      margin-left: 15px;
    }
    .title-en {
      position: absolute;
      top: 23px;
      left: 0;
      font-size: 12px;
    }
    .content-box {
      position: relative;
    }
    .avitor {
      width: 36px;
      height: 36px;
      margin-right: 20px;
      background: url("../../assets/logo/pic_logo.png") no-repeat;
      // border-radius: 50%;
      position: relative;
      top: 7px;
    }
    .el-divider {
      height: 20px;
      background: #101116;
      margin: 0 16px;
      position: relative;
      top: 5px;
    }
  }
  .show-pwd {
    position: absolute;
    right: 10px;
    top: 7px;
    font-size: 16px;
    color: $dark_gray;
    cursor: pointer;
    user-select: none;
  }
}
</style>
