<template>
  <div class="auth-login-container" :style="{ background: 'url(' + innerSetting.pageImg + ') center center no-repeat', 'background-size': '100% 100%' }">
    <div class="auth-header">
      <img class="auth-header-img" :src="innerSetting.logoImg" />
    </div>
    <div class="auth-body">
      <div class="auth-context" id="auth-context">
        <div class="auth-main-left">
          <img class="auth-left-bg" :src="innerSetting.boxLeftImg" />
        </div>
        <div class="auth-main-right" :style="{ 'background-image': 'url(' + innerSetting.boxRightImg + ')' }">
          <div class="auth-header-box">
            <div class="auth-system-name">欢迎登录</div>
            <div class="space-line"></div>
            <div class="auth-form-title">{{ innerSetting.organizationName }}</div>
          </div>
          <div class="auth-form-box">
            <form class="auth-form" method="post">
              <div class="auth-control">
                <div class="auth-input">
                  <t-input type="text" size="large" v-model="username" placeholder="请输入用户名" @mouseenter="loginErrorMsg = ''">
                    <user-icon slot="prefix-icon"></user-icon>
                  </t-input>
                  <!--                  <img class="icon-input" width="25" height="25" :src="activeIconUser ? innerSetting.iconUserActive : innerSetting.iconUser" />-->
                  <!--                  <input type="text" v-model="username" placeholder="请输入用户名" @input="loginErrorMsg = ''" @focus="activeIconUser = true" @blur="activeIconUser = false" />-->
                </div>
              </div>
              <div class="auth-control mt-26">
                <div class="auth-input">
                  <t-input type="password" size="large" v-model="password" placeholder="请输入登录密码" @mouseenter="loginErrorMsg = ''">
                    <lock-on-icon slot="prefix-icon"></lock-on-icon>
                  </t-input>
                  <!--                  <img class="icon-input" width="25" height="25" :src="activeIconPwd ? innerSetting.iconPwdActive : innerSetting.iconPwd" />-->
                  <!--                  <input type="password" v-model="password" placeholder="请输入登录密码" @input="loginErrorMsg = ''" @focus="activeIconPwd = true" @blur="activeIconPwd = false" />-->
                </div>
              </div>
              <div class="auth-control-verify mt-26">
                <div class="auth-verify">
                  <input type="text" v-model="verifyCode" placeholder="请输入验证码" @input="loginErrorMsg = ''" />
                </div>
                <div class="verify">
                  <img class="icon-verify" :src="KaptchaImage" @click="getKaptchaImage" />
                  <span>不清晰？请点击图片刷新</span>
                </div>
              </div>
              <div class="auth-error">
                <div v-if="loginErrorMsg">{{ loginErrorMsg }}</div>
              </div>
              <div class="auth-submit" @click="onLogin">{{ loading ? "处理中" : "登录" }}</div>
            </form>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts">
import Vue from "vue";
import Component from "vue-class-component";
import { Prop, Watch } from "vue-property-decorator";
import { LoginPageSetting } from "../../model/LoginPageSetting";
import { LOGIN_PWD_ACTIVE_LABEL, LOGIN_PWD_LABEL, LOGIN_USER_ACTIVE_LABEL, LOGIN_USER_LABEL } from "../../constants/encode-assets/svg";
import { loginLogoImg } from "../../constants/encode-assets/login-logo-img";
import { loginPageImg } from "../../constants/encode-assets/login-page-img";
import { loginBoxLeftImg } from "../../constants/encode-assets/login-box-left-img";
import { loginBoxRightImg } from "../../constants/encode-assets/login-box-right-img";
import { oauthService } from "../../services/oauth.service";
import { LoginRequest } from "../../model/LoginRequest";
import { IdentityType } from "../../constants/enum/identity-type.enum";
import { RestfulResponse } from "../../model/RestfulResponse";
import { Code } from "../../constants/enum/code.enum";
import { LockOnIcon } from "tdesign-icons-vue";
import { UserIcon } from "tdesign-icons-vue";
import { SM4 } from "gm-crypto";

@Component({
  name: "Login",
  components: {
    LockOnIcon,
    UserIcon,
  },
})
export default class Login extends Vue {
  @Prop() setting: LoginPageSetting | undefined; // 登录页配置
  @Prop({ default: false }) isPreview!: boolean; // 是否仅预览页面

