<template>
  <div class="login"
    v-if="isShowLogin">
    <el-form ref="loginRef"
      :model="loginForm"
      :rules="loginRules"
      class="login-form">
      <div class="logo">
        <img src="@/assets/logo/logo.png" />
      </div>
      <el-form-item prop="username">
        <el-input v-model="loginForm.username"
          type="text"
          size="large"
          auto-complete="off"
          placeholder="工号">
          <template #prefix>
            <svg-icon icon-class="user"
              class="el-input__icon input-icon" />
          </template>
        </el-input>
      </el-form-item>
      <el-form-item prop="password">
        <el-input v-model="loginForm.password"
          type="password"
          size="large"
          auto-complete="off"
          placeholder="密码"
          @keyup.enter="handleLogin">
          <template #prefix>
            <svg-icon icon-class="password"
              class="el-input__icon input-icon" />
          </template>
        </el-input>
      </el-form-item>
      <el-checkbox v-model="loginForm.rememberMe">记住密码</el-checkbox>
      <el-form-item>
        <el-button :loading="loading"
          size="large"
          type="primary"
          @click.prevent="handleLogin"
          class="login_btn">
          <span v-if="!loading">登 录</span>
          <span v-else>登 录 中...</span>
        </el-button>
        <div class="auth_wrap">
          <p>
            <span>其他登录方式</span>
          </p>
          <div class="group">
            <a :href="fsOAuthUrl">
              <img src="@/assets/logo/feishu.png"
                alt=""
                class="item">
            </a>
          </div>
        </div>
      </el-form-item>
    </el-form>
    <!--  底部  -->
    <div class="el-login-footer">
      <span>Copyright © 2016-{{ (new Date()).getFullYear() }} 王小卤 All Rights Reserved.</span>
    </div>
  </div>
  <div class="auth_wait"
    v-else
    v-loading="!isShowLogin"
    element-loading-text="授权登录中...">
  </div>
</template>

<script setup>
import { fsOAuthUrl, fsClientAuth } from "@/api";
import Cookies from "js-cookie";
import { encrypt, decrypt } from "@/utils";
import useUserStore from '@/store/modules/user'

const userStore = useUserStore()
const route = useRoute();
const router = useRouter();
const { proxy } = getCurrentInstance();

const loginForm = ref({
  username: "",
  password: "",
  rememberMe: false
});

const loginRules = {
  username: [{ required: true, trigger: "blur", message: "请输入您的工号" }],
  password: [{ required: true, trigger: "blur", message: "请输入您的密码" }]
};

const loading = ref(false);
const isShowLogin = ref(false);
const redirect = ref(undefined);

watch(route, (newRoute) => {
  redirect.value = newRoute.query?.redirect;
}, { immediate: true });

// 回显账号密码
function getCookie() {
  const username = Cookies.get("username");
  const password = Cookies.get("password");
  const rememberMe = Cookies.get("rememberMe");
  loginForm.value = {
    username: username === undefined ? loginForm.value.username : username,
    password: password === undefined ? loginForm.value.password : decrypt(password),
    rememberMe: rememberMe === undefined ? false : Boolean(rememberMe)
  };
}
getCookie();

// code 登录
const loginByType = async (type, data) => {
  // 登录
  userStore.login({
    type,
    data
  }).then(() => {
    router.push({ path: redirect.value || "/" });
  }).catch(() => {
    loading.value = false;
  });
}

// 飞书网页授权登录（授权后会回调我这个网页，执行代码获取 state，进行登录）
const getOAuthState = () => {
  const params = new URLSearchParams(window.location.search);
  const code = params.get('code');
  const state = params.get('state');
  if (state === 'fs') {
    loginByType('fs', { code })
  }
}
getOAuthState()

// 检查-是否飞书回跳，并客户端登录
const checkFsLoginAuth = async () => {
  if (window.h5sdk) {
    const code = await fsClientAuth()
    loginByType('fs', { code })
  } else {
    isShowLogin.value = true
  }
}
checkFsLoginAuth()

// 检查-是否勤策回跳，并客户端登录
const checkQcLoginAuth = async () => {
  isShowLogin.value = false
  const isState = window.location.href.includes('state')
  if (isState) {
    loginByType('qc', window.location.href.split('?')[2])
  } else {
    isShowLogin.value = true
  }
}
checkQcLoginAuth()

// 工号密码登录
function handleLogin() {
  proxy.$refs.loginRef.validate(valid => {
    if (valid) {
      loading.value = true;
      // 勾选了需要记住密码设置在 cookie 中设置记住用户名和密码
      if (loginForm.value.rememberMe) {
        Cookies.set("username", loginForm.value.username, { expires: 30 });
        Cookies.set("password", encrypt(loginForm.value.password), { expires: 30 });
        Cookies.set("rememberMe", loginForm.value.rememberMe, { expires: 30 });
      } else {
        // 否则移除
        Cookies.remove("username");
        Cookies.remove("password");
        Cookies.remove("rememberMe");
      }
      // 调用action的登录方法
      loginByType('upass', loginForm.value)
    }
  });
}

// 网页回车登录
window.addEventListener('keyup', (ev) => {
  if (ev.key === 'Enter') {
    handleLogin()
  }
})
</script>

<style lang='scss'
  scoped>
  .login {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100%;
    background-image: url("../assets/images/login-background.jpg");
    background-size: cover;

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

      .logo {
        text-align: center;
        margin-bottom: 20px;

        img {
          width: 150px;
        }
      }

      .el-input {
        height: 40px;

        input {
          height: 40px;
        }
      }

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

      .login_btn {
        width: 100%;
        border-radius: 20px;
      }

      // 其他登录方式
      .auth_wrap {
        width: 100%;
        margin-top: 20px;

        p {
          width: 100%;
          padding: 0 20px;
          margin: 0;
          position: relative;
          text-align: center;

          span {
            position: relative;
            background: white;
            color: gray;
            z-index: 2;
            padding: 0 20px;
          }

          &:after {
            content: '';
            display: block;
            width: 100%;
            height: 1px;
            background: rgb(192, 191, 191);
            position: absolute;
            left: 0;
            top: 50%;
            z-index: 0;
            transform: translate(0, -50%);
          }
        }

        .group {
          display: flex;
          justify-content: center;

          .item {
            width: 50px;
          }
        }
      }
    }

    // 网页底部标题
    .el-login-footer {
      height: 40px;
      line-height: 40px;
      position: fixed;
      bottom: 0;
      width: 100%;
      text-align: center;
      color: #fff;
      font-family: Arial;
      font-size: 12px;
      letter-spacing: 1px;
    }
  }

  // 授权登录等待容器
  .auth_wait {
    height: 100%;
  }
</style>
