import React, { useEffect, useState, useCallback, useRef, useMemo } from 'react';
import StatCard from '@/components/V2504/StatCard';
import styles from './index.less';
import { useDataType, useMapState } from '@/pages/Home_v_2504/components/MapStateContext';
import { getDisposeStats } from '@/services/CityProblem';
import { formatDateTime } from '@/pages/Home_v_2504/hooks/useApiControl';
import useLatestValue from '@/pages/Home_v_2504/hooks/useLatestValue';
import usePageAwareApi from '@/pages/Home_v_2504/hooks/usePageAwareApi';

// Import stat card background images
import cardBg1 from '@/assets/images/V-2504/statcard-bg-1.png';
import cardBg2 from '@/assets/images/V-2504/statcard-bg-2.png';
import cardBg3 from '@/assets/images/V-2504/statcard-bg-3.png';
import cardBg4 from '@/assets/images/V-2504/statcard-bg-4.png';
import cardBg5 from '@/assets/images/V-2504/statcard-bg-5.png';

export interface StatisticsCardsProps {
  dateType?: string;
  dateRange?: { startTime: string; endTime: string };
  dataTypeKey?: string;
  pageId?: string; // 新增页面ID参数
}

// 案件情况数据结构
interface DisposeStatsData {
  accept: { name: string; code: string; value: number };
  disposing: { name: string; code: string; value: number };
  overdue: { name: string; code: string; value: number };
  close: { name: string; code: string; value: number };
  closeRate: { name: string; code: string; value: number };
}