  innerSetting: LoginPageSetting = new LoginPageSetting();
  activeIconUser = false; // 用户名激活图标
  activeIconPwd = false; // 密码激活图标
  isShowPwd = false; // 是否展示密码
  loading = false; // 处理中
  KaptchaImage = ""; // 验证码图片base64

  username = ""; // 用户名
  password = ""; // 密码
  verifyCode = ""; // 验证码
  loginErrorMsg = ""; // 错误描述
  encryptedData = "";
  key = "7c4a8d09ca3762af61e59520943dc264"; // 16 字节的密钥

  @Watch("setting", { immediate: true })
  onLoginPageSetupChange(): void {
    const setting: LoginPageSetting = this.setting || new LoginPageSetting();
    this.innerSetting = new LoginPageSetting({
      pageImg: setting.pageImg ? setting.pageImg : loginPageImg,
      logoImg: setting.logoImg ? setting.logoImg : loginLogoImg,
      boxLeftImg: setting.boxLeftImg ? setting.boxLeftImg : loginBoxLeftImg,
      boxRightImg: setting.boxRightImg ? setting.boxRightImg : loginBoxRightImg,
      organizationName: setting.organizationName ? setting.organizationName : "东华软件",
      iconUser: setting.iconUser ? setting.iconUser : LOGIN_USER_LABEL,
      iconPwd: setting.iconPwd ? setting.iconPwd : LOGIN_PWD_LABEL,
      iconUserActive: setting.iconUserActive ? setting.iconUserActive : LOGIN_USER_ACTIVE_LABEL,
      iconPwdActive: setting.iconPwdActive ? setting.iconPwdActive : LOGIN_PWD_ACTIVE_LABEL,
    });
  }

  /**
   * @description: 主窗口尺寸调整
   * @author ChenRui
   * @date 2022/1/25 17:46
   */
  screenScale = () => {
    const element: any = document.getElementById("auth-context");
    if (element) {
      let scale = (0.8 * (document.documentElement.clientHeight - 116)) / 600;
      if (scale <= 0.7) {
        scale = 0.7;
      }
      if (scale >= 1) {
        scale = 1;
      }
      // 缩放主视图区域
      const transform = `scale(${scale})`;
      element.style.transform = transform;
      // 调整主视图与顶栏的间距
      const spacing = window.innerHeight - 640;
      if (spacing > 0) {
        element.style.marginTop = "-" + spacing / 2 / 2 + "px";
      } else {
        element.style.marginTop = "20px";
      }
    }
  };

  /**
   * @description: 挂载
   * @author ChenRui
   * @date 2022/1/25 14:01
   */
  mounted(): void {
    this.getKaptchaImage();
    this.screenScale();
    window.addEventListener("resize", this.screenScale);
  }

  destroyed() {
    window.removeEventListener("resize", this.screenScale);
  }

  /**
   * sm4加密
   */
  arrayBufferToHex(buffer: any) {
    const hex = Array.from(new Uint8Array(buffer))
      .map((byte) => byte.toString(16).padStart(2, "0"))
      .join("");
    return hex;
  }
  encrypt() {
    const encrypted = SM4.encrypt(this.password, this.key, {
      inputEncoding: "utf8",
      outputEncoding: "base64",
    });
    this.encryptedData = encrypted;
  }

  /**
   * 获取图形验证码
   */
  getKaptchaImage() {
    oauthService.getKaptcha().then((res: RestfulResponse) => {
      if (res.code === Code.SUCCESS.code) {
        for (let key in res.data) {
          this.KaptchaImage = res.data[key];
          localStorage.setItem("kapt", key);
        }
      } else {
        this.loginErrorMsg = res.msg!;
      }
    });
  }

  /**
   * @description: 密码模式登录
   * @author ChenRui
   * @date 2022/1/25 17:47
   */
  async onLogin() {
    if (this.loading || !!this.isPreview) {
      return;
    }
    await this.encrypt();
    const params: LoginRequest = {
      identityCode: this.username,
      credential: this.encryptedData,
      identityType: IdentityType.password.code,
      kaptchaCode: this.verifyCode,
      tenantId: this.$route.query.tenantId || localStorage.getItem("tenantId") || "1030132831902502912",
    };
    this.loading = true;
    oauthService.simpleLogin(params).then((res: RestfulResponse) => {
      this.loading = false;
      if (res.code === Code.SUCCESS.code) {
        this.$emit("login-success", res.data);
        localStorage.setItem("tenantId", res.data.sysUserInfo.tenantId);
      } else {
        this.loginErrorMsg = res.msg!;
      }
    });
  }
}
</script>

