import React, { useEffect, useState } from 'react';
import { Flex, Popover, Progress } from 'antd';
// import Modal from '@/components/HncyModal';
// import BaseCard from '@/pages/Common/components/BaseCard';
import dayjs from 'dayjs';
import services from '@/services';
import styles from './index.less';
import quoteIcon from '@/assets/images/newMain/quote.png';
import PieChart from './PieChart'

const AreaDistribution: React.FC = () => {
  const [statisticTotal, setStatisticTotal] = useState<any>([]);
  const [modalVisible, setModalVisible] = useState(false);
  const [pieData, setPieData] = 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.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);
    }
  };

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

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

  const renderSummaryContent = () => {
    // 按数量分类
    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(statisticTotal || []);
    
    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('、');

    return (
      <Flex vertical className={styles.summaryDetail}>
        <div className={styles.title}>区域分布总结</div>
        <PieChart data={pieData} chartStyle={{ width: '118px', height: '118px' }} />
        <div className={styles.desc}>
          从具体区（市）县看，有<span className={styles.highlight}> {above300Count} </span>个区（市）县案件均超过
          <span className={styles.highlight}> 300 </span>件
          {regions.above400.length > 0 && <>，其中<span className={styles.highlight}>{above400Names}</span>超过了400件</>}；
          有<span className={styles.highlight}> {regions.between100And300.length} </span>个区（市）县处理投诉案件数在100-300件之间；
          有<span className={styles.highlight}> {regions.below100.length} </span>个区（市）县处理投诉案件少于100件，分别是
          <span >{below100Names}</span>。
        </div>
      </Flex>
    );
  };

  return (
    <div className={styles.container}>
      <div className={styles.header}>
        <span className={styles.title}>区域分布</span>
        
        <Popover
          content={renderSummaryContent()}
          placement="bottomRight"
          trigger="click"
          overlayClassName={styles.summaryPopover}
        >
        <div className={styles.quoteWrapper} >
          <img src={quoteIcon} className={styles.quoteIcon} />
        </div>
        </Popover>
      </div>

      <div className={styles.progressWrap}>
        {statisticTotal?.map((item: any, index: number) => (
          <Flex key={index} align="center" justify="space-between" style={{ marginBottom: 18 }}>
            <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>
    </div>
  );
};

export default AreaDistribution; 