import type { Recordable, UserInfo } from '@vben/types';

import { ref } from 'vue';
import { useRouter } from 'vue-router';

import { DEFAULT_HOME_PATH, LOGIN_PATH } from '@vben/constants';
import { resetAllStores, useAccessStore, useUserStore } from '@vben/stores';

import { notification } from 'ant-design-vue';
import { defineStore } from 'pinia';

import { getUserInfoApi, loginApi, logoutApi } from '#/api';
import { setToken } from '#/api/csrf';
import { $t } from '#/locales';

export const useAuthStore = defineStore('auth', () => {
  const accessStore = useAccessStore();
  const userStore = useUserStore();
  const router = useRouter();

  const loginLoading = ref(false);

  /**
   * 异步处理登录操作
   * Asynchronously handle the login process
   * @param params 登录表单数据
   */
  async function authLogin(
    params: Recordable<any>,
    onSuccess?: () => Promise<void> | void,
  ) {
    // 异步处理用户登录操作并获取 accessToken
    const userInfo: null | UserInfo = null;
    try {
      loginLoading.value = true;
      const { user, csrf } = await loginApi(params);

      // 如果成功获取到 accessToken
      if (typeof user !== 'string') {
        // accessStore.setAccessToken(accessToken);
        //
        // // 获取用户信息并存储到 accessStore 中
        // const [fetchUserInfoResult, accessCodes] = await Promise.all([
        //   fetchUserInfo(),
        //   getAccessCodesApi(),
        // ]);

        const userInfo = {
          userId: user?.id?.toString() ?? '',
          avatar: '',
          realName: user.username,
          username: user.username,
          roles: [user.role.name],
          // permissions Keven自定义
          permissions: user.permissions,
          homePath: '/home',
          token: csrf.token,
        };
        accessStore.setAccessToken(csrf.token);

        userStore.setUserInfo(userInfo);
        accessStore.setAccessCodes(user.permissions);

        if (accessStore.loginExpired) {
          accessStore.setLoginExpired(false);
        } else {
          onSuccess
            ? await onSuccess?.()
            : await router.push(userInfo?.homePath || DEFAULT_HOME_PATH);
        }

        if (userInfo?.realName) {
          notification.success({
            description: `${$t('authentication.loginSuccessDesc')}:${userInfo?.realName}`,
            duration: 3,
            message: $t('authentication.loginSuccess'),
          });
        }
      }
    } catch (error: any) {
      if (error.code === 401) {
        const { csrf } = await getUserInfoApi(); // 获取新的 token
        setToken(csrf.token); // 更新 CSRF token
        accessStore.setAccessToken(csrf.token);
      }
    } finally {
      loginLoading.value = false;
    }

    return {
      userInfo,
    };
  }

  async function logout() {
    try {
      await logoutApi();
    } catch {
      // 不做任何处理
    }
    resetAllStores();
    accessStore.setLoginExpired(false);

    // 回登录页带上当前路由地址
    await router.replace({
      path: LOGIN_PATH,
      // query: redirect
      //   ? {
      //       redirect: encodeURIComponent(router.currentRoute.value.fullPath),
      //     }
      //   : {},
    });
  }

  async function fetchUserInfo() {
    // let userInfo: null | UserInfo;
    const { user, csrf } = await getUserInfoApi();
    if (typeof user !== 'string') {
      const userInfo = {
        userId: user?.id?.toString() ?? '',
        avatar: '',
        realName: user.username,
        username: user.username,
        roles: [user.role.name],
        homePath: '/home',
        token: csrf.token,
      };
      userStore.setUserInfo(userInfo);
      return userInfo;
    }
    return null;
  }

  async function csrfToken() {
    const { csrf } = await getUserInfoApi();
    setToken(csrf.token);
  }

  function $reset() {
    loginLoading.value = false;
  }

  // 👇 添加 hasPerm 方法
  function hasPerm(permission: string): boolean {
    const userInfo = userStore.userInfo;
    return Boolean(userInfo?.permissions?.includes(permission));
  }

  return {
    $reset,
    authLogin,
    fetchUserInfo,
    loginLoading,
    logout,
    csrfToken,
    hasPerm,
  };
});
