<template>
  <div class="login"
    v-if="!autoLoginLoading">
    <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="accountPassLoading"
          size="large"
          type="primary"
          @click.prevent="handleLogin"
          class="login_btn">
          <span v-if="!accountPassLoading">登 录</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="autoLoginLoading"
    element-loading-text="授权登录中...">
  </div>
</template>

<script setup>
import { fsOAuthUrl, fsClientAuth } from "@/api"
import Cookies from "js-cookie"
import { encrypt, decrypt, getQueryString } 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 accountPassLoading = ref(false) // 账号密码登录状态
const autoLoginLoading = 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()

// 账号密码登录
function handleLogin() {
  proxy.$refs.loginRef.validate(valid => {
    if (valid) {
      accountPassLoading.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)
    }
  });
}

// 自动登录
async function checkAutoLogin() {
  if (window.h5sdk) {
    // 飞书客户端内-自动登录
    autoLoginLoading.value = true
    const code = await fsClientAuth()
    return loginByType('fs', { code })
  }

  const state = getQueryString('state')
  const code = getQueryString('code')
  if (state) {
    // 有 state 代表网页回调-自动登录
    autoLoginLoading.value = true
    state === 'fs' && loginByType('fs', { code })
    state === 'STATE' && loginByType('qc', { code })
  }
}
checkAutoLogin()

// code 免账号密码登录
async function loginByType(type, data) {
  // 登录
  userStore.login({
    type,
    data
  }).then(() => {
    router.push({ path: redirect.value || "/" });
  }).catch(() => {
    accountPassLoading.value = false;
    autoLoginLoading.value = false;
  })
}

// 网页回车登录
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>
