<script setup lang="ts">
import {
  onBeforeMount,
  onBeforeUnmount,
  onMounted,
  reactive,
  ref,
  toRaw,
  watch
} from "vue";
import Motion from "./utils/motion";
import { useRouter } from "vue-router";
import { message } from "@/utils/message";
import { buildRegisterRules, loginRules } from "./utils/rule";
import TypeIt from "@/components/ReTypeit";
import { useNav } from "@/layout/hooks/useNav";
import type { FormInstance } from "element-plus";
import { ElMessage } from "element-plus";
import { useLayout } from "@/layout/hooks/useLayout";
import { rsaEncrypt } from "@/utils/crypt";
import { findRouteByPath, initRouter } from "@/router/utils";
import { avatar, bg, illustration } from "./utils/static";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import { useDataThemeChange } from "@/layout/hooks/useDataThemeChange";
import { DEFAULT_ENTRY_PATH } from "@/router/defaultEntry";
import { useMultiTagsStoreHook } from "@/store/modules/multiTags";
import {
  getIsRememberMe,
  getPassword,
  removePassword,
  saveIsRememberMe,
  savePassword,
  setTokenFromBackend
} from "@/utils/auth";

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";
import * as CommonAPI from "@/api/common/login";
import { useUserStoreHook } from "@/store/modules/user";

defineOptions({
  name: "Login"
});

// TODO 当请求验证码过于频繁的话  服务器会报错  但是前端没有反应 这块需要处理一下, 通过axios处理一下
const captchaCodeBase64 = ref("");

const isCaptchaOn = ref(false);
const isRegisterUserOn = ref(true);
const isRegisterMode = ref(false);

const router = useRouter();
const loading = ref(false);
const isRememberMe = ref(false);
const ruleFormRef = ref<FormInstance>();
const registerFormRef = ref<FormInstance>();

const { initStorage } = useLayout();
initStorage();
const { dataTheme, dataThemeChange } = useDataThemeChange();
dataThemeChange();
// const { title, getDropdownItemStyle, getDropdownItemClass } = useNav();
const { title } = useNav();

const ruleForm = reactive({
  username: "",
  password: getPassword(),
  captchaCode: "",
  captchaCodeKey: ""
});

const registerForm = reactive({
  username: "",
  nickname: "",
  password: "",
  confirmPassword: "",
  email: "",
  phoneNumber: "",
  captchaCode: "",
  captchaCodeKey: ""
});

const registerRules = buildRegisterRules(() => registerForm.password);

const onLogin = async () => {
  const formEl = ruleFormRef.value;
  if (!formEl) return;
  loading.value = true;
  const isValid = await formEl.validate().catch(() => false);
  if (!isValid) {
    loading.value = false;
    return;
  }
  await submitLogin();
};

async function submitLogin() {
  try {
    const { data } = await CommonAPI.loginByPassword({
      username: ruleForm.username,
      password: rsaEncrypt(ruleForm.password),
      captchaCode: ruleForm.captchaCode,
      captchaCodeKey: ruleForm.captchaCodeKey
    });
    await handleLoginSuccess(data, "", "登录成功");
    saveRememberedPassword();
  } catch {
    loading.value = false;
    await getCaptchaCode();
  }
}

const onRegister = async () => {
  const formEl = registerFormRef.value;
  if (!formEl) {
    ElMessage.error("注册表单未初始化，请刷新页面后重试");
    return;
  }
  loading.value = true;
  const isValid = await formEl.validate().catch(() => false);
  if (!isValid) {
    loading.value = false;
    ElMessage.error("请检查注册表单信息");
    return;
  }
  await submitRegister();
};

async function submitRegister() {
  try {
    const command = toRegisterCommand();
    const { data } = await CommonAPI.registerUser(command);
    await handleLoginSuccess(data, DEFAULT_ENTRY_PATH, "注册成功");
  } catch (error) {
    loading.value = false;
    await getCaptchaCode();
    if (error instanceof Error) {
      ElMessage.error(error.message);
    }
  }
}

function toRegisterCommand() {
  assertRegisterFormReady();
  return {
    username: registerForm.username,
    nickname: registerForm.nickname,
    password: rsaEncrypt(registerForm.password),
    confirmPassword: rsaEncrypt(registerForm.confirmPassword),
    email: registerForm.email,
    phoneNumber: registerForm.phoneNumber,
    captchaCode: registerForm.captchaCode,
    captchaCodeKey: registerForm.captchaCodeKey
  };
}

function assertRegisterFormReady() {
  if (!registerForm.username || !registerForm.password) {
    throw new Error("请输入账号和密码");
  }
  if (registerForm.password !== registerForm.confirmPassword) {
    throw new Error("两次输入的密码不一致");
  }
}

