import { Flex } from 'antd'
import styles from './index.less'
import LineCharts from './LineCharts'
import BaseCard from '@/pages/Common/components/BaseCard'
import dayjs from 'dayjs'
import services from '@/services'
import { useEffect, useState } from 'react'

const HighIncidenceTime = () => {

  const [statisticTotal, setStatisticTotal] = useState<any>([])
  const [statisticTotalForCharts, setStatisticTotalForCharts] = useState<any>([])
  const [summary, setSummary] = useState<string[]>([])

  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]
      
      // 处理数据,确保每个时间点都有数据,并按自然顺序排序
      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;
      };
      
      const processedData = [
        { ...resp.data?.all, data: processData(resp.data?.all?.data) },
        ...resp.data?.data.map((item: any) => ({
          ...item,
          data: processData(item.data)
        }))
      ];
      
      setStatisticTotal(data);  // 保留原始数据用于生成总结
      setStatisticTotalForCharts(processedData);  // 处理后的数据用于图表展示
      generateSummary(data)
    }
  }

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

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

    // 获取每个类型的前三高发时段
    const typeTimesSummary = top3Types.map(type => {
      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
      };
    });

    const summaryText = [
      `近一个月投诉主要集中在 ${overallTop3Times}。`,
      '其中市民关注和反映问题较多问题：',
      ...typeTimesSummary.map(item => `${item.name}集中在 ${item.times}。`)
    ];
    
    setSummary(summaryText);
  };

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

  return (
    <Flex justify='space-between' gap={30} className={styles.wrap}>
      <div style={{ flex: 1 }}>
        <LineCharts dataSource={statisticTotalForCharts} />
      </div>
      <BaseCard
        width={417}
        height={353}
        title="高发时间总结"
        style={{
          paddingTop: 20
        }}
      >
        <div className={styles.content}>
          {summary.map((text, index) => (
            <p key={index}>
              {text.split(/(\d+点[、]?\d*点?[、]?\d*点?。?)/).map((part, i) => (
                part.match(/\d+点[、]?\d*点?[、]?\d*点?。?/) ? 
                <span key={i} className={styles.tipsText}>{part}</span> : 
                <span key={i}>{part}</span>
              ))}
            </p>
          ))}
        </div>
      </BaseCard>
    </Flex>
  )
}

export default HighIncidenceTime