import React, { useCallback, useState, useEffect, useRef } from 'react';
import PanelTitle from '@/pages/Home_v_2504/components/common/PanelTitle';
import DateSelector from '@/components/V2504/DateSelector';
import HighFrequency from './components/HighFrequency';
import ProblemTrend from './components/ProblemTrend';
import CompletionRate from './components/CompletionRate';
import HighFrequencyArea from './components/HighFrequencyArea';
import SourceSection from './components/SourceSection';
import StatisticsCards from './components/StatisticsCards';
import styles from './index.less';
import { Card, Typography } from 'antd';
import { useMapState } from '@/pages/Home_v_2504/components/MapStateContext';

const { Title } = Typography;

// 导入图标
import statusCardIcon from '@/assets/images/V-2504/main-complaint.png';
import HighFrequencyType from './components/HighFrequencyType';

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

interface Statistic {
  caseCount: number;
  processingCount: number;
  overtimeCount: number;
  completedCount: number;
  completionRate: number;
}

interface AreaData {
  name: string;
  percentage: number;
  count: number;
}

// 添加组件Props接口
interface RightContentProps {
  // 数据类型键名，用于获取正确的dataType
  dataTypeKey?: string;
  // 标题
  title?: string;
  // 是否使用高频类型组件
  useHighFrequencyType?: boolean;
  // 是否使用瘦脸组件
  isThinLayout?: boolean;
  // 时间选项配置
  timeOptions?: Array<'day' | 'month' | 'year' | 'range' | 'yesterday' | 'lastMonth'>;
  // 页面ID，用于区分不同页面的时间设置
  pageId?: string;
}

