<template>
  <div class="login-container">
    <!-- 登录表单 -->
    <div class="body">
      <div class="main-box">
        <div
          :class="['container', 'container-register', { 'is-txl': isLogin }]"
        >
          <el-form>
            <h2 class="title">注册</h2>
            <input class="form__input" type="text" placeholder="请输入用户名" />
            <input class="form__input" type="text" placeholder="请输入工号" />
            <input
              class="form__input"
              type="password"
              placeholder="请输入密码"
            />
            <input
              class="form__input"
              type="password"
              placeholder="请输入密码"
            />
            <div class="form__button">立即注册</div>
          </el-form>
        </div>
        <div
          :class="[
            'container',
            'container-login',
            { 'is-txl is-z200': isLogin },
          ]"
        >
          <el-form
            ref="loginFormRef"
            :label-position="labelPosition"
            layout="vertical"
            :model="loginData"
            :rules="loginRules"
            label-width="auto"
            hide-required-mark="true"
            style="max-width: 600px"
          >
            <h2 class="title">登录</h2>
            <el-form-item
              field="username"
              label="用户名"
              prop="username"
              label-position="right"
            >
              <input
                class="form__input"
                v-model="loginData.username"
                type="text"
                placeholder="用户名/邮箱/手机号"
              />
            </el-form-item>

            <div class="input-login">
              <el-form-item
                field="password"
                prop="password"
                label="密码"
                label-position="right"
              >
                <div class="input-wrapper">
                  <input
                    class="form__input"
                    v-model="loginData.password"
                    :type="ShowPassword ? 'text' : 'password'"
                    placeholder="请输入密码"
                    @keyup="checkCapslock"
                    @keyup.enter="handleLoginSubmit"
                  />
                  <el-icon
                    class="icon"
                    name="eye"
                    @click="ShowPassword = !ShowPassword"
                  >
                    <View />
                  </el-icon>
                </div>
              </el-form-item>

              <div v-show="isCapslock" class="caps-lock-tip">
                大写锁定已开启
              </div>
            </div>

            <div class="form__button" @click="handleLoginSubmit()">
              立即登录
            </div>
          </el-form>
        </div>
        <div :class="['switch', { login: isLogin }]">
          <div class="switch__circle"></div>
          <div class="switch__circle switch__circle_top"></div>
          <div class="switch__container">
            <h2>{{ isLogin ? "您好 !" : "欢迎回来 !" }}</h2>
            <p>
              {{
                isLogin
                  ? "如果您还没有账号，请点击下方立即注册按钮进行账号注册"
                  : "如果您已经注册过账号，请点击下方立即登录按钮进行登录"
              }}
            </p>
            <div class="form__button" @click="isLogin = !isLogin">
              {{ isLogin ? "立即注册" : "立即登录" }}
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- ICP备案 -->
    <div class="icp-info" v-show="icpVisible">
      <p>
        Copyright © 2021 - 2024 337.tech All Rights Reserved. 叁叁柒 版权所有
      </p>
      <p>蜀ICP备2024080927号</p>
    </div>
  </div>
</template>

<script setup lang="ts">
// 外部库和依赖
import { LocationQuery, useRoute } from "vue-router";

// 内部依赖
import { useSettingsStore, useUserStore } from "@/store";
import AuthAPI, { type LoginData } from "@/api/auth";
import router from "@/router";
import defaultSettings from "@/settings";
import { ThemeEnum } from "@/enums/ThemeEnum";
import type { FormItemProps, FormProps, FormRules } from "element-plus";

// 类型定义
import type { FormInstance } from "element-plus";

// 导入 login.scss 文件
import "@/styles/login.scss";
import { View } from "@element-plus/icons-vue";

// 使用导入的依赖和库
const userStore = useUserStore();
const settingsStore = useSettingsStore();
const route = useRoute();
// 窗口高度
const { height } = useWindowSize();
// 国际化 Internationalization
const { t } = useI18n();

