import React, { useEffect, useState, useCallback, useRef } from 'react';
import ModuleTitleWithTabs from '@/pages/Home_v_2504/components/common/ModuleTitleWithTabs';
import ChartWithLegend, { ChartDataItem } from '@/components/V2504/ChartWithLegend';
import styles from './index.less';
import { useDataType, useMapState } from '@/pages/Home_v_2504/components/MapStateContext';
import { getSourceSystemRank } from '@/services/CityProblem';
import { formatDateTime } from '@/pages/Home_v_2504/hooks/useApiControl';
import useLatestValue from '@/pages/Home_v_2504/hooks/useLatestValue';
import classNames from 'classnames';
import usePageAwareApi from '@/pages/Home_v_2504/hooks/usePageAwareApi';
import { INDUSTRY_PAGE_IDS } from '@/constants/dataTypes';

interface ProgramTypeProps {
  dateType?: string;
  dateRange?: { startTime: string; endTime: string };
  dataTypeKey?: string;
  isThinLayout?: boolean;
  pageId?: string;
}

const ProgramType: React.FC<ProgramTypeProps> = ({ 
  dateType,
  dateRange,
  dataTypeKey = '行政处罚',
  isThinLayout = false,
  pageId = INDUSTRY_PAGE_IDS.LAW_ENFORCEMENT_PUNISHMENT, 
}) => {
  // 地图状态
  const { mapState } = useMapState();
  const mapStateRef = useLatestValue(mapState);
  
  // 统计数据
  const [data, setData] = useState<ChartDataItem[]>([]);
  
  // 图表颜色
  const colors = ['rgb(49, 198, 250)', 'rgb(255, 227, 53)', 'rgb(71, 223, 155)', 'rgb(170, 145, 255)', 'rgb(97, 141, 255)', 'rgb(53, 193, 247)', 'rgb(152, 141, 252)', 'rgb(199, 195, 89)'];
  
  // 转换日期类型为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'; // 默认月视图
    }
  }, []);
  
  // 构建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)
    };
    
    // 处理日期参数
    if (effectiveType === 'range') {
      params.customizeStart = formatDateTime(rightPanelTime.startTime);
      params.customizeEnd = formatDateTime(rightPanelTime.endTime, true);
    } else {
      // 年、月、日视图使用time参数
      params.time = formatDateTime(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;
    }
    
    // 使用传入的dataTypeKey获取对应的subTypeCode
    params.subTypeCode = useDataType(dataTypeKey);
    
    return params;
  }, [mapStateRef, dateType, translateDateType, dataTypeKey, pageId]);
  
  // 使用usePageAwareApi管理问题来源API调用
  const sourceSystemRankApi = usePageAwareApi({
    apiFunction: async (params: any) => {
      console.log('发起问题来源请求，参数:', params);
      const response = await getSourceSystemRank(params);
      
      if (response.code === 200 && response.data) {
        return response.data;
      }
      
      throw new Error('获取问题来源数据失败');
    },
    onSuccess: (data: any) => {
      if (!data || !Array.isArray(data) || data.length === 0) {
        let useMockData = true;
        if (useMockData) {
          data = [
            { name: '市城运平台', value: 1625, percent: '32.53' },
            { name: '12345市民投诉', value: 1400, percent: '30.53' },
            { name: '数字城管巡查上报', value: 1322, percent: '20.8' },
            { name: '青羊区', value: 186, percent: '5.6' },
            { name: '双流区', value: 152, percent: '4.9' },
          ];
          console.log('使用模拟问题来源数据');
        }else{
          setData([]);
          return;
        }
      }
      
      // 转换接口返回的数据格式为图表需要的格式
      const formattedData = data.map((item: any) => ({
        name: item.name || '未知来源',
        value: parseInt(item.value) || 0,
        percentage: parseFloat(item.percent) || 0
      }));
      
      console.log('问题来源数据成功:', formattedData);
      setData(formattedData);
    },
    onError: (error: any) => {
      console.error('获取问题来源数据出错:', error);
      setData([]);
    },
    apiName: '问题来源',
    debounceTime: 300,
    cacheTime: 5000, // 缓存5秒，避免频繁刷新时重复请求
    enableDebug: false,
    pageId: pageId, // 添加页面ID以启用页面感知
  });

  // 在地图状态变化时加载数据
  useEffect(() => {
    const params = buildApiParams();
    
    // 如果没有必要的参数，不发送请求
    if (!params) {
      console.log('缺少必要的日期参数，暂不加载问题来源数据');
      return;
    }
    
    console.log(`加载${pageId}页面-案件来源 数据，参数:`, params);
    sourceSystemRankApi.callApi(params);
    
  }, [mapState.regionCode, mapState.rightPanelTime, mapState.pageTimeSettings, buildApiParams, sourceSystemRankApi, pageId]);

  return (
    <div className={styles.container}>
      <ModuleTitleWithTabs title="案件来源" />
      <div className={classNames(styles.content)}>
        <ChartWithLegend 
          data={data}
          colors={colors}
          chartWidth={160}
          chartHeight={160}
          unit="件"
          showPercentage={true}
          showCount={true}
          isThinLayout={false}
          legendHeight={150}
          fullCountOfLegend={3}   
        />
      </div>
    </div>
  );
};

export default ProgramType; 