<style scoped lang="scss">
.auth-login-container {
  height: 100vh;
  width: 100%;
  display: flex;
  flex-direction: column;
  .auth-header {
    margin: 30px 30px 10px 30px;
    padding-left: 40px;
    .auth-header-img {
      max-width: 174px;
      max-height: 62px;
    }
  }
  .auth-body {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100%;
    overflow: hidden;

    .auth-context {
      width: 1032px;
      height: 600px;
      display: flex;
      flex-direction: row;
      align-items: center;
      background: transparent;
      transform-origin: center;
      border: none;
      border-radius: 1rem;
      box-shadow: 0 10px 40px rgba(25, 114, 255, 0.1);
      margin-top: -10px;
      .auth-main-left {
        position: relative;
        .auth-left-bg {
          width: 528px;
          height: 600px;
        }
      }
      .auth-main-right {
        flex: 1;
        height: 93%;
        display: flex;
        flex-direction: column;
        background-color: #ffffff;
        background-repeat: no-repeat;
        background-position: right bottom;
        padding-left: 25%;
        padding-right: 5%;
        margin-left: -20%;
        border-radius: 1rem;
        .auth-header-box {
          display: flex;
          align-items: flex-end;
          justify-content: center;
          margin-top: 82px;
          .auth-system-name {
            font-family: 微软雅黑;
            font-weight: 700;
            font-style: normal;
            font-size: 30px;
            color: #2754fc;
          }
          .space-line {
            width: 2px;
            height: 1.35rem;
            background-color: #cccccc;
            margin: 0 1rem 0 2.2rem;
          }
          .auth-form-title {
            font-family: 微软雅黑;
            font-weight: 400;
            font-size: 18px;
            color: #333333;
          }
        }
        .auth-form-box {
          .auth-form {
            .mt-26 {
              margin-top: 36px;
            }
            .auth-control {
              margin-top: 30px;
              .auth-input {
                display: flex;
                position: relative;
                align-items: center;
                flex-direction: row;
                margin-top: 10px;
                .icon-input {
                  position: absolute;
                  left: 1.25rem;
                  &:hover {
                    border-color: #1972ff;
                  }
                }
                input {
                  flex-grow: 1;
                  border: 0 !important;
                  border-radius: 10px;
                  background: #fafafa;
                  outline: none;
                  font-size: 16px;
                  height: 56px;
                  line-height: 56px;
                  padding-left: 4.65rem;
                  &::-webkit-input-placeholder {
                    font-size: 16px;
                    font-weight: 400;
                    font-style: normal;
                    color: #cccccc;
                  }
                }
              }
            }
            .auth-control-verify {
              margin-top: 30px;
              display: flex;
              flex-direction: row;
              justify-content: space-between;
              align-items: center;
              .auth-verify {
                display: flex;
                position: relative;
                align-items: center;
                flex-direction: row;
                height: 56px;
                line-height: 56px;
                //margin-top: 10px;
                margin-right: 10px;
                input {
                  border: none;
                  border-radius: 3px;
                  padding: 15px 20px;
                }
              }
              .verify {
                height: 56px;
                display: flex;
                flex: 1;
                flex-direction: column;
                align-items: end;
                justify-content: center;
                .icon-verify {
                  max-height: 50px;
                  width: 90%;
                  border-radius: 6px;
                }
                span {
                  flex: 1;
                  font-size: 12px;
                }
              }
            }
            .auth-error {
              height: 50px;
              display: flex;
              flex-direction: row;
              align-items: center;
              color: #ff0f2f;
            }
            .auth-submit {
              width: 100%;
              height: 56px;
              background-color: #1f63eb;
              font-size: 16px;
              border: 0;
              border-radius: 2rem;
              color: white;
              //margin-top: 52px;
              cursor: pointer;
              display: flex;
              justify-content: center;
              align-items: center;
            }
          }
        }
      }
    }
  }
}
</style>
