import React, { useEffect, useState } from 'react';
import { Flex, Popover } from 'antd';
import dayjs from 'dayjs';
import services from '@/services';
import styles from './index.less';
import LineCharts from './LineCharts'
import quoteIcon from '@/assets/images/newMain/quote.png';

const HighIncidenceTime: React.FC = () => {
  const [statisticTotal, setStatisticTotal] = useState<any>([]);
  const [statisticTotalForCharts, setStatisticTotalForCharts] = useState<any>([]);

  const getDate = () => {
    const oneMonthAgo = dayjs().subtract(1, 'month');
    return { 
      startTime: oneMonthAgo.format('YYYY-MM-DD'), 
      endTime: dayjs().format('YYYY-MM-DD') 
    };
  };

  const getData = async () => {
    const resp = await services.DataBase.getQzGfData({
      typeCode: "quhs-gfsj",
      params: {
        ...getDate()
      }
    });
    if (resp.code === 200) {
      const data = [resp.data?.all, ...resp.data?.data];
      // console.log(data)
      setStatisticTotal(data);

      // 处理数据,确保每个时间点都有数据,并按自然顺序排序
      const processData = (rawData: any) => {
        // 生成0-23的完整时间序列
        const fullTimeData = Array.from({ length: 24 }, (_, i) => ({
          times: i,
          num: 0
        }));
        
        // 用实际数据填充
        rawData.forEach((item: any) => {
          const index = item.times;
          if (index >= 0 && index < 24) {
            fullTimeData[index].num = item.num;
          }
        });
        
        return fullTimeData;
      };
      // setStatisticTotalForCharts(data);
      // setStatisticTotalForCharts(processData(data));
      
      const processedData = [
        { ...resp.data?.all, data: processData(resp.data?.all?.data) },
        ...resp.data?.data.map((item: any) => ({
          ...item,
          data: processData(item.data)
        }))
      ];
      // console.log(processedData)
      
      // setStatisticTotal(resp.data?.all?.data);
      setStatisticTotalForCharts(processedData);
    }
  };

  useEffect(() => {
    getData();
  }, []);

  const getSummaryText = () => {
    // 找到"整体"数据
    const overallData = statisticTotal.find((item: any) => item.name === "整体");
    
    // 获取整体数据中前三高发时段
    const overallTop3Times = overallData?.data
      .sort((a: any, b: any) => b.num - a.num)
      .slice(0, 3)
      .map((item: any) => item.times + '点')
      .join('、');

    // 获取除"整体"外数量最多的前三类型
    const top3Types = statisticTotal
      .filter((item: any) => item.name !== "整体")
      .sort((a: any, b: any) => b.num - a.num)
      .slice(0, 3);

    // 获取每个类型的前三高发时段
    const typeTimesSummary = top3Types.map((type: any) => {
      const top3Times = type.data
        .sort((a: any, b: any) => b.num - a.num)
        .slice(0, 3)
        .map((item: any) => item.times + '点')
        .join('、');
        
      return {
        name: type.name,
        times: top3Times
      };
    });

    return (
      <div className={styles.summaryContent}>
        <div className={styles.title}>高发时间总结</div>
        <div className={styles.content}>
          <p>近一个月投诉主要集中在 <span className={styles.highlight}>{overallTop3Times}</span>。</p>
          <p>其中市民关注和反映问题较多问题：</p>
          {typeTimesSummary.map((item: any, index: any) => (
            <p key={index}>
              {item.name}集中在 <span className={styles.highlight}>{item.times}</span>。
            </p>
          ))}
        </div>
      </div>
    );
  };

  return (
    <div className={styles.container}>
      <div className={styles.header}>
        <span className={styles.title}>高发时间</span>
        <Popover
          content={getSummaryText()}
          placement="rightTop"
          trigger="click"
          overlayClassName={styles.summaryPopover}
          // overlayStyle={{ width: 262 }}
          destroyTooltipOnHide
        >
        <div className={styles.quoteWrapper} >
          <img src={quoteIcon} className={styles.quoteIcon} />
        </div>
        </Popover>
      </div>

      <div className={styles.content}>
        <LineCharts dataSource={statisticTotalForCharts} />
      </div>
    </div>
  );
};

export default HighIncidenceTime; 