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 useApiControl, { formatDateTime } from '@/pages/Home_v_2504/hooks/useApiControl';
import useLatestValue from '@/pages/Home_v_2504/hooks/useLatestValue';
import classNames from 'classnames';

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

const BridgeMaintenanceLevel: React.FC<CarTypeProps> = ({ 
  dateType,
  dateRange,
  dataTypeKey = '市政设施',
  isThinLayout = true,
}) => {
  // 地图状态
  const { mapState } = useMapState();
  const mapStateRef = useLatestValue(mapState);
  
  // 统计数据
  const [data, setData] = useState<ChartDataItem[]>([]);
  
  // 图表颜色
  const colors = ['rgb(53, 193, 247)', 'rgb(152, 141, 252)', 'rgb(199, 195, 89)', 'rgb(71, 223, 155)', 'rgb(97, 141, 255)'];
  
  // 转换日期类型为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;
    }
    
    // 使用当前时间类型，如果不存在则使用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);
    }
    
    // 处理区域参数
    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]);
  
  // 使用useApiControl管理问题来源API调用
  const sourceSystemRankApi = useApiControl({
    apiFunction: async (params) => {
      console.log('发起问题来源请求，参数:', params);
      const response = await getSourceSystemRank(params);
      
      if (response.code === 200 && response.data) {
        return response.data;
      }
      
      throw new Error('获取问题来源数据失败');
    },
    onSuccess: (data) => {
      if (!data || !Array.isArray(data) || data.length === 0) {
        let useMockData = true;
        if (useMockData) {
          data = [
            { name: 'I等', value: 456, percent: '97.2' },
            { name: 'II等', value: 400, percent: '83.5' },
            { name: 'III等', value: 322, percent: '70.8' },
            // { name: '青羊区', value: 186, percent: '65.6' },
            // { name: '双流区', value: 152, percent: '12.9' },
          ];
          // console.log('使用模拟问题来源数据');
        }else{
          setData([]);
          return;
        }
      }

      // 如果接口返回数据都是0，生成模拟数据
      // if (data.every(item => parseInt(item.value) === 0 && parseFloat(item.percent) === 0)) {
        
      // }
      
      // 转换接口返回的数据格式为图表需要的格式
      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) => {
      console.error('获取问题来源数据出错:', error);
      setData([]);
    },
    apiName: '问题来源',
    debounceTime: 300,
    cacheTime: 5000 // 缓存5秒，避免频繁刷新时重复请求
  });

  // 在地图状态变化时加载数据
  useEffect(() => {
    const params = buildApiParams();
    
    // 如果没有必要的参数，不发送请求
    if (!params) {
      console.log('缺少必要的日期参数，不加载问题来源数据');
      return;
    }
    
    console.log('加载桥梁养护等级数据，参数:', params);
    sourceSystemRankApi.callApi(params);
    
  }, [mapState.regionCode, mapState.rightPanelTime, buildApiParams, sourceSystemRankApi]);

  const totalValue = data.reduce((sum, item) => sum + (item.value || 0), 0);

  return (
    <div className={styles.container}>
      <ModuleTitleWithTabs title="桥梁养护等级" />
      <div className={classNames(styles.content)}>
        <ChartWithLegend 
          data={data}
          colors={colors}
          chartWidth={200}
          chartHeight={200}
          unit="件"
          showPercentage={true}
          showCount={true}
          isThinLayout={isThinLayout}
          legendHeight={200}
          fullCountOfLegend={3}
          showLabel={true}
          labelFormatter={['{a|1524}{b|条}',`{c|总共}`].join('\n')}
          labelFormatterParams = {{
            a: {
              fontFamily: 'D-DIN',
              fontSize: 24,
              fontWeight: 700,
              color: 'rgb(188, 206, 233)',
              lineHeight: 36,
            },
            b: {
              fontFamily: '微软雅黑',
              fontSize: 16,
              fontWeight: 400,
              color: '#BCCEE9',
              padding: [8, 8, 0, 0]
            },
            c: {
              fontFamily: '微软雅黑',
              fontSize: 16,
              fontWeight: 400,
              color: '#BCCEE9',
            }
          }}
          isShortLegendItem={true}
        />
      </div>
    </div>
  );
};

export default BridgeMaintenanceLevel; 