<script setup lang="ts">
import { useI18n } from "vue-i18n";
import Motion from "./utils/motion";
import { useRouter, useRoute } from "vue-router";
import { message } from "@/utils/message";
import { loginRules } from "./utils/rule";
import TypeIt from "@/components/ReTypeit";
import { debounce } from "@pureadmin/utils";
import { useNav } from "@/layout/hooks/useNav";
import { useEventListener } from "@vueuse/core";
import type { FormInstance } from "element-plus";
import { $t, transformI18n } from "@/plugins/i18n";
import { operates, thirdParty } from "./utils/enums";
import { useLayout } from "@/layout/hooks/useLayout";
import LoginPhone from "./components/LoginPhone.vue";
import LoginRegist from "./components/LoginRegist.vue";
import LoginUpdate from "./components/LoginUpdate.vue";
import LoginQrCode from "./components/LoginQrCode.vue";
import { useUserStoreHook } from "@/store/modules/user";
import { initRouter, getTopMenu } from "@/router/utils";
import { bg, avatar, illustration } from "./utils/static";
import { ReImageVerify } from "@/components/ReImageVerify";
import { ref, toRaw, reactive, watch, computed, onMounted } from "vue";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import { useTranslationLang } from "@/layout/hooks/useTranslationLang";
import { useDataThemeChange } from "@/layout/hooks/useDataThemeChange";
import { getFeishuLogin } from "@/api/feishu";
import { setToken, userKey } from "@/utils/auth";
import { storageLocal } from "@pureadmin/utils";

import dayIcon from "@/assets/svg/day.svg?component";
import darkIcon from "@/assets/svg/dark.svg?component";
import globalization from "@/assets/svg/globalization.svg?component";
import Lock from "~icons/ri/lock-fill";
import Check from "~icons/ep/check";
import User from "~icons/ri/user-3-fill";
import Info from "~icons/ri/information-line";
import Keyhole from "~icons/ri/shield-keyhole-line";

defineOptions({
  name: "Login"
});

// 飞书OAuth配置
const FEISHU_APP_ID = "cli_a94c8a7930badcd5";
// 使用hash路由模式，redirect_uri需要包含#
const FEISHU_REDIRECT_URI = encodeURIComponent(
  window.location.origin + "/#/login"
);

const imgCode = ref("");
const loginDay = ref(7);
const router = useRouter();
const route = useRoute();
const loading = ref(false);
const checked = ref(false);
const disabled = ref(false);
const ruleFormRef = ref<FormInstance>();
const currentPage = computed(() => {
  return useUserStoreHook().currentPage;
});

// 飞书登录loading状态
const feishuLoading = ref(false);

// 是否显示飞书登录（作为默认登录方式）
const showFeishuLogin = ref(true);

const { t } = useI18n();
const { initStorage } = useLayout();
initStorage();
const { dataTheme, themeMode, dataThemeChange } = useDataThemeChange();
dataThemeChange(themeMode.value);
const { title, getDropdownItemStyle, getDropdownItemClass } = useNav();
const { locale, translationCh, translationEn } = useTranslationLang();

const ruleForm = reactive({
  username: "admin",
  password: "admin123",
  verifyCode: ""
});

const onLogin = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate(valid => {
    if (valid) {
      loading.value = true;
      useUserStoreHook()
        .loginByUsername({
          username: ruleForm.username,
          password: ruleForm.password
        })
        .then(async () => {
          // 获取后端路由
          await initRouter();
          disabled.value = true;
          router.push(getTopMenu(true).path).then(() => {
            message(t("login.pureLoginSuccess"), { type: "success" });
          });
        })
        .catch(_err => {
          message(t("login.pureLoginFail"), { type: "error" });
        })
        .finally(() => {
          disabled.value = false;
          loading.value = false;
        });
    }
  });
};

const immediateDebounce: any = debounce(
  formRef => onLogin(formRef),
  1000,
  true
);

useEventListener(document, "keydown", ({ code }) => {
  if (
    ["Enter", "NumpadEnter"].includes(code) &&
    !disabled.value &&
    !loading.value
  )
    immediateDebounce(ruleFormRef.value);
});