async function handleLoginSuccess(
  data: CommonAPI.TokenDTO,
  path: string,
  successMessage: string
) {
  setTokenFromBackend(data);
  await initRouter();
  const entryPath = path || DEFAULT_ENTRY_PATH;
  pushEntryTag(entryPath);
  router.push(entryPath);
  message(successMessage, { type: "success" });
}

function pushEntryTag(entryPath: string) {
  const children = router.options.routes[0]?.children ?? [];
  const route = findRouteByPath(entryPath, children);
  if (!route?.meta?.title) return;
  const { path, name, meta } = route;
  useMultiTagsStoreHook().handleTags("push", { path, name, meta });
}

function saveRememberedPassword() {
  if (isRememberMe.value) {
    savePassword(ruleForm.password);
  }
}

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

async function getCaptchaCode() {
  if (isCaptchaOn.value) {
    await CommonAPI.getCaptchaCode().then(res => {
      captchaCodeBase64.value = `data:image/gif;base64,${res.data.captchaCodeImg}`;
      setCaptchaCodeKey(res.data.captchaCodeKey);
    });
  }
}

function setCaptchaCodeKey(captchaCodeKey: string) {
  if (isRegisterMode.value) {
    registerForm.captchaCodeKey = captchaCodeKey;
    return;
  }
  ruleForm.captchaCodeKey = captchaCodeKey;
}

function switchMode(isRegister: boolean) {
  isRegisterMode.value = isRegister;
  clearCaptchaCode();
  getCaptchaCode();
}

function clearCaptchaCode() {
  ruleForm.captchaCode = "";
  ruleForm.captchaCodeKey = "";
  registerForm.captchaCode = "";
  registerForm.captchaCodeKey = "";
}

watch(isRememberMe, newVal => {
  saveIsRememberMe(newVal);
  if (newVal === false) {
    removePassword();
  }
});

