<script setup lang="ts">
import type { FormInstance, FormRules } from "element-plus";
import { login } from "@/api";
import bg from "@/assets/images/login/bg.png";
import illustration from "@/assets/images/login/illustration.svg";
import logo from "@/assets/images/logo.svg";
import { Constant } from "@/constants";
import Locale from "@/layouts/components/LayHeader/components/Locale.vue";
import ThemeSwitch from "@/layouts/components/LayHeader/components/ThemeSwitch.vue";
import { useRouteStore, useUserStore } from "@/stores";
import { $t, renderIcon, storage } from "@/utils";
import dayjs from "dayjs";

defineOptions({ name: "Login" });

const loading = ref(false);
const checked = ref(true);
const disabled = ref(false);

const rules: FormRules = {
  userName: [
    {
      required: true,
      message: $t("page.login.userNameError"),
      trigger: "blur",
    },
  ],
  password: [
    {
      required: true,
      message: $t("page.login.passwordError"),
      trigger: "blur",
    },
  ],
};

interface State {
  userName: string;
  password: string;
}

const state = reactive({
  userName: "admin",
  password: "123456",
});

// 获取用户账号
async function getUserConfig() {
  try {
    const rss = await storage.getItem<State>(Constant.LoginAccount, "");

    if (!rss) return;

    state.userName = rss.userName;
    state.password = rss.password;
    checked.value = true;
  } catch (e) {
    console.error(e);
  }
}

onMounted(() => {
  // getUserConfig();
  handleLogin();
});

const appName = import.meta.env.VITE_APP_NAME;
const userStore = useUserStore();
const routeStore = useRouteStore();
const router = useRouter();
const formRef = ref<FormInstance | null>(null);
// 点击登录
async function handleLogin(): Promise<void> {
  try {
    if (checked.value) {
      await storage.setItem(Constant.LoginAccount, state);
    } else {
      await storage.removeItem(Constant.LoginAccount);
    }

    const res = await login(state);
    userStore.setToken(res.data.token);
    //调取用户信息，目前不需要这个接口
    await routeStore.initAuthRoute();
    router
      .push("/")
      .then(() => {
        ElNotification.success({
          title: $t("page.login.loginSuccessful"),
          message: $t("page.login.welcomeBack"),
          duration: 2500,
        });
      })
      .finally(() => {
        disabled.value = false;
      });
  } finally {
    // loading.value = false;
    // disabled.value = false;
  }
}

// 回车登录
useEventListener(document, "keypress", ({ code }) => {
  if (
    ["Enter", "NumpadEnter"].includes(code) &&
    !disabled.value &&
    !loading.value
  )
    handleLogin();
});
</script>

<template>
  <div class="select-none">
    <!-- <img :src="bg" class="wave" alt="" />
    <div class="absolute right-5 top-3">
      <Locale />
      <ThemeSwitch />
    </div> -->
    <div class="login-container">
      <!-- <div class="img">
        <img :src="illustration" alt="" />
      </div> -->
      <div class="login-box">
        <div class="login-form">
          <!-- <img class="avatar" :src="logo" alt="" />
          <h2 class="outline-none">
            {{ appName }}
          </h2> -->
          <!-- <el-form ref="formRef" :model="state" :rules="rules" size="large">
            <el-form-item prop="userName">
              <el-input
                v-model="state.userName"
                clearable
                :placeholder="$t('page.login.userName')"
                :prefix-icon="renderIcon('UserFilled')"
              />
            </el-form-item>
            <el-form-item prop="password">
              <el-input
                v-model="state.password"
                :placeholder="$t('page.login.password')"
                :prefix-icon="renderIcon('bxs:lock')"
                clearable
                show-password
              />
            </el-form-item>
            <el-form-item>
              <div class="h-[20px] w-full flex items-center justify-between">
                <el-checkbox v-model="checked">
                  {{ $t("page.login.rememberMe") }}
                </el-checkbox>
              </div>
              <el-button
                class="mt-16 w-full"
                type="primary"
                size="default"
                :loading
                :disabled
                @click="handleLogin"
              >
                {{ $t("page.login.login") }}
              </el-button>
            </el-form-item>
          </el-form> -->
        </div>
      </div>
    </div>
    <!-- <div
      class="absolute bottom-12 w-full flex-center text-14 text-[rgba(0,0,0,0.6)] line-height-14 dark:text-[rgba(220,220,242,0.8)]"
    >
      Copyright © 2024-{{ dayjs().year() }}
      <el-link href="https://blog.wjp.plus" target="_blank" :underline="false">
        &nbsp;{{ appName }}
      </el-link>
    </div> -->
  </div>
</template>

<style scoped lang="scss">
.wave {
  position: fixed;
  height: 100%;
  width: 80%;
  left: 0;
  bottom: 0;
}

.login-container {
  width: 100vw;
  height: 100vh;
  max-width: 100%;
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  grid-gap: 18rem;
  padding: 0 2rem;

  .img {
    display: flex;
    justify-content: flex-end;
    align-items: center;
    z-index: 1;

    img {
      width: 500px;
    }
  }

  .login-box {
    display: flex;
    align-items: center;
    text-align: center;
    overflow: hidden;

    .login-form {
      width: 360px;

      .avatar {
        width: 350px;
        height: 80px;
      }

      h2 {
        text-transform: uppercase;
        margin: 15px 0;
        color: #999;
        font: bold 200% Consolas, Monaco, monospace;
      }
    }
  }
}

@media screen and (max-width: 1180px) {
  .login-container {
    grid-gap: 9rem;

    .img {
      img {
        width: 360px;
      }
    }

    .login-form {
      width: 290px;

      .avatar {
        width: 280px;
        height: 80px;
      }

      h2 {
        font-size: 2.4rem;
        margin: 8px 0;
      }
    }
  }
}

@media screen and (max-width: 968px) {
  .wave {
    display: none;
  }

  .login-container {
    grid-template-columns: 1fr;

    .img {
      display: none;
    }

    .login-box {
      justify-content: center;
    }
  }
}
</style>
