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

const AreaDistribution = () => {

  const [statisticTotal, setStatisticTotal] = useState<any>([])

  const [pieData, setPieData] = useState<any>([])

  const [summary, setSummary] = useState<Array<string | { text: string; highlight: boolean }>>([])

  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.getSjdzInfoData({
      typeCode: "quhs-quyj",
      params: {
        ...getDate()
      }
    })
    if (resp.code === 200) {
      const data = resp.data?.data?.records
      // 将成都市改为成都城管委
      data.forEach((record: any) => {
        if (record.ssqy === '成都市') {
          record.ssqy = '市城管委';
        }
      });
      setStatisticTotal(data)
      generateSummary(data)
    }
  }

  const generateSummary = (data: any[]) => {
    // 按数量分类
    const categorizeRegions = (data: any[]) => {
      const filteredData = data.filter(item => item.ssqy !== "市城管委");
      const above400 = filteredData.filter(item => Number(item.num) >= 400);
      const above300 = filteredData.filter(item => Number(item.num) >= 300 && Number(item.num) < 400);
      const between100And300 = filteredData.filter(item => Number(item.num) >= 100 && Number(item.num) < 300);
      const below100 = filteredData.filter(item => Number(item.num) < 100);
      
      return { above400, above300, between100And300, below100 };
    };
    
    const regions = categorizeRegions(data);
    const above300Count = regions.above300.length + regions.above400.length;
    const above400Names = regions.above400.map(item => item.ssqy).join('和');
    const below100Names = regions.below100.map(item => item.ssqy).join('、');
    
    // 使用固定格式生成总结文本
    const summaryParts = [
      '从具体区（市）县看，有',
      { text: above300Count.toString(), highlight: true },
      '个区（市）县案件均超过',
      { text: '300', highlight: true },
      '件',
    ];
    
    if (regions.above400.length > 0) {
      summaryParts.push(
        '，其中',
        ...regions.above400.map((item: any) => ({ text: item.ssqy, highlight: true })).reduce((acc: any, curr: any, idx: number) => {
          if (idx === regions.above400.length - 1) {
            return [...acc, curr];
          }
          return [...acc, curr, '和'];
        }, []),
        '超过了400件'
      );
    }
    
    summaryParts.push(
      '；有',
      { text: regions.between100And300.length.toString(), highlight: true },
      '个区（市）县处理投诉案件数在100-300件之间；有',
      { text: regions.below100.length.toString(), highlight: true },
      '个区（市）县处理投诉案件少于100件，分别是',
      below100Names,
      '。'
    );
    
    setSummary(summaryParts);
  };

  const getPieData = async () => {
    const resp = await services.DataBase.getSjdzInfoData({
      typeCode: "quhs-tsfbzj",
      params: {
        ...getDate()
      }
    })
    if (resp.code === 200) {
      const data = resp.data?.data?.records
      setPieData(data)
    }
  }

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

  // const chartData: any = [
  //   {
  //     name: '“5+2”中心城区',
  //     value: 1625,
  //     percent: 33
  //   },
  //   {
  //     name: '其它中心城区',
  //     value: 1625,
  //     percent: 33
  //   },
  //   {
  //     name: '郊区新城',
  //     value: 1625,
  //     percent: 33
  //   }
  // ]

  return (
    <Flex justify='space-between' gap={40} className={styles.wrap}>
      <div className={styles.progressWrap}>
        {
          statisticTotal?.map((item: any, index: number) => (
            <Flex key={index} align='center' justify='space-between' style={{ marginBottom: 20 }}>
              <div className={styles.itemName}>{item.ssqy}</div>
              <div className={styles.progress}>
                <Progress
                  size={{ height: 16 }}
                  status="active"
                  percent={item.num}
                  showInfo={false}
                  strokeColor={{ from: '#38F2E3', to: '#3DC3FF' }}
                />
              </div>
              <div className={styles.itemNum}>
                <span className={styles.num}>{item.num}</span>
                <span>件</span>
              </div>
            </Flex>
          ))
        }
      </div>
      <BaseCard
        width={552}
        height={353}
        title="区域分布总结"
        style={{
          padding: '20px 0',
          overflow: 'hidden'
        }}
      >
        <Flex vertical className={styles.content}>
          <PieChart data={pieData} chartStyle={{ width: '118px', height: '118px' }} />
          <div className={styles.desc}>
            {summary.map((part, index) => 
              typeof part === 'string' ? (
                <span key={index}>{part}</span>
              ) : (
                <span key={index} className={styles.tipsText}>{part.text}</span>
              )
            )}
          </div>
        </Flex>
      </BaseCard>
    </Flex>
  )
}

export default AreaDistribution