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

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

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

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

import { getUserInfoApi, loginApi, logoutApi } from '#/api';
import { accessRoutes } from '#/router/routes';

import { useDictStore } from './dict';

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
    let userInfo: null | UserInfo = null;
    try {
      loginLoading.value = true;
      const { accessToken } = await loginApi(params);
      // 如果成功获取到 accessToken
      if (accessToken) {
        accessStore.setAccessToken(accessToken);

        // 获取用户信息并存储到 accessStore 中
        // const [fetchUserInfoResult, accessCodes] = await Promise.all([
        //   fetchUserInfo(),
        //   // getAccessCodesApi(),
        // ]);

        userInfo = await fetchUserInfo();

        userStore.setUserInfo(userInfo);
        // accessStore.setAccessCodes(accessCodes);

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

        if (userInfo?.realName) {
          notification.success({
            description: `欢迎回来:${userInfo?.realName}`,
            duration: 3,
            message: '登陆成功',
          });
        }
      }
    } finally {
      loginLoading.value = false;
    }

    return {
      userInfo,
    };
  }

  async function logout(redirect: boolean = true) {
    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() {
    const backUserInfo = await getUserInfoApi();
    /**
     * 登录超时的情况
     */
    if (!backUserInfo) {
      throw new Error('获取用户信息失败.');
    }
    const {
      authorities = [],
      roles = [],
      sysUser,
      homePath = '',
    } = backUserInfo;
    let realHomePath = '';
    if (homePath) {
      const finalRoutes = flatFilterTree(accessRoutes, (route) => {
        return route.name === homePath;
      });
      console.log('[homePath]', finalRoutes);
      realHomePath = finalRoutes.length > 0 ? finalRoutes[0]?.path || '' : '';
    }
    console.log('[userInfo]', realHomePath);
    /**
     * 从后台user -> vben user转换
     */
    const userInfo: UserInfo = {
      avatar:
        'https://unpkg.com/@vbenjs/static-source@0.1.7/source/avatar-v1.webp',
      realName: sysUser.name,
      userId: `${sysUser.id}`,
      username: sysUser.username,
      desc: sysUser.remark || '',
      homePath: realHomePath,
      token: '',
      roles,
      // permissions: authorities,
    };
    userStore.setUserInfo(userInfo);
    /**
     * 在这里设置权限
     */
    accessStore.setAccessCodes(authorities);
    /**
     * 需要重新加载字典
     * 比如退出登录切换到其他租户
     */
    const dictStore = useDictStore();
    dictStore.resetCache();
    return userInfo;
  }

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

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