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

// 类型定义
export interface HighFrequencyTypeProps {
  dateType?: string;
  dateRange?: { startTime: string; endTime: string };
  dataTypeKey?: string;
}

// 区域类型定义
export type AreaType = 'all' | 'urban' | 'central' | 'county';

// 区域级别定义
export enum RegionLevelEnum {
  CITY = '1',      // 市级
  DISTRICT = '2',  // 区县级
  STREET = '3',    // 街道级
  GRID = '4',      // 网格级
}

// 区域编码生成函数
const getRegionCodes = (areaType: AreaType, regionCode: string) => {
  // 默认所有区域
  if (areaType === 'all') {
    return regionCode.length > 4 
      ? regionCode 
      : regionCode === '5101' 
        ? '510104,510105,510106,510107,510108,510112,510113,510114,510115,510116,510117,510121,510129,510131,510132,510181,510182,510183,510184,510185'
        : '';
  }
  
  // 城市新区
  if (areaType === 'urban') {
    return '510112,510113,510114,510115,510116,510117';
  }
  
  // 中心城区
  if (areaType === 'central') {
    return '510104,510105,510106,510107,510108';
  }
  
  // 县市新城
  if (areaType === 'county') {
    return '510121,510129,510131,510132,510181,510182,510183,510184,510185';
  }
  
  return '';
};

const HighFrequencyType: React.FC<HighFrequencyTypeProps> = ({ 
  dateType,
  dateRange,
  dataTypeKey = '餐饮油烟事件'
}) => {
  // 地图状态
  const { mapState } = useMapState();
  const mapStateRef = useLatestValue(mapState);
  
  // 当前选中的区域类型
  const [currentTab, setCurrentTab] = useState<AreaType>('all');
  const currentTabRef = useLatestValue(currentTab);
  
  // 高频区域数据
  const [data, setData] = useState<AreaBarItem[]>([]);

  // 转换日期类型为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'; // 默认月视图
    }
  }, []);

  // 处理Tab切换
  const handleTabChange = (tab: string) => {
    setCurrentTab(tab as AreaType);
  };

  // 构建API请求参数
  const buildApiParams = useCallback(() => {
    const currentMapState = mapStateRef.current;
    
    // 如果没有必要的时间参数，返回null表示不应该发起请求
    if (!currentMapState.rightPanelTime?.startTime || !currentMapState.rightPanelTime?.endTime) {
      return null;
    }
    
    // 使用当前时间类型，如果不存在则使用props或默认值
    const effectiveType = currentMapState.rightPanelTime.type || dateType || 'month';
    
    // 基础参数对象
    const params: any = {
      type: translateDateType(effectiveType)
    };
    
    // 处理日期参数
    if (effectiveType === 'range') {
      params.customizeStart = formatDateTime(currentMapState.rightPanelTime.startTime);
      params.customizeEnd = formatDateTime(currentMapState.rightPanelTime.endTime, true);
    } else {
      // 年、月、日视图使用time参数
      params.time = formatDateTime(currentMapState.rightPanelTime.startTime);
    }
    
    // 获取区域编码列表
    const districtCodeList = getRegionCodes(currentTabRef.current, currentMapState.regionCode);
    if (districtCodeList) {
      params.districtCodeList = districtCodeList;
    }
    
    // 处理区域参数
    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;
    }
    
    // 使用传入的dataTypeKey获取对应的subTypeCode
    params.subTypeCode = useDataType(dataTypeKey);
    
    return params;
  }, [mapStateRef, currentTabRef, dateType, translateDateType, dataTypeKey]);

  // 使用useApiControl管理高频区域API调用
  const highFrequencyApi = useApiControl({
    apiFunction: async (params) => {
      console.log('发起高频区域请求，参数:', params);
      const response = await getDistrictHighFrequencyArea(params);
      
      if (response.code === 200 && response.data) {
        return response.data;
      }
      
      throw new Error('获取高频区域数据失败');
    },
    onSuccess: (data) => {
      if (!data || !Array.isArray(data) || data.length === 0) {
        setData([]);
        return;
      }
      
      // 转换接口返回的数据格式为图表需要的格式
      const formattedData = data.map((item: any) => ({
        name: item.name,
        percentage: parseFloat(item.percent) || 0,
        count: parseInt(item.value) || 0
      }));
      
      console.log('高频区域数据成功:');
      setData(formattedData);
    },
    onError: (error) => {
      console.error('获取高频区域数据出错:', error);
      setData([]);
    },
    apiName: '高频区域',
    debounceTime: 300,
    cacheTime: 5000 // 缓存5秒，避免频繁刷新时重复请求
  });

  // 使用 useMemo 跟踪 rightPanelTime 的实际变化
  const memoizedRightPanelTime = useMemo(() => {
    return {
      type: mapState.rightPanelTime.type,
      startTime: mapState.rightPanelTime.startTime,
      endTime: mapState.rightPanelTime.endTime
    };
  }, [
    mapState.rightPanelTime.type,
    mapState.rightPanelTime.startTime, 
    mapState.rightPanelTime.endTime
  ]);

  // 跟踪上一次的API参数，避免重复调用
  const prevApiParamsRef = useRef<string>('');

  // 在地图状态变化和Tab变化时加载数据
  useEffect(() => {
    const params = buildApiParams();
    
    // 如果没有必要的参数，不发送请求
    if (!params) {
      console.log('缺少必要的日期参数，不加载高频区域数据');
      return;
    }
    
    // 参数签名，用于比较参数是否有实际变化
    const paramsSignature = JSON.stringify(params);
    
    // 检查参数是否真正变化，防止重复调用
    if (paramsSignature === prevApiParamsRef.current) {
      console.log('高频区域参数未变化，跳过重复加载');
      return;
    }
    
    console.log('加载高频区域数据，参数:', params);
    highFrequencyApi.callApi(params);
    
    // 更新上一次参数签名
    prevApiParamsRef.current = paramsSignature;
    
  }, [mapState.regionCode, memoizedRightPanelTime, currentTab, buildApiParams, highFrequencyApi]);

  return (
    <div className={styles.container}>
      <ModuleTitleWithTabs 
        title="高发类型"
      />
      <div className={styles.content}>
        <AreaBarList 
          data={data} 
          height={290}
          showCount={true}
          showPercentage={true}
          isThinProgress={true}
        />
      </div>
    </div>
  );
};

export default HighFrequencyType; 