<template>
  <div class="login-container">
    <el-form ref="loginFormRef" :model="loginData" :rules="loginRules" class="login-form">
      <div class="title">
        <span>登录</span>
      </div>
      <el-form-item prop="phone">
        <span class="m-2"> <svg-icon icon-class="username" size="30px" /> </span>|
        <el-input
          ref="username"
          v-model="loginData.phone"
          class="flex-1"
          placeholder="请输入登录账号"
          name="username" />
      </el-form-item>
      <el-form-item prop="password">
        <span class="m-2"> <svg-icon icon-class="password" size="30px" /> </span>|
        <el-input
          v-model="loginData.password"
          class="flex-1"
          placeholder="请输入登录密码"
          :type="passwordVisible === false ? 'password' : 'input'"
          name="password"
          @keyup.enter="handleLogin" />
        <span class="mr-3" @click="passwordVisible = !passwordVisible">
          <svg-icon :icon-class="!passwordVisible ? 'eye' : 'eye-open'" class="cursor-pointer" size="18px" />
        </span>
      </el-form-item>
      <el-button :loading="loading" class="w-full" size="default" type="primary" @click.prevent="handleLogin"
        >登录
      </el-button>

      <el-checkbox v-model="autoLogin" fill="#727272" label="自动登录" size="small" />
    </el-form>
  </div>
</template>

<script setup lang="ts">
import router from "@/router";
import SvgIcon from "@/components/SvgIcon/index.vue";

// 状态管理依赖
import {useUserStore} from "@/store/modules/user";

// API依赖
import {LocationQuery, LocationQueryValue, useRoute} from "vue-router";
import {LoginData} from "@/api/auth/types";

const userStore = useUserStore();
const route = useRoute();

/**
 * 按钮loading
 */
const loading = ref(false);
/**
 * 密码是否可见
 */
const passwordVisible = ref(false);
/**
 * 登录表单引用
 */
const loginFormRef = ref(ElForm);
const autoLogin = ref(true);
const loginData = ref<LoginData>({
  // phone: "18770033942",
  // password: "123456",
  phone: atob(localStorage.getItem("autoName") || ""),
  password: atob(localStorage.getItem("autoPass") || ""),
});

const loginRules = {
  phone: [{required: true, trigger: "blur", validator: usernameValidator}],
  password: [{required: true, trigger: "blur", validator: passwordValidator}],
};

/**
 * 用户名校验
 */
function usernameValidator(rule: any, value: any, callback: any) {
  if (value * 1 === 0) {
    callback(new Error("输入的手机号码不能为空"));
  }
  if (!new RegExp(/^1[3-9][0-9]{9}$/).test(value)) {
    callback(new Error("输入的手机号码格式错误"));
  }
  callback();
}
/**
 * 密码校验器
 */
function passwordValidator(rule: any, value: any, callback: any) {
  if (value.length < 6) {
    callback(new Error("密码格式错误"));
  } else {
    callback();
  }
}
/**
 * 登录
 */
function handleLogin() {
  loginFormRef.value.validate((valid: boolean) => {
    if (valid) {
      loading.value = true;
      if (autoLogin.value) {
        // 自动登录存入本地存储
        localStorage.setItem("autoName", btoa(<string>loginData.value.phone));
        localStorage.setItem("autoPass", btoa(<string>loginData.value.password));
      }
      userStore
        .login(loginData.value)
        .then(() => {
          const query: LocationQuery = route.query;
          const redirect = (query.redirect as LocationQueryValue) ?? "/";
          const otherQueryParams = Object.keys(query).reduce((acc: any, cur: string) => {
            if (cur !== "redirect") {
              acc[cur] = query[cur];
            }
            return acc;
          }, {});
          router.push({path: redirect, query: otherQueryParams});
        })
        .catch((error) => {
          console.log("登录", error);
          // 验证失败，重新生成验证码
          new Error("您输入的密码错误");
        })
        .finally(() => {
          loading.value = false;
        });
    }
  });
}
</script>

<style lang="scss" scoped>
.login-container {
  box-sizing: border-box;
  width: 100%;
  height: 100%;
  min-height: 750px;
  padding-top: 260px;
  overflow: hidden;
  background: #eaf7fd url("../../assets/login/login.jpg") no-repeat left top;
  background-size: auto 100%;

  .login-form {
    width: 500px;
    max-width: 100%;
    padding: 0 42px 20px;
    margin: 0 auto;
    overflow: hidden;
    background: #fff;
    box-shadow: 0 0 10px #f2f3f5;

    .title {
      height: 98px;
      font-size: 30px;
      line-height: 98px;
      color: #151515;
    }

    .svg-icon {
      width: 18px;
      height: 18px;
    }
  }

  .el-form-item {
    height: 54px;
    margin-bottom: 40px;
    font-size: 16px;
    line-height: 54px;
    color: #747474;
    background: #f2f3f5;
    border: 1px solid #f2f3f5;
    border-radius: 5px;
  }

  .el-button {
    height: 54px;
    margin: 20px auto 10px;
    font-size: 18px;
    line-height: 54px;
    background: #006eff;
  }
}

@media only screen and (width >= 1080px) {
  .login-container {
    padding-left: 660px;
  }
}

@media only screen and (width <= 1080px) {
  .login-container {
    padding: 400px 0;
    background-position: center center;
  }
}

@media only screen and (width <= 600px) {
  .login-container {
    .login-form .title {
      height: 80px;
      line-height: 80px;
    }

    .el-form-item {
      margin-bottom: 20px;
    }
  }
}

.el-input {
  height: 54px;
  line-height: 54px;
  background: transparent;
  // 子组件 scoped 无效，使用 :deep
  :deep(.el-input__wrapper) {
    height: 54px;
    padding: 0;
    background: transparent;
    box-shadow: none;

    .el-input__inner {
      height: 54px;
      text-indent: 1.5em;
      background: transparent;
      border: 0;
      border-radius: 0;

      &:-webkit-autofill {
        box-shadow: 0 0 0 1000px transparent inset !important;
        -webkit-text-fill-color: #fff !important;
      }
      // 设置输入框自动填充的延迟属性
      &:-webkit-autofill,
      &:-webkit-autofill:hover,
      &:-webkit-autofill:focus,
      &:-webkit-autofill:active {
        transition: color 99999s ease-out, background-color 99999s ease-out;
        transition-delay: 99999s;
      }
    }
  }
}

:deep(.el-checkbox__input.is-checked .el-checkbox__inner) {
  background-color: #727272;
  border-color: #727272;
}

:deep(.el-checkbox__input.is-checked + .el-checkbox__label) {
  color: #727272;
}
</style>
