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';
import SmoothLineChart from '@/components/V2504/SmoothLineChart';

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

interface TrendData {
  time: string;
  value: number;
}

const YesterdayPowerTrend: React.FC<YesterdayPowerTrendProps> = ({ 
  dateType,
  dateRange,
  dataTypeKey = '景观照明',
  isThinLayout = true,
}) => {
  // 地图状态
  const { mapState } = useMapState();
  const mapStateRef = useLatestValue(mapState);
  
  // 统计数据
  const [data, setData] = useState<TrendData[]>([]);
  
  // 图表颜色
  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 = [
            { time: '00:00:00', value: 145 },
            { time: '01:00:00', value: 160 },
            { time: '02:00:00', value: 155 },
            { time: '03:00:00', value: 165 },
            { time: '04:00:00', value: 175 },
            { time: '05:00:00', value: 185 },
            { time: '06:00:00', value: 180 },
            { time: '07:00:00', value: 190 },
            { time: '08:00:00', value: 195 },
            { time: '09:00:00', value: 205 },
            { time: '10:00:00', value: 210 },
            { time: '11:00:00', value: 215 },
            { time: '12:00:00', value: 220 },
            { time: '13:00:00', value: 210 },
            { time: '14:00:00', value: 205 },
            { time: '15:00:00', value: 195 },
            { time: '16:00:00', value: 200 },
            { time: '17:00:00', value: 205 },
            { time: '18:00:00', value: 210 },
            { time: '19:00:00', value: 215 },
            { time: '20:00:00', value: 225 },
            { time: '21:00:00', value: 230 },
            { time: '22:00:00', value: 235 },
            { time: '23:00:00', value: 240 },
          ];
        }else{
          setData([]);
          return;
        }
      }
      // console.log('使用模拟问题来源数据');

      // 如果接口返回数据都是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(data);
    },
    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.chartWrapper)}>
        <SmoothLineChart           
          data={data}
          unitText="单位：kw"
          lineColor="rgb(32, 214, 201)"
          lineColorStop1="rgba(32, 214, 201, 0)"
          lineColorStop2="rgba(32, 214, 201, 0.36)"
          style={{ height: '240px', width: '100%' }}
        />        
      </div>
    </div>
  );
};

export default YesterdayPowerTrend; 