<script setup lang="ts">
import Motion from "./utils/motion";
import { useRouter } from "vue-router";
import { message } from "@/utils/message";
import { loginRules } from "./utils/rule";
import { useNav } from "@/layout/hooks/useNav";
import type { FormInstance } from "element-plus";
import { useLayout } from "@/layout/hooks/useLayout";
import { initRouter, getTopMenu } from "@/router/utils";
import { bg, avatar, illustration } from "./utils/static";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import lockOn from "../../assets/icon-png/lock-on.svg";
import userPng from "@/assets/icon-png/user.svg";
import { useUserStoreHook } from "@/store/modules/user";
import { useAppStoreHook } from "@/store/modules/app";
import {
  ref,
  reactive,
  toRaw,
  onMounted,
  onBeforeUnmount,
  computed
} from "vue";
import { useDataThemeChange } from "@/layout/hooks/useDataThemeChange";
import { encryption } from "@/utils/encrypt";
import dayIcon from "@/assets/svg/day.svg?component";
import darkIcon from "@/assets/svg/dark.svg?component";
import Lock from "@iconify-icons/ri/lock-fill";
import User from "@iconify-icons/ri/user-3-fill";
defineOptions({
  name: "Login"
});
const router = useRouter();
const loading = ref(false);
const ruleFormRef = ref<FormInstance>();

const { initStorage } = useLayout();
initStorage();

const { dataTheme, dataThemeChange } = useDataThemeChange();
dataThemeChange();
const { title, toggleSideBar } = useNav();

const ruleForm = reactive({
  username: "",
  password: ""
});
const handleBlur = () => {
  // @ts-ignore
  // localStorage.setItem("password", ruleForm.password);
  // @ts-ignore
  localStorage.setItem("rolesName", ruleForm.username);
};
const onLogin = async (formEl: FormInstance | undefined) => {
  loading.value = true;
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      useUserStoreHook()
        .loginByUsername({
          username: encryption(ruleForm.username),
          password: encryption(ruleForm.password)
          // username: ruleForm.username,
          // password: ruleForm.password
        })
        .then(res => {
          // @ts-ignore
          if (res.code === 200) {
            // @ts-ignore
            localStorage.setItem("token", res.data.token);
            // @ts-ignore
            localStorage.setItem("userName", res.data.realName);
            //  获取后端路由动态路由逻辑，不可删除
            // debugger;
            initRouter().then(() => {
              // router.push(getTopMenu(true).path);
              router.push("/");
              useAppStoreHook().toggleSideBar(false, "关闭");
              // toggleSideBar(false);
              message("登录成功", { type: "success" });
            });
            // router.push("/");
            console.log("登录成功", res);
          }
        })
        .catch(err => {
          loading.value = false;
          return fields;
        });
    } else {
      loading.value = false;
      return fields;
    }
  });
};

/** 使用公共函数，避免`removeEventListener`失效 */
function onkeypress({ code }: KeyboardEvent) {
  if (code === "Enter") {
    onLogin(ruleFormRef.value);
  }
}

onMounted(() => {
  window.document.addEventListener("keypress", onkeypress);
});

onBeforeUnmount(() => {
  window.document.removeEventListener("keypress", onkeypress);
});
</script>

<template>
  <div class="select-none">
    <img :src="bg" class="wave" />
    <div class="login-container">
      <img src="@/assets/login/logo@2x.png" class="wave-logo" />
      <!-- <img src="@/assets/login/logo.png" class="wave-logo" /> -->
      <div class="img">
        <!--  -->
      </div>
      <div class="login-box">
        <div class="login-form">
          <div class="logo-box-form">
            <Motion>
              <!-- <h2 class="outline-none">{{ title }}</h2> -->
              <h2 class="">您好，欢迎登录！</h2>
            </Motion>
            <el-form
              ref="ruleFormRef"
              :model="ruleForm"
              :rules="loginRules"
              size="large"
              class="mt-10"
            >
              <Motion :delay="100">
                <el-form-item
                  :rules="[
                    {
                      required: true,
                      message: '请输入账号',
                      trigger: 'blur'
                    }
                  ]"
                  prop="username"
                >
                  <el-input
                    v-model="ruleForm.username"
                    clearable
                    placeholder="账号"
                    :prefix-icon="userPng"
                    class="custom-input"
                  />
                </el-form-item>
              </Motion>

              <Motion :delay="150">
                <el-form-item prop="password">
                  <el-input
                    v-model="ruleForm.password"
                    clearable
                    show-password
                    placeholder="密码"
                    :prefix-icon="lockOn"
                    @blur="handleBlur"
                  />
                </el-form-item>
              </Motion>

              <Motion :delay="250">
                <el-button
                  class="w-full mt-4"
                  size="default"
                  type="primary"
                  :loading="loading"
                  @click="onLogin(ruleFormRef)"
                >
                  登录
                </el-button>
              </Motion>
            </el-form>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
@import url("@/style/login.css");
</style>

<style lang="scss" scoped>
:deep(.el-input-group__append, .el-input-group__prepend) {
  padding: 0;
}

.gongshi {
  // font-family: PingFangSC-Regular;
  font-size: 13px;
  font-weight: 400;
  line-height: 20px;
  color: #333;
  text-align: center;
}

:deep(.el-input__prefix) {
  font-size: 20px;

  /* 设置图标大小 */
}
</style>
