import services from '@/services';
import { useRequest } from 'ahooks';
import * as echarts from 'echarts';
import React, { useEffect, useMemo, useRef } from 'react';
import styles from './index.less';
import { values } from 'lodash';

interface StatisticsChartProps {
  searchTime: {
    startTime: string;
    endTime: string;
  };
}

const StatisticsChart: React.FC<StatisticsChartProps> = ({ searchTime }) => {
  const chartRef = useRef<HTMLDivElement>(null);

  const { data: charData } = useRequest(
    () =>
      services.DataBase.getSjdzInfoData({
        typeCode: 'zzcc-jzlj-lxtjlssbpfl',
        params: {
          ...searchTime,
        },
      }).then((res) => {
        if (res.code === 200) {
          return res?.data?.data?.records;
        }
        throw new Error('获取数据失败');
      }),
    {
      refreshDeps: [searchTime],
    },
  );
  const { data: total } = useRequest(
    () =>
      services.DataBase.getSjdzInfoData({
        typeCode: 'zzcc-jzlj-aqytjpfl',
        params: {
          ...searchTime,
        },
      }).then((res) => {
        if (res.code === 200) {
        

          return res?.data?.data?.records?.[0]?.total;
        }
        throw new Error('获取数据失败');
      }),
    {
      refreshDeps: [searchTime],
    },
  );

  let isUsingValue = true;
  const data = useMemo(() => {
    const gczt = charData?.find((item) => item.name === 'gczt')?.num??0;
    const gcnj = charData?.find((item) => item.name === 'gcnj')?.num??0;
    const zxlj = charData?.find((item) => item.name === 'zxlj')?.num??0;
    const gclj = charData?.find((item) => item.name === 'gclj')?.num??0
    const cclj = charData?.find((item) => item.name === 'cclj')?.num??0;


    
    return [
      {
        name: '工程渣土',
        value: gczt,
        percentage: ((gczt / total) * 100).toFixed(2),
        color: '#FF9B5D',
      },
      {
        name: '工程泥浆',
        value: gcnj,
        percentage: ((gcnj / total) * 100).toFixed(2),
        color: '#FFE335',
      },
      {
        name: '装修垃圾',
        value: zxlj,
        percentage: ((zxlj / total) * 100).toFixed(2),
        color: '#35B2FF',
      },
      {
        name: '工程垃圾',
        value: gclj,
        percentage: ((gclj / total) * 100).toFixed(2),
        color: '#77E67B',
      },
      {
        name: '拆除垃圾',
        value: cclj,
        percentage: ((cclj / total) * 100).toFixed(2),
        color: '#00FFB3',
      },
    ];
  }, [charData, total]);

  const showValue = (value: number | string) => {
    if (isUsingValue) {
      return value;
    }
    return '--';
  };

  useEffect(() => {
    if (!chartRef.current) return;

    const chart = echarts.init(chartRef.current);

    const option = {
      tooltip: {
        trigger: 'item',
        backgroundColor: 'rgba(8, 24, 63, 0.9)',
        borderColor: '#13659680',
        borderWidth: 1,
        textStyle: {
          color: '#BCCEE9',
        },
      },
    
      title: {
        // text: isUsingValue ? total : '---.--',
        text: '0',
        subtext: '共计（万方）',
        left: '68px', // 根据需求调整位置
        top: '58px', // 根据需求调整位置
        textStyle: {
          color: '#FFFFFF',
          fontSize: 24,
          fontFamily: 'D-DIN',
          lineHeight: 31,
        },
        subtextStyle: {
          color: '#BCCEE9',
          fontSize: 16,
          lineHeight: 23,
        },
      },
      series: [
        {
          type: 'pie',
          padAngle: 5,
          radius: ['50%', '70%'],
          center: ['40%', '38%'], // 调整环形图位置
          data: data.map((item) => ({
            name: item.name,
            // value: item.value,
            value:0,
            itemStyle: {
              color: item.color,
            },
          })),
          label: {
            show: false,
          },
        },
      ],
    };

    chart.setOption(option);

    return () => {
      chart.dispose();
    };
  }, [total]);

  return (
    <div className={styles.container}>
      <div className={styles.title}>建筑垃圾申报排放统计</div>
      <div className={styles.content}>
        <div className={styles.chart}>
          <div ref={chartRef} style={{ width: '270px', height: '270px' }} />
        </div>
        <div className={styles.legend}>
          <div className={styles.legendColumn}>
            {data.slice(0, 3).map((item, index) => (
              <div key={index} className={styles.legendItem}>
                <div
                  className={styles.dot}
                  style={{ background: item.color }}
                />
                <div className={styles.info}>
                  <div className={styles.type}>{item.name}</div>
                  <div className={styles.value}>
                    {showValue(item.value)}
                    <span className={styles.unit}>万方</span>
                  </div>
                  <div className={styles.percentage}>
                    {showValue(item.percentage)}%
                  </div>
                </div>
              </div>
            ))}
          </div>
          <div className={styles.legendColumn}>
            {data.slice(3).map((item, index) => (
              <div key={index} className={styles.legendItem}>
                <div
                  className={styles.dot}
                  style={{ background: item.color }}
                />
                <div className={styles.info}>
                  <div className={styles.type}>{item.name}</div>
                  <div className={styles.value}>
                    {showValue(item.value)}
                    <span className={styles.unit}>万方</span>
                  </div>
                  <div className={styles.percentage}>
                    {showValue(item.percentage)}%
                  </div>
                </div>
              </div>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
};

export default StatisticsChart;