// 是否暗黑模式
const isDark = ref(settingsStore.theme === ThemeEnum.DARK);
// 是否显示 ICP 备案信息
const icpVisible = ref(true);
// 按钮 loading 状态
const loading = ref(false);
// 是否大写锁定
const isCapslock = ref(false);
// 验证码图片Base64字符串
const captchaBase64 = ref();
// 登录表单ref
const loginFormRef = ref<FormInstance>();
// 是否登录
const isLogin = ref(true);
// 是否显示密码
const ShowPassword = ref(false);

const labelPosition = ref<FormProps["labelPosition"]>("right");

const loginData = ref<LoginData>({
  username: "admin",
  password: "123456",
  captchaKey: "",
  captchaCode: "",
});

const loginRules = reactive<FormRules<LoginData>>({
  username: [
    {
      required: true,
      trigger: "blur",
      message: t("login.message.username.required"),
    },
  ],
  password: [
    {
      required: true,
      trigger: "blur",
      message: t("login.message.password.required"),
    },
    {
      min: 6,
      message: t("login.message.password.min"),
      trigger: "blur",
    },
  ],
  captchaCode: [
    {
      required: true,
      trigger: "blur",
      message: t("login.message.captchaCode.required"),
    },
  ],
});

/** 获取验证码 */
function getCaptcha() {
  AuthAPI.getCaptcha().then((data) => {
    loginData.value.captchaKey = data.captchaKey;
    captchaBase64.value = data.captchaBase64;
  });
}

/** 登录表单提交 */
function handleLoginSubmit() {
  loginFormRef.value?.validate((valid: boolean) => {
    if (valid) {
      loading.value = true;
      userStore
        .login(loginData.value)
        .then(() => {
          const { path, queryParams } = parseRedirect();
          router.push({ path: path, query: queryParams });
        })
        .catch(() => {
          getCaptcha();
        })
        .finally(() => {
          loading.value = false;
        });
    }
  });
}

/** 解析 redirect 字符串 为 path 和  queryParams */
function parseRedirect(): {
  path: string;
  queryParams: Record<string, string>;
} {
  const query: LocationQuery = route.query;
  const redirect = (query.redirect as string) ?? "/";

  const url = new URL(redirect, window.location.origin);
  const path = url.pathname;
  const queryParams: Record<string, string> = {};

  url.searchParams.forEach((value, key) => {
    queryParams[key] = value;
  });

  return { path, queryParams };
}

/** 主题切换 */
const toggleTheme = () => {
  const newTheme =
    settingsStore.theme === ThemeEnum.DARK ? ThemeEnum.LIGHT : ThemeEnum.DARK;
  settingsStore.changeTheme(newTheme);
};

/** 根据屏幕宽度切换设备模式 */
watchEffect(() => {
  icpVisible.value = height.value >= 600;
});

/** 检查输入大小写 */
function checkCapslock(event: KeyboardEvent) {
  // 防止浏览器密码自动填充时报错
  if (event instanceof KeyboardEvent) {
    isCapslock.value = event.getModifierState("CapsLock");
  }
}

onMounted(() => {
  getCaptcha();
});
</script>