onBeforeMount(async () => {
  await CommonAPI.getConfig().then(res => {
    isCaptchaOn.value = res.data.isCaptchaOn;
    isRegisterUserOn.value = res.data.isRegisterUserOn !== false;
    useUserStoreHook().SET_DICTIONARY(res.data.dictionary);
  });

  await getCaptchaCode();

  isRememberMe.value = getIsRememberMe();
  if (isRememberMe.value) {
    ruleForm.password = getPassword();
  }
});

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="absolute flex-c right-5 top-3">
      <!-- 主题 -->
      <el-switch
        v-model="dataTheme"
        :active-icon="dayIcon"
        :inactive-icon="darkIcon"
        inline-prompt
        @change="dataThemeChange"
      />
    </div>
    <div class="login-container">
      <div class="img">
        <!-- 登录页面的背景图 -->
        <component :is="toRaw(illustration)" />
      </div>
      <div class="login-box">
        <div class="login-form">
          <!-- 登录窗口上面的LOGO -->
          <avatar class="avatar" />
          <Motion>
            <h2 class="outline-none">
              <TypeIt :cursor="false" :speed="150" :values="[title]" />
            </h2>
          </Motion>

          <el-form
            v-if="!isRegisterMode"
            ref="ruleFormRef"
            :model="ruleForm"
            :rules="loginRules"
            size="large"
          >
            <Motion :delay="100">
              <el-form-item
                :rules="[
                  {
                    required: true,
                    message: '请输入账号',
                    trigger: 'blur'
                  }
                ]"
                prop="username"
              >
                <el-input
                  v-model="ruleForm.username"
                  :prefix-icon="useRenderIcon(User)"
                  clearable
                  placeholder="账号"
                />
              </el-form-item>
            </Motion>

            <Motion :delay="150">
              <el-form-item prop="password">
                <el-input
                  v-model="ruleForm.password"
                  :prefix-icon="useRenderIcon(Lock)"
                  clearable
                  placeholder="密码"
                  show-password
                />
              </el-form-item>
            </Motion>

            <Motion :delay="200">
              <el-form-item v-if="isCaptchaOn" prop="captchaCode">
                <el-input
                  v-model="ruleForm.captchaCode"
                  :prefix-icon="useRenderIcon('ri:shield-keyhole-line')"
                  clearable
                  placeholder="验证码"
                >
                  <template v-slot:append>
                    <el-image
                      :src="captchaCodeBase64"
                      style="
                        justify-content: center;
                        width: 120px;
                        height: 40px;
                      "
                      @click="getCaptchaCode"
                    >
                      <template #error>
                        <span>Loading</span>
                      </template>
                    </el-image>
                  </template>
                </el-input>
              </el-form-item>
            </Motion>

            <Motion :delay="250">
              <el-form-item>
                <div class="w-full h-[20px] flex justify-between items-center">
                  <el-checkbox v-model="isRememberMe"> 记住密码</el-checkbox>
                  <el-button
                    v-if="isRegisterUserOn"
                    link
                    native-type="button"
                    type="primary"
                    @click.prevent="switchMode(true)"
                  >
                    注册账号
                  </el-button>
                </div>
                <el-button
                  :loading="loading"
                  class="w-full mt-4"
                  native-type="button"
                  size="default"
                  type="primary"
                  @click.prevent="onLogin"
                >
                  登录
                </el-button>
              </el-form-item>
            </Motion>
          </el-form>

          <el-form
            v-else
            ref="registerFormRef"
            :model="registerForm"
            :rules="registerRules"
            size="large"
          >
            <Motion :delay="100">
              <el-form-item prop="username">
                <el-input
                  v-model="registerForm.username"
                  :prefix-icon="useRenderIcon(User)"
                  clearable
                  placeholder="账号"
                />
              </el-form-item>
            </Motion>

            <Motion :delay="150">
              <el-form-item prop="nickname">
                <el-input
                  v-model="registerForm.nickname"
                  :prefix-icon="useRenderIcon('ri:user-smile-line')"
                  clearable
                  placeholder="昵称"
                />
              </el-form-item>
            </Motion>

            <Motion :delay="200">
              <el-form-item prop="password">
                <el-input
                  v-model="registerForm.password"
                  :prefix-icon="useRenderIcon(Lock)"
                  clearable
                  placeholder="密码"
                  show-password
                />
              </el-form-item>
            </Motion>

            <Motion :delay="250">
              <el-form-item prop="confirmPassword">
                <el-input
                  v-model="registerForm.confirmPassword"
                  :prefix-icon="useRenderIcon(Lock)"
                  clearable
                  placeholder="确认密码"
                  show-password
                />
              </el-form-item>
            </Motion>

            <Motion :delay="300">
              <el-form-item prop="email">
                <el-input
                  v-model="registerForm.email"
                  :prefix-icon="useRenderIcon('ri:mail-line')"
                  clearable
                  placeholder="邮箱"
                />
              </el-form-item>
            </Motion>

            <Motion :delay="350">
              <el-form-item prop="phoneNumber">
                <el-input
                  v-model="registerForm.phoneNumber"
                  :prefix-icon="useRenderIcon('ri:phone-line')"
                  clearable
                  placeholder="手机号"
                />
              </el-form-item>
            </Motion>

            <Motion :delay="400">
              <el-form-item
                v-if="isCaptchaOn"
                :rules="[
                  {
                    required: true,
                    message: '请输入验证码',
                    trigger: 'blur'
                  }
                ]"
                prop="captchaCode"
              >
                <el-input
                  v-model="registerForm.captchaCode"
                  :prefix-icon="useRenderIcon('ri:shield-keyhole-line')"
                  clearable
                  placeholder="验证码"
                >
                  <template v-slot:append>
                    <el-image
                      :src="captchaCodeBase64"
                      style="
                        justify-content: center;
                        width: 120px;
                        height: 40px;
                      "
                      @click="getCaptchaCode"
                    >
                      <template #error>
                        <span>Loading</span>
                      </template>
                    </el-image>
                  </template>
                </el-input>
              </el-form-item>
            </Motion>

            <Motion :delay="450">
              <el-form-item>
                <div class="w-full h-[20px] flex justify-end items-center">
                  <el-button
                    link
                    native-type="button"
                    type="primary"
                    @click.prevent="switchMode(false)"
                  >
                    返回登录
                  </el-button>
                </div>
                <el-button
                  :loading="loading"
                  class="w-full mt-4"
                  native-type="button"
                  size="default"
                  type="primary"
                  @click.prevent="onRegister"
                >
                  注册
                </el-button>
              </el-form-item>
            </Motion>
          </el-form>
        </div>
      </div>
    </div>
    <!--  底部  -->
    <div class="flex items-center justify-center h-full">
      <div class="flex flex-col items-center justify-center mb-3">
        <span>Copyright © 2018-2023 Agileboot All Rights Reserved. </span>
        <el-link
          href="https://beian.miit.gov.cn"
          rel="external nofollow"
          target="_blank"
          type="primary"
          >闽ICP备2022018106号-2
        </el-link>
      </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;
}

.translation {
  ::v-deep(.el-dropdown-menu__item) {
    padding: 5px 40px;
  }

  .check-zh {
    position: absolute;
    left: 20px;
  }

  .check-en {
    position: absolute;
    left: 20px;
  }
}
</style>