watch(imgCode, value => {
  useUserStoreHook().SET_VERIFYCODE(value);
});
watch(checked, bool => {
  useUserStoreHook().SET_ISREMEMBERED(bool);
});
watch(loginDay, value => {
  useUserStoreHook().SET_LOGINDAY(value);
});

/** 跳转到飞书授权页面 */
const handleFeishuLogin = () => {
  const feishuAuthUrl = `https://open.feishu.cn/open-apis/authen/v1/index?app_id=${FEISHU_APP_ID}&redirect_uri=${FEISHU_REDIRECT_URI}`;
  window.location.href = feishuAuthUrl;
};

/** 处理飞书回调登录 */
const handleFeishuCallback = async (code: string) => {
  feishuLoading.value = true;
  try {
    const res = await getFeishuLogin(code);
    if (res.code === 200 && res.data?.token) {
      const { data } = res;
      // 设置token（适配后端返回的字段名）
      setToken({
        accessToken: data.token,
        expires: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000),
        refreshToken: data.token,
        avatar: data.avatar,
        username: data.username,
        nickname: data.realName,
        userId: data.userId,
        roles: data.roles || ["admin"],
        permissions: data.permissions || []
      });

      // 保存用户信息到本地存储
      storageLocal().setItem(userKey, {
        refreshToken: data.token,
        expires: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000).getTime(),
        avatar: data.avatar,
        username: data.username,
        nickname: data.realName,
        userId: data.userId,
        roles: data.roles || ["admin"],
        permissions: data.permissions || []
      });

      // 更新全局状态
      const userStore = useUserStoreHook();
      userStore.SET_AVATAR(data.avatar);
      userStore.SET_USERNAME(data.username);
      userStore.SET_NICKNAME(data.realName);
      userStore.SET_USERID(data.userId);
      userStore.SET_ROLES(data.roles || ["admin"]);
      userStore.SET_PERMS(data.permissions || []);

      // 初始化路由
      await initRouter();

      // 跳转到首页
      router.push(getTopMenu(true).path).then(() => {
        message(t("login.pureLoginSuccess"), { type: "success" });
      });
    } else {
      message(res.message || "飞书登录失败", { type: "error" });
    }
  } catch (err) {
    console.error("飞书登录失败:", err);
    message("飞书登录失败", { type: "error" });
  } finally {
    feishuLoading.value = false;
  }
};

/** 切换到账号密码登录 */
const switchToAccountLogin = () => {
  showFeishuLogin.value = false;
};

/** 切换到飞书登录 */
const switchToFeishuLogin = () => {
  showFeishuLogin.value = true;
};

// 页面加载时检查是否有飞书回调code
onMounted(() => {
  // hash路由模式下，飞书回调URL格式为: http://localhost:8848/?code=xxx#/login
  // 或者在hash内部: http://localhost:8848/#/login?code=xxx
  // 需要同时检查两种情况
  let code: string | null = null;

  // 方式1: code在hash之前 (飞书回调的标准方式)
  const urlParams = new URLSearchParams(window.location.search);
  code = urlParams.get("code");

  // 方式2: 如果没有找到，尝试从hash内部获取
  if (!code) {
    const hash = window.location.hash;
    const hashParams = new URLSearchParams(hash.split("?")[1] || "");
    code = hashParams.get("code");
  }

  if (code) {
    handleFeishuCallback(code);
    // 清除 URL 中的 code 参数，避免重复处理
    const cleanUrl = window.location.origin + "/#/login";
    window.history.replaceState({}, document.title, cleanUrl);
  }
});
</script>