<style lang="scss" scoped>
.body {
  width: 100vw;
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  font-family: "Montserrat", sans-serif;
  font-size: 12px;

  background-image: url("src/assets/images/login-background.jpg");
  color: #a0a5a8;
}
.main-box {
  position: relative;
  width: 800px;
  min-width: 800px;
  min-height: 500px;
  height: 500px;
  padding: 25px;
  background-color: #ecf0f3;
  box-shadow: 1px 1px 100px 10px #ecf0f3;
  border-radius: 12px;
  overflow: hidden;

  .container {
    display: flex;
    justify-content: center;
    align-items: center;
    position: absolute;
    top: 0;
    width: 400px;
    height: 100%;
    padding: 25px;
    background-color: #ecf0f3;
    transition: all 1.25s;

    form {
      display: flex;
      justify-content: center;
      align-items: center;
      flex-direction: column;
      width: 100%;
      height: 100%;
      color: #a0a5a8;

      .form__icon {
        object-fit: contain;
        width: 30px;
        margin: 0 5px;
        opacity: 0.5;
        transition: 0.15s;

        &:hover {
          opacity: 1;
          transition: 0.15s;
          cursor: pointer;
        }
      }

      .title {
        font-size: 34px;
        font-weight: 700;
        line-height: 3;
        color: #181818;
      }

      .text {
        margin-top: 30px;
        margin-bottom: 12px;
      }

      .form__input {
        width: 350px;
        height: 40px;
        margin: 4px 0;
        padding-left: 25px;
        font-size: 13px;
        letter-spacing: 0.15px;
        border: none;
        outline: none;
        // font-family: 'Montserrat', sans-serif;
        background-color: #ecf0f3;
        transition: 0.25s ease;
        border-radius: 8px;
        box-shadow:
          inset 2px 2px 4px #d1d9e6,
          inset -2px -2px 4px #f9f9f9;

        &::placeholder {
          color: #a0a5a8;
        }
      }
    }
  }

  .container-register {
    z-index: 100;
    left: calc(100% - 450px);
  }

  .container-login {
    left: calc(100% - 450px);
    z-index: 0;
  }

  .is-txl {
    left: 50px;
    transition: 1.25s;
    transform-origin: right;
  }

  .is-z200 {
    z-index: 200;
    transition: 1.25s;
  }

  .switch {
    display: flex;
    justify-content: center;
    align-items: center;
    position: absolute;
    top: 0;
    left: 0;
    height: 100%;
    width: 300px;
    padding: 50px;
    z-index: 200;
    transition: 1.25s;
    background-color: #ecf0f3;
    overflow: hidden;
    box-shadow:
      4px 4px 10px #d1d9e6,
      -4px -4px 10px #f9f9f9;
    color: #a0a5a8;

    .switch__circle {
      position: absolute;
      width: 330px;
      height: 330px;
      border-radius: 50%;
      background-color: #ecf0f3;
      box-shadow:
        inset 8px 8px 12px #d1d9e6,
        inset -8px -8px 12px #f9f9f9;
      bottom: -50%;
      left: -30%;
      transition: 1.25s;
    }

    .switch__circle_top {
      top: -30%;
      left: 60%;
      width: 250px;
      height: 250px;
    }

    .switch__container {
      display: flex;
      justify-content: center;
      align-items: center;
      flex-direction: column;
      position: absolute;
      width: 400px;
      padding: 50px 55px;
      transition: 1.25s;

      h2 {
        font-size: 34px;
        font-weight: 700;
        line-height: 3;
        color: #181818;
      }

      p {
        font-size: 14px;
        letter-spacing: 0.25px;
        text-align: center;
        line-height: 1.6;
        margin: 50px;
      }
    }
  }

  .login {
    left: calc(100% - 300px);

    .switch__circle {
      left: 0;
    }
  }

  .form__button {
    width: 180px;
    height: 50px;
    border-radius: 25px;
    margin-top: 50px;
    text-align: center;
    line-height: 50px;
    font-size: 14px;
    letter-spacing: 2px;
    background-color: #4b70e2;
    color: #f9f9f9;
    cursor: pointer;
    box-shadow:
      8px 8px 16px #d1d9e6,
      -8px -8px 16px #f9f9f9;

    &:hover {
      box-shadow:
        2px 2px 3px 0 rgba(255, 255, 255, 50%),
        -2px -2px 3px 0 rgba(116, 125, 136, 50%),
        inset -2px -2px 3px 0 rgba(255, 255, 255, 20%),
        inset 2px 2px 3px 0 rgba(0, 0, 0, 30%);
    }
  }
}
.input-login {
  position: relative;
}
.input-login .icon {
  position: absolute;
  top: 50%;
  right: 10px;
  transform: translateY(-50%);
  font-size: 16px;
  color: #a0a5a8;
}
.input-login .icon:hover {
  color: #4b70e2;
  cursor: pointer;
}

.input-wrapper {
  position: relative;
  width: 100%;
}

.form__input {
  width: 100%;
  padding-right: 40px; /* 给图标预留空间 */
  box-sizing: border-box;
}

.icon {
  position: absolute;
  top: 50%;
  right: 20px;
  transform: translateY(-50%);
  color: #999;
  cursor: pointer;
}

.caps-lock-tip {
  position: absolute;
  margin-top: -20px;
  color: rgba(255, 0, 0, 0.6);
  display: inline-flex;
}

input {
  width: 250px !important;
}
</style>