const StatisticsCards: React.FC<StatisticsCardsProps> = ({ 
  dateType, 
  dateRange, 
  dataTypeKey = '餐饮油烟事件',
  pageId = 'restaurantOil' // 默认为restaurantOil
}) => {
  // 地图状态
  const { mapState } = useMapState();
  // 使用ref存储最新的mapState，避免闭包问题
  const mapStateRef = useLatestValue(mapState);
  
  // 案件情况统计数据
  const [statsData, setStatsData] = useState({
    caseCount: 0,       // 立案
    processingCount: 0, // 处置中
    overtimeCount: 0,   // 超时
    completedCount: 0,  // 已办结
    completionRate: 0,  // 办结率
  });
  
  // 转换日期类型为API参数
  const translateDateType = useCallback((type: string) => {
    switch (type) {
      case 'year': return '1';
      case 'month': return '2';
      case 'day': return '3';
      case 'range': return '4';
      default: return '2'; // 默认月视图
    }
  }, []);
  
  // 参数格式化函数
  const formatApiParams = useCallback((params: any) => {
    const formattedParams = { ...params };
    
    // 确保时间字段包含完整的时间部分
    if (formattedParams.time) {
      formattedParams.time = formatDateTime(formattedParams.time);
    }
    
    if (formattedParams.customizeStart) {
      formattedParams.customizeStart = formatDateTime(formattedParams.customizeStart);
    }
    
    if (formattedParams.customizeEnd) {
      formattedParams.customizeEnd = formatDateTime(formattedParams.customizeEnd, true);
    }
    
    return formattedParams;
  }, []);
  
  // 使用usePageAwareApi管理案件情况API调用
  const disposeStatsApi = usePageAwareApi({
    apiFunction: async (params: any) => {
      const response = await getDisposeStats(params);
      
      if (response.code === 200 && response.data) {
        return response.data;
      }
      
      throw new Error('获取案件情况数据失败');
    },
    onSuccess: (data: DisposeStatsData) => {
      if (!data) return;
      
      // 转换接口返回的数据格式
      setStatsData({
        caseCount: data.accept?.value || 0,
        processingCount: data.disposing?.value || 0,
        overtimeCount: data.overdue?.value || 0,
        completedCount: data.close?.value || 0,
        completionRate: data.closeRate?.value || 0,
      });
      
      console.log('案件情况数据成功:', data);
    },
    onError: (error: any) => {
      console.error('获取案件情况数据出错:', error);
    },
    formatParams: formatApiParams,
    apiName: '案件情况',
    debounceTime: 300,
    cacheTime: 5000, // 缓存5秒，避免频繁刷新时重复请求
    enableDebug: false,
    pageId: pageId, // 添加页面ID以启用页面感知
  });

  // 构建API参数函数
  const buildApiParams = useCallback(() => {
    const currentMapState = mapStateRef.current;
    
    // 如果没有必要的时间参数，返回null表示不应该发起请求
    if (!currentMapState.rightPanelTime?.startTime || !currentMapState.rightPanelTime?.endTime) {
      return null;
    }
    
    // 获取当前页面的时间设置
    const pageTimeSettings = currentMapState.pageTimeSettings?.[pageId];
    if (!pageTimeSettings) {
      console.log(`缺少${pageId}页面的时间设置，使用全局设置`);
    }
    
    // 使用页面级别的时间设置，如果存在的话
    const rightPanelTime = pageTimeSettings?.rightPanelTime || currentMapState.rightPanelTime;
    
    // 使用当前时间类型，如果不存在则使用props或默认值
    const effectiveType = rightPanelTime.type || dateType || 'month';
    
    // 基础参数对象
    const params: any = {
      type: translateDateType(effectiveType),
      subTypeCode: useDataType(dataTypeKey)
    };
    
    // 处理日期参数
    if (effectiveType === 'range') {
      params.customizeStart = rightPanelTime.startTime;
      params.customizeEnd = rightPanelTime.endTime;
    } else {
      // 年、月、日视图使用time参数
      params.time = rightPanelTime.startTime;
    }
    
    // 处理区域参数
    if (currentMapState.regionCode === '5101') {
      // 成都，这两个参数不传
      params.districtCode = undefined;
      params.streetCode = undefined;
    } else if (currentMapState.regionCode.length === 6) {
      // 区县级别
      params.districtCode = currentMapState.regionCode;
    } else if (currentMapState.regionCode.length === 9) {
      // 街道级别
      params.districtCode = currentMapState.regionCode.substring(0, 6);
      params.streetCode = currentMapState.regionCode;
    }
    
    return params;
  }, [mapStateRef, dateType, translateDateType, dataTypeKey, pageId]);
  
  // 在地图状态变化时加载数据
  useEffect(() => {
    const params = buildApiParams();
    
    // 如果没有必要的参数，不发送请求
    if (!params) {
      console.log('缺少必要的日期参数，暂不加载案件情况数据');
      return;
    }
    
    console.log(`加载${pageId}页面案件情况数据，参数:`, params);
    disposeStatsApi.callApi(params);
  }, [mapState.regionCode, mapState.rightPanelTime, mapState.pageTimeSettings, buildApiParams, disposeStatsApi, pageId]);

  return (
    <div className={styles.container}>
      <div className={styles.row}>
        <StatCard 
          value={statsData.caseCount}
          label="立案"
          unit="件"
          icon={cardBg1}
          iconSize={{ width: 45.84, height: 52.02 }}
          className={styles.smallCard}
        />
        
        <StatCard 
          value={statsData.processingCount}
          label="处置中"
          unit="件"
          icon={cardBg2}
          iconSize={{ width: 59, height: 59 }}
          valueStyle={{ background: 'linear-gradient(180.00deg, rgb(170, 255, 246),rgb(10, 192, 167))'}}
          className={styles.smallCard}
        />

        <StatCard 
          value={statsData.overtimeCount}
          label="超时"
          unit="件"
          icon={cardBg3}
          iconSize={{ width: 52, height: 52 }}
          valueStyle={{ background: 'rgb(255, 79, 79)'}}
          className={styles.smallCard}
        />
      </div>

      <div className={styles.row}>
        <StatCard 
          value={statsData.completedCount}
          label="已办结"
          unit="件"
          icon={cardBg4}
          iconSize={{ width: 48, height: 48 }}
          className={styles.largeCard}
          direction="horizontal"
        />
        
        <StatCard 
          value={statsData.completionRate}
          label="办结率"
          unit="%"
          icon={cardBg5}
          iconSize={{ width: 49, height: 49 }}
          className={styles.largeCard}
          direction="horizontal"
          valueDecimals={2}
        />
      </div>
    </div>
  );
};

export default StatisticsCards; 