<template>
  <div class="select-none">
    <img :src="bg" class="wave" />
    <div class="flex-c absolute right-5 top-3">
      <!-- 主题 -->
      <el-switch
        v-model="dataTheme"
        inline-prompt
        :active-icon="dayIcon"
        :inactive-icon="darkIcon"
        @change="dataThemeChange"
      />
      <!-- 国际化 -->
      <el-dropdown trigger="click">
        <globalization
          class="hover:text-primary hover:bg-transparent! size-5 ml-1.5 cursor-pointer outline-hidden duration-300"
        />
        <template #dropdown>
          <el-dropdown-menu class="translation">
            <el-dropdown-item
              :style="getDropdownItemStyle(locale, 'zh')"
              :class="['dark:text-white!', getDropdownItemClass(locale, 'zh')]"
              @click="translationCh"
            >
              <IconifyIconOffline
                v-show="locale === 'zh'"
                class="check-zh"
                :icon="Check"
              />
              简体中文
            </el-dropdown-item>
            <el-dropdown-item
              :style="getDropdownItemStyle(locale, 'en')"
              :class="['dark:text-white!', getDropdownItemClass(locale, 'en')]"
              @click="translationEn"
            >
              <span v-show="locale === 'en'" class="check-en">
                <IconifyIconOffline :icon="Check" />
              </span>
              English
            </el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown>
    </div>
    <div class="login-container">
      <div class="img">
        <component :is="toRaw(illustration)" />
      </div>
      <div class="login-box">
        <div class="login-form">
          <avatar class="avatar" />
          <Motion>
            <h2 class="outline-hidden">
              <TypeIt
                :options="{ strings: [title], cursor: false, speed: 100 }"
              />
            </h2>
          </Motion>

          <!-- 飞书登录 - 默认登录方式 -->
          <div
            v-if="currentPage === 0 && showFeishuLogin"
            class="feishu-login-container"
          >
            <Motion :delay="100">
              <div class="feishu-login-box">
                <div class="feishu-icon">
                  <svg viewBox="0 0 1024 1024" width="64" height="64">
                    <path
                      fill="#3370FF"
                      d="M512 64C264.6 64 64 264.6 64 512s200.6 448 448 448 448-200.6 448-448S759.4 64 512 64zm0 820c-205.4 0-372-166.6-372-372s166.6-372 372-372 372 166.6 372 372-166.6 372-372 372z"
                    />
                    <path
                      fill="#3370FF"
                      d="M696 480H544V328c0-4.4-3.6-8-8-8h-48c-4.4 0-8 3.6-8 8v152H328c-4.4 0-8 3.6-8 8v48c0 4.4 3.6 8 8 8h152v152c0 4.4 3.6 8 8 8h48c4.4 0 8-3.6 8-8V544h152c4.4 0 8-3.6 8-8v-48c0-4.4-3.6-8-8-8z"
                    />
                  </svg>
                </div>
                <h3 class="feishu-title">飞书登录</h3>
                <p class="feishu-desc">使用飞书扫码或授权登录</p>
                <el-button
                  class="w-full mt-4 feishu-login-btn"
                  size="large"
                  type="primary"
                  :loading="feishuLoading"
                  @click="handleFeishuLogin"
                >
                  <IconifyIconOnline icon="ri:login-circle-line" class="mr-1" />
                  点击授权登录
                </el-button>
                <div class="login-switch">
                  <el-button link type="primary" @click="switchToAccountLogin">
                    使用账号密码登录
                  </el-button>
                </div>
              </div>
            </Motion>
          </div>

          <el-form
            v-if="currentPage === 0 && !showFeishuLogin"
            ref="ruleFormRef"
            :model="ruleForm"
            :rules="loginRules"
            size="large"
          >
            <Motion :delay="100">
              <el-form-item
                :rules="[
                  {
                    required: true,
                    message: transformI18n($t('login.pureUsernameReg')),
                    trigger: 'blur'
                  }
                ]"
                prop="username"
              >
                <el-input
                  v-model="ruleForm.username"
                  clearable
                  :placeholder="t('login.pureUsername')"
                  :prefix-icon="useRenderIcon(User)"
                />
              </el-form-item>
            </Motion>

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

            <Motion :delay="200">
              <el-form-item prop="verifyCode">
                <el-input
                  v-model="ruleForm.verifyCode"
                  clearable
                  :placeholder="t('login.pureVerifyCode')"
                  :prefix-icon="useRenderIcon(Keyhole)"
                >
                  <template v-slot:append>
                    <ReImageVerify v-model:code="imgCode" />
                  </template>
                </el-input>
              </el-form-item>
            </Motion>

            <Motion :delay="250">
              <el-form-item>
                <div class="w-full h-5 flex-bc">
                  <el-checkbox v-model="checked">
                    <span class="flex">
                      <select
                        v-model="loginDay"
                        :style="{
                          width: loginDay < 10 ? '10px' : '16px',
                          outline: 'none',
                          background: 'none',
                          appearance: 'none',
                          border: 'none'
                        }"
                      >
                        <option value="1">1</option>
                        <option value="7">7</option>
                        <option value="30">30</option>
                      </select>
                      {{ t("login.pureRemember") }}
                      <IconifyIconOffline
                        v-tippy="{
                          content: t('login.pureRememberInfo'),
                          placement: 'top'
                        }"
                        :icon="Info"
                        class="ml-1"
                      />
                    </span>
                  </el-checkbox>
                  <el-button
                    link
                    type="primary"
                    @click="useUserStoreHook().SET_CURRENTPAGE(4)"
                  >
                    {{ t("login.pureForget") }}
                  </el-button>
                </div>
                <el-button
                  class="w-full mt-4!"
                  size="default"
                  type="primary"
                  :loading="loading"
                  :disabled="disabled"
                  @click="onLogin(ruleFormRef)"
                >
                  {{ t("login.pureLogin") }}
                </el-button>
              </el-form-item>
            </Motion>

            <Motion :delay="300">
              <el-form-item>
                <div class="w-full h-5 flex-bc">
                  <el-button
                    v-for="(item, index) in operates"
                    :key="index"
                    class="w-full mt-4!"
                    size="default"
                    @click="useUserStoreHook().SET_CURRENTPAGE(index + 1)"
                  >
                    {{ t(item.title) }}
                  </el-button>
                </div>
              </el-form-item>
            </Motion>

            <!-- 切换回飞书登录 -->
            <Motion :delay="350">
              <el-form-item>
                <div class="login-switch mt-4">
                  <el-button link type="primary" @click="switchToFeishuLogin">
                    使用飞书登录
                  </el-button>
                </div>
              </el-form-item>
            </Motion>
          </el-form>

          <Motion v-if="currentPage === 0" :delay="350">
            <el-form-item>
              <el-divider>
                <p class="text-gray-500 text-xs">
                  {{ t("login.pureThirdLogin") }}
                </p>
              </el-divider>
              <div class="w-full flex justify-evenly">
                <span
                  v-for="(item, index) in thirdParty"
                  :key="index"
                  :title="t(item.title)"
                >
                  <IconifyIconOnline
                    :icon="`ri:${item.icon}-fill`"
                    width="20"
                    class="cursor-pointer text-gray-500 hover:text-blue-400"
                  />
                </span>
              </div>
            </el-form-item>
          </Motion>
          <!-- 手机号登录 -->
          <LoginPhone v-if="currentPage === 1" />
          <!-- 二维码登录 -->
          <LoginQrCode v-if="currentPage === 2" />
          <!-- 注册 -->
          <LoginRegist v-if="currentPage === 3" />
          <!-- 忘记密码 -->
          <LoginUpdate v-if="currentPage === 4" />
        </div>
      </div>
    </div>
    <div
      class="w-full flex-c absolute bottom-3 text-sm text-[rgba(0,0,0,0.6)] dark:text-[rgba(220,220,242,0.8)]"
    >
      Copyright © 2020-present
      <a
        class="hover:text-primary!"
        href="https://github.com/pure-admin"
        target="_blank"
      >
        &nbsp;{{ title }}
      </a>
    </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 {
  :deep(.el-dropdown-menu__item) {
    padding: 5px 40px;
  }

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

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

/* 飞书登录样式 */
.feishu-login-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 20px 0;
}

.feishu-login-box {
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 100%;
}

.feishu-icon {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 80px;
  height: 80px;
  margin-bottom: 20px;
  background: linear-gradient(135deg, #3370ff20, #3370ff10);
  border-radius: 20px;
}

.feishu-title {
  margin: 0 0 8px;
  font-size: 20px;
  font-weight: 600;
  color: var(--el-text-color-primary);
}

.feishu-desc {
  margin: 0 0 24px;
  font-size: 14px;
  color: var(--el-text-color-secondary);
}

.feishu-login-btn {
  height: 44px;
  font-size: 16px;
  font-weight: 500;
  background: linear-gradient(135deg, #3370ff, #2b5fd9);
  border: none;

  &:hover {
    background: linear-gradient(135deg, #2860d9, #1f4fb3);
  }
}

.login-switch {
  margin-top: 20px;
  text-align: center;
}
</style>
