import { computed, reactive, ref } from 'vue';
import { useRoute } from 'vue-router';
import { defineStore } from 'pinia';
import { useLoading } from '@sa/hooks';
import { SetupStoreId } from '@/enum';
import { useRouterPush } from '@/hooks/common/router';
import { fetchLogin, fetchLogout } from '@/service/api';
import { localStg } from '@/utils/storage';
import { $t } from '@/locales';
import { useRouteStore } from '../route';
import { useTabStore } from '../tab';
import { clearAuthStorage, getLocalUserInfo, getToken } from './shared';

export const useAuthStore = defineStore(SetupStoreId.Auth, () => {
  const route = useRoute();
  const routeStore = useRouteStore();
  const tabStore = useTabStore();
  const { toLogin, redirectFromLogin } = useRouterPush(false);
  const { loading: loginLoading, startLoading, endLoading } = useLoading();

  const token = ref(getToken());

  const userInfo: Api.Auth.UserInfo = reactive({
    userId: '',
    userName: '',
    FullName: '',
    roles: [],
    buttons: []
  });

  /** is super role in static route */
  const isStaticSuper = computed(() => {
    const { VITE_AUTH_ROUTE_MODE, VITE_STATIC_SUPER_ROLE } = import.meta.env;

    return VITE_AUTH_ROUTE_MODE === 'static' && userInfo.roles.includes(VITE_STATIC_SUPER_ROLE);
  });

  /** Is login */
  const isLogin = computed(() => Boolean(token.value));

  /** Reset auth store */
  async function resetStore() {
    const authStore = useAuthStore();

    try {
      // 调用退出接口
      const { error } = await fetchLogout();
      if (!error) {
        // 清除存储
        clearAuthStorage();
        // 重置store
        authStore.$reset();
        // 设置未认证状态
        if (window.uiGlobalConfig) {
          window.uiGlobalConfig.IsAuthenticated = false;
        }

        if (!route.meta.constant) {
          await toLogin();
        }

        tabStore.cacheTabs();
        routeStore.resetStore();
      }
    } catch (err) {
      // 即使退出接口失败，也要清除本地状态
      clearAuthStorage();
      authStore.$reset();
      // 设置未认证状态
      if (window.uiGlobalConfig) {
        window.uiGlobalConfig.IsAuthenticated = false;
      }

      if (!route.meta.constant) {
        await toLogin();
      }

      tabStore.cacheTabs();
      routeStore.resetStore();
    }
  }

  /** Handle successful login redirect */
  async function handleLoginRedirect() {
    try {
      await redirectFromLogin();

      // 显示成功通知
      window.$notification?.success({
        title: $t('page.login.common.loginSuccess'),
        content: $t('page.login.common.welcomeBack', { FullName: userInfo.FullName }),
        duration: 4500
      });
    } catch (redirectError) {
      console.error('Redirect error:', redirectError);
      // 如果重定向失败，直接跳转到首页
      window.location.href = '/home';
    }
  }

  /** Initialize routes after login */
  async function initializeAuthRoutes(redirect: boolean) {
    // 登录后清除动态路由缓存，确保获取最新数据
    try {
      const { clearDynamicRoutesCache } = await import('@/router/routes');
      clearDynamicRoutesCache();
    } catch (error) {
      console.warn('清除动态路由缓存失败:', error);
    }

    await routeStore.forceReloadAuthRoute();

    if (!routeStore.isInitAuthRoute) {
      console.error('Failed to initialize auth routes');
      throw new Error('Route initialization failed');
    }

    // 确保菜单也更新了
    await routeStore.updateGlobalMenusByLocale();

    if (redirect) {
      // 延迟执行重定向，确保路由完全加载
      setTimeout(() => handleLoginRedirect(), 300);
    }
  }

  /**
   * Login
   *
   * @param userName User name
   * @param password Password
   * @param [redirect=true] Whether to redirect after login. Default is `true`
   */
  async function login(userName: string, password: string, redirect = true) {
    startLoading();

    try {
      const { data: loginToken, error } = await fetchLogin(userName, password);
      if (error) {
        resetStore();
        return;
      }

      const pass = await loginByToken(loginToken);
      if (!pass) {
        resetStore();
        return;
      }

      // 设置认证状态为true
      if (window.uiGlobalConfig) {
        window.uiGlobalConfig.IsAuthenticated = true;
      }

      try {
        await initializeAuthRoutes(redirect);
      } catch (routeError) {
        console.error('Route loading error:', routeError);
        // 如果路由初始化失败，尝试刷新页面作为备用方案
        setTimeout(() => {
          window.location.reload();
        }, 1000);
      }
    } catch (loginError) {
      console.error('Login error:', loginError);
      resetStore();
    }

    endLoading();
  }

  async function loginByToken(loginToken: Api.Auth.LoginToken) {
    // 1. stored in the localStorage, the later requests need it in headers
    localStg.set('token', loginToken.SessionId);
    localStg.set('refreshToken', loginToken.SessionId);
    localStg.set('userInfo', JSON.stringify(loginToken));

    // 2. get user info
    token.value = loginToken.FullName;
    Object.assign(userInfo, loginToken);

    return true;
  }

  async function initUserInfo() {
    const hasToken = getToken();
    const userInfoStr = getLocalUserInfo();

    if (hasToken) {
      try {
        const hasUserInfo = userInfoStr ? JSON.parse(userInfoStr) : null;
        if (hasUserInfo) {
          token.value = hasUserInfo.FullName;
          Object.assign(userInfo, hasUserInfo);
        } else {
          resetStore();
        }
      } catch (error) {
        console.error('Error parsing user info:', error);
        resetStore();
      }
    }
  }

  return {
    token,
    userInfo,
    isStaticSuper,
    isLogin,
    loginLoading,
    resetStore,
    login,
    initUserInfo
  };
});
