import React, { useState, useEffect, useCallback, useRef, useMemo } from 'react';
import ModuleTitleWithTabs from '@/pages/Home_v_2504/components/common/ModuleTitleWithTabs';
import SmoothLineChart from '@/components/V2504/SmoothLineChart';
import styles from './index.less';
import { useDataType, useMapState } from '@/pages/Home_v_2504/components/MapStateContext';
import { getEventTrends } 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 { INDUSTRY_PAGE_IDS } from '@/constants/dataTypes';

// 类型定义
interface PunishmentTrendProps {
  dateType?: string;
  dateRange?: { startTime: string; endTime: string };
  dataTypeKey?: string;
  isThinLayout?: boolean;
  pageId?: string; // 新增页面ID参数
}

const PunishmentTrend: React.FC<PunishmentTrendProps> = ({ 
  dateType, 
  dateRange, 
  dataTypeKey = '行政处罚',
  isThinLayout = false,
  pageId = INDUSTRY_PAGE_IDS.LAW_ENFORCEMENT_PUNISHMENT, // 默认为lawEnforcementPunishment
}) => {
  // 地图状态
  const { mapState } = useMapState();
  const mapStateRef = useLatestValue(mapState);
  
  // 图表数据
  const [data, setData] = useState<{ time: string; value: number }[]>([]);
  
  // 转换日期类型为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'; // 默认月视图
    }
  }, []);
  
  // 转换时间格式 - 参考LeftContent中的translateTrendTime函数
  const translateTrendTime = useCallback((inputDate: string | number) => {
    if (typeof inputDate === 'string') {
      // 处理类似'2025-11'的格式
      if (inputDate.includes('-') && inputDate.length === 7) {
        const month = parseInt(inputDate.substring(5, 7));
        return `${month}月`;
      }
      // 处理类似'20250425'的格式
      // if (inputDate.length === 8) {
      //   const month = parseInt(inputDate.substring(4, 6));
      //   const day = parseInt(inputDate.substring(6, 8));
      //   return `${month}月${day}日`;
      // }
      // 处理YYYY-MM-DD格式
      if (inputDate.includes('-') && inputDate.length === 10) {
        const dateParts = inputDate.split('-');
        if (dateParts.length >= 3) {
          const month = parseInt(dateParts[1]);
          const day = parseInt(dateParts[2]);
          return `${month}月${day}日`;
        }
      }
      // 处理类似"03"的格式
      if (inputDate.length === 2) {
        if (inputDate === '23') {
          return '23:59:59';
        }
        return `${inputDate.padStart(2, '0')}:00:00`;
      }
      // console.log('inputDate:', inputDate);
      return inputDate.substring(0, 10);
    }
    // 处理number类型
    if (typeof inputDate === 'number') {
      if (inputDate === 23) {
        return '23:59:59';
      }
      return `${inputDate.toString().padStart(2, '0')}:00`;
    }
    return inputDate;
  }, []);
  
  // 构建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 eventTrendsApi = usePageAwareApi({
    apiFunction: async (params: any) => {
      console.log('发起问题趋势请求，参数:', params);
      const response = await getEventTrends(params);
      
      if (response.code === 200 && response.data) {
        return response.data;
      }
      
      throw new Error('获取问题趋势数据失败');
    },
    onSuccess: (data: any) => {
      if (!data || !Array.isArray(data)) {
        setData([]);
        return;
      }
      console.log('onSuccess:');

      let isUseMockData = true;
      if (isUseMockData) {
        setData(mockData);
        return;
      }

      const isSupplementData = false;
      // 如果是月数据，补充到月底  '2025-05-06'
      if (data[0].name.includes('-') && data[0].name.length === 10 && isSupplementData) {
        // 获取当前日期
        const today = new Date();
        const lastDay = new Date(today.getFullYear(), today.getMonth() + 1, 1);
        // console.log('lastDay:', lastDay);
        
        // 生成完整日期范围
        const fullData = [...data]; // 先复制已有数据
        
        // 从明天开始补充数据
        for (let d = new Date(today); d <= lastDay; d.setDate(d.getDate() + 1)) {
          // 跳过今天及之前的日期
          if (d <= today) continue;
          
          const dateStr = d.toISOString().slice(0, 10).replace(/-/g, '-');
          fullData.push({
            name: dateStr,
            value: '0'
          });
        }
        data = fullData;
        // console.log('补充到月底的数据:', data);
      }

      // 如果是小时数据，补充到23点
      if (data[0].name.length === 2 && isSupplementData) {
        // 获取当前小时
        const currentHour = new Date().getHours();
        // 生成完整小时范围
        const fullData = [...data]; // 先复制已有数据
        
        // 从下一小时开始补充数据
        for (let h = currentHour + 1; h <= 23; h++) {
          const hourStr = h.toString().padStart(2, '0');
          fullData.push({
            name: hourStr,
            value: '0'
          });
        }
        data = fullData;
      }
      
      // 转换接口返回的数据格式为图表需要的格式
      const formattedData = data.map((item: any) => ({
        time: translateTrendTime(item.name),
        value: parseInt(item.value) || 0
      }));
      
      console.log('问题趋势数据成功:');
      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);
    eventTrendsApi.callApi(params);
    
  }, [mapState.regionCode, mapState.rightPanelTime, mapState.pageTimeSettings, buildApiParams, eventTrendsApi, pageId]);

  const chartStyle = useMemo(() => ({
    height: isThinLayout ? '278px' : '178px',
    width: '100%'
  }), [isThinLayout]);

  
  // Mock data for the chart
  const mockData: { time: string; value: number }[] = [
    { 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: 310 },
    { time: '11:00:00', value: 425 },
    { time: '12:00:00', value: 330 },
    { time: '13:00:00', value: 320 },
    { time: '14:00:00', value: 265 },
    { time: '15:00:00', value: 255 },
    { time: '16:00:00', value: 240 },
    { time: '17:00:00', value: 235 },
    { 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 },
  ];


  return (
    <div className={styles.container}>
      <ModuleTitleWithTabs 
        title="处罚趋势"
      />
      <div className={styles.chartWrapper}>
        <SmoothLineChart
          data={data}
          unitText="单位：件"
          // lineColor="rgb(32, 214, 201)"
          // lineColorStop1="rgba(32, 214, 201, 0)"
          // lineColorStop2="rgba(32, 214, 201, 0.36)"
          lineColor="rgb(136, 238, 248)"
          lineColorStop1="rgba(136, 238, 248, 0.36)"
          lineColorStop2="rgba(136, 238, 248, 0)"
          style={{ height: '190px', width: '100%' }}
        />
      </div>
    </div>
  );
};

export default PunishmentTrend; 