import { useState, useEffect, useCallback } from 'react';
import services from '@/services';
import { useGlobalModalServices } from '@/pages/GlobalModalServices/provider';

// 服务类型定义
export interface ServiceItem {
  id: string;
  linkUrl?: string;
  name?: string;
  [key: string]: any;
}

// 服务动作类型
export type ServiceAction = 'refresh' | 'newTab' | 'modal';

// 专项服务配置项
export interface ServiceConfig {
  id: string;
  logoSrc: string;
  titleSrc?: string;
  targetUrl?: string;
  action?: ServiceAction;
  modalKey?: string;
  modalProps?: Record<string, any>;
  label?: string; // 用于导航栏显示
}

/**
 * 专项服务hook，用于获取服务列表和处理跳转逻辑
 */
export function useSpecialServices() {
  const [serviceList, setServiceList] = useState<ServiceItem[]>([]);
  const [loading, setLoading] = useState(false);
  const { dispatch } = useGlobalModalServices();

  // 获取专项服务列表
  useEffect(() => {
    setLoading(true);
    services.AuthApi.getSpecialServiceListApi({
      groupId: 'SPECIFIC_SERVICE'
    }).then(res => {
      if (res.code === 200) {
        setServiceList(res.data || []);
      }
    }).finally(() => {
      setLoading(false);
    });
  }, []);

  // 处理服务跳转
  const handleServiceAction = useCallback((service: ServiceConfig) => {
    if (!service) return;
    
    // 根据服务配置的动作类型执行不同操作
    switch(service.action) {
      case 'refresh':
        // 刷新页面
        window.location.reload();
        break;
        
      case 'newTab':
        // 在新标签页打开链接
        if (service.targetUrl) {
          window.open(service.targetUrl, '_blank');
        }
        break;
        
      case 'modal':
        // 打开弹窗
        if (service.modalKey) {
          dispatch.push(service.modalKey as any, {
            style: { marginTop: '-100px' },
            props: service.modalProps || {},
          });
        }
        break;
        
      default:
        // 默认在新标签页打开
        if (service.targetUrl) {
          window.open(service.targetUrl, '_blank');
        }
    }
  }, [dispatch]);

  // 根据ID获取服务配置
  const getServiceById = useCallback((id: string): ServiceItem | undefined => {
    return serviceList.find(item => item.id === id);
  }, [serviceList]);

  return {
    serviceList,
    loading,
    handleServiceAction,
    getServiceById,
  };
}

export default useSpecialServices; 