const RightContent: React.FC<RightContentProps> = ({ 
  dataTypeKey = '餐饮油烟事件',
  title = '餐饮油烟事件',
  useHighFrequencyType = false,
  isThinLayout = false,
  timeOptions = ['day', 'month', 'year', 'range'],
  pageId = 'restaurantOil',
}) => {
  // 获取地图状态
  const { mapState, updateTimeRange } = useMapState();
  
  // 状态
  const [dateType, setDateType] = useState<string>('month');
  const [dateRange, setDateRange] = useState<{ startTime: string; endTime: string }>({
    startTime: '',
    endTime: '',
  });
  // const [statistics, setStatistics] = useState<Statistic>({
  //   caseCount: 1000,
  //   processingCount: 862,
  //   overtimeCount: 126,
  //   completedCount: 2633,
  //   completionRate: 89.72,
  // });
  // const [sourceData, setSourceData] = useState<{ name: string; value: number; percentage: number }[]>([
  //   { name: '市城运平台', value: 1625, percentage: 32.53 },
  //   { name: '12345市民投诉', value: 1589, percentage: 30.22 },
  //   { name: '数字城管巡查上报', value: 1233, percentage: 30.22 },
  //   { name: '其他', value: 1233, percentage: 30.22 },
  // ]);
  // const [completionRateData, setCompletionRateData] = useState<AreaData[]>([
  //   { name: '锦江区', percentage: 87.2, count: 0 },
  //   { name: '金牛区', percentage: 73.5, count: 0 },
  //   { name: '成华区', percentage: 60.8, count: 0 },
  //   { name: '青羊区', percentage: 55.6, count: 0 },
  //   { name: '双流区', percentage: 42.9, count: 0 },
  //   { name: '武侯区', percentage: 35.6, count: 0 },
  //   { name: '龙泉驿区', percentage: 30.5, count: 0 },
  //   { name: '温江区', percentage: 25.4, count: 0 },
  //   { name: '新都区', percentage: 20.3, count: 0 },
  //   { name: '郫都区', percentage: 15.2, count: 0 },
  //   { name: '都江堰市', percentage: 10.1, count: 0 },
  // ]);
  // const [highFrequencyData, setHighFrequencyData] = useState<AreaData[]>([
  //   { name: '锦江区', percentage: 97.2, count: 456 },
  //   { name: '金牛区', percentage: 83.5, count: 400 },
  //   { name: '成华区', percentage: 70.8, count: 322 },
  //   { name: '青羊区', percentage: 65.6, count: 186 },
  //   { name: '双流区', percentage: 12.9, count: 152 },
  //   { name: '武侯区', percentage: 10.6, count: 122 },
  //   { name: '龙泉驿区', percentage: 10.5, count: 121 },
  //   { name: '温江区', percentage: 10.4, count: 120 },
  //   { name: '新都区', percentage: 10.3, count: 119 },
  //   { name: '郫都区', percentage: 10.2, count: 118 },
  //   { name: '都江堰市', percentage: 10.1, count: 117 },
  // ]);

  // 跟踪前一次的日期值，避免重复更新
  const prevDateRef = useRef({
    type: 'month',
    startTime: '',
    endTime: ''
  });

  // 根据日期类型和范围获取数据
  // const loadData = useCallback(() => {
  //   // 这里可以根据dateType和dateRange从接口获取对应的数据
  //   console.log('获取数据:', dateType, dateRange);
    
  //   // 更新统计数据
  //   if (dateType === 'day') {
  //     setStatistics({
  //       caseCount: 562,
  //       processingCount: 314,
  //       overtimeCount: 46,
  //       completedCount: 862,
  //       completionRate: 94.2,
  //     });
  //   } else if (dateType === 'year') {
  //     setStatistics({
  //       caseCount: 12500,
  //       processingCount: 1024,
  //       overtimeCount: 236,
  //       completedCount: 11240,
  //       completionRate: 91.6,
  //     });
  //   } else if (dateType === 'range') {
  //     setStatistics({
  //       caseCount: 5620,
  //       processingCount: 862,
  //       overtimeCount: 156,
  //       completedCount: 4602,
  //       completionRate: 87.5,
  //     });
  //   } else {
  //     // 月视图的默认数据
  //     setStatistics({
  //       caseCount: 1000,
  //       processingCount: 862,
  //       overtimeCount: 126,
  //       completedCount: 2633,
  //       completionRate: 89.72,
  //     });
  //   }
    
  //   // 此处可以调用API获取其他数据
  //   // fetchSourceData(dateType, dateRange);
  //   // fetchCompletionRateData(dateType, dateRange);
  //   // fetchHighFrequencyData(dateType, dateRange);
  // }, [dateType, dateRange]);

  // 日期变化时加载数据
  // useEffect(() => {
  //   if (!dateRange.startTime || !dateRange.endTime) {
  //     return;
  //   }
    
  //   // 只有在日期真的变化时才加载数据
  //   loadData();
  // }, [dateType, dateRange, loadData]);

  // 处理日期变化
  const handleDateChange = useCallback((params: { type: string; startTime: string; endTime: string }) => {
    console.log('Date changed: RightContent!!', params);
    
    // 检查日期是否真的变化了
    const prevValues = prevDateRef.current;
    if (prevValues.type === params.type && 
        prevValues.startTime === params.startTime && 
        prevValues.endTime === params.endTime) {
      console.log('忽略重复的日期变更事件');
      return;
    }
    
    // 更新前一次值的引用
    prevDateRef.current = {
      type: params.type,
      startTime: params.startTime,
      endTime: params.endTime
    };
    
    // 更新状态
    setDateType(params.type);
    setDateRange({
      startTime: params.startTime,
      endTime: params.endTime,
    });
    
    // 通知地图状态上下文日期变化
    updateTimeRange('right', params.type, params.startTime, params.endTime);
  }, [updateTimeRange]);

  return (
    <div className={styles.container}>
      {/* 标题 */}
      <div className={styles.header}>
        <PanelTitle title={title} />
        <DateSelector
          onChange={handleDateChange}
          defaultType="month"
          panelType="right"
          pageId={pageId}
          timeOptions={timeOptions}
        />
      </div>

      {/* 高发时段和统计卡片区域 */}
      <div className={`${styles.topSection} ${isThinLayout ? styles.topSection_thinLayout : ''}`}>
        <HighFrequency 
          dataTypeKey={dataTypeKey}
          pageId={pageId}
        />
        
        <StatisticsCards 
          dataTypeKey={dataTypeKey}
          pageId={pageId}
        />
      </div>

      {/* 中间内容 */}
      <div className={`${styles.middleContent} ${isThinLayout ? styles.middleContent_thinLayout : ''}`}>
        {/* 问题来源 */}
        <SourceSection 
          dataTypeKey={dataTypeKey}
          isThinLayout={isThinLayout}
          pageId={pageId}
        />
        
        {/* 问题趋势 */}
        {/* <div className={styles.trendSection}> */}
          <ProblemTrend
            dateType={dateType}
            dateRange={dateRange}
            dataTypeKey={dataTypeKey}
            isThinLayout={isThinLayout}
            pageId={pageId}
          />
        {/* </div> */}
      </div>

      {/* 底部内容 */}
      <div className={`${styles.bottomContent} ${isThinLayout ? styles.bottomContent_thinLayout : ''}`}>
        {!useHighFrequencyType ? (
        /* 办结率 */
        <CompletionRate 
          dateType={dateType}
          dateRange={dateRange}
          dataTypeKey={dataTypeKey}
          pageId={pageId}
        />
        ) : (
          <HighFrequencyType
            dateType={dateType}
            dateRange={dateRange}
            dataTypeKey={dataTypeKey}
            pageId={pageId}
          />
        )}
        {/* 高发区域 */}
        <HighFrequencyArea 
          dateType={dateType}
          dateRange={dateRange}
          dataTypeKey={dataTypeKey}
          isThinLayout={isThinLayout}
          pageId={pageId}
        />
      </div>
    </div>
  );
};

export default RightContent; 