import { useEffect, useCallback } from 'react';
import { useUserStore } from '@/stores/userStore';
import userService from '@/services/user_service';
import type { IUserInfo } from '@/interfaces/database/user-setting';

/**
 * 用户数据管理Hook
 * 负责在登录后获取用户相关的全局数据
 */
export const useUserData = () => {
  const {
    userInfo,
    tenantInfo,
    tenantList,
    isLoading,
    error,
    setUserInfo,
    setTenantInfo,
    setTenantList,
    setLoading,
    setError,
    clearUserData,
  } = useUserStore();

  /**
   * 获取用户信息
   */
  const fetchUserInfo = useCallback(async () => {
    try {
      const response = await userService.getUserInfo();
      if (response.data.code === 0) {
        const userInfoData: IUserInfo | null = response.data.data || null;
        setUserInfo(userInfoData);
        return userInfoData;
      } else {
        throw new Error(response.data.message || '获取用户信息失败');
      }
    } catch (error) {
      console.error('获取用户信息失败:', error);
      throw error;
    }
  }, [setUserInfo]);

  /**
   * 获取租户信息
   */
  const fetchTenantInfo = useCallback(async () => {
    try {
      const response = await userService.getTenantInfo();
      if (response.data.code === 0) {
        setTenantInfo(response.data.data);
        return response.data.data;
      } else {
        throw new Error(response.data.message || '获取租户信息失败');
      }
    } catch (error) {
      console.error('获取租户信息失败:', error);
      throw error;
    }
  }, [setTenantInfo]);

  /**
   * 获取租户列表
   */
  const fetchTenantList = useCallback(async () => {
    try {
      const response = await userService.listTenant();
      if (response.data.code === 0) {
        setTenantList(response.data.data || []);
        return response.data.data;
      } else {
        throw new Error(response.data.message || '获取租户列表失败');
      }
    } catch (error) {
      console.error('获取租户列表失败:', error);
      throw error;
    }
  }, [setTenantList]);

  /**
   * 初始化所有用户数据
   * 并行请求三个API以提高性能
   */
  const initializeUserData = useCallback(async () => {
    setLoading(true);
    setError(null);

    try {
      // 并行请求三个API
      const [userInfoResult, tenantInfoResult, tenantListResult] = await Promise.allSettled([
        fetchUserInfo(),
        fetchTenantInfo(),
        fetchTenantList(),
      ]);

      // 检查是否有失败的请求
      const errors: string[] = [];
      
      if (userInfoResult.status === 'rejected') {
        errors.push(`用户信息: ${userInfoResult.reason.message}`);
      }
      
      if (tenantInfoResult.status === 'rejected') {
        errors.push(`租户信息: ${tenantInfoResult.reason.message}`);
      }
      
      if (tenantListResult.status === 'rejected') {
        errors.push(`租户列表: ${tenantListResult.reason.message}`);
      }

      if (errors.length > 0) {
        const errorMessage = `部分数据获取失败: ${errors.join(', ')}`;
        setError(errorMessage);
        console.warn(errorMessage);
      }

    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : '初始化用户数据失败';
      setError(errorMessage);
      console.error('初始化用户数据失败:', error);
    } finally {
      setLoading(false);
    }
  }, [fetchUserInfo, fetchTenantInfo, fetchTenantList, setLoading, setError]);

  /**
   * 刷新用户数据
   */
  const refreshUserData = useCallback(async () => {
    await initializeUserData();
  }, [initializeUserData]);

  /**
   * 清除用户数据
   */
  const logout = useCallback(() => {
    clearUserData();
  }, [clearUserData]);

  return {
    // 状态
    userInfo,
    tenantInfo,
    tenantList,
    isLoading,
    error,
    
    // 方法
    initializeUserData,
    refreshUserData,
    fetchUserInfo,
    fetchTenantInfo,
    fetchTenantList,
    logout,
  };
};