import { querySimulationProfit } from '@/services/SmartOps';
import { useRequest } from '@umijs/max';
import dayjs from 'dayjs';
import * as echarts from 'echarts';
import { useEffect, useRef } from 'react';

const SimulatePie = (props) => {
  const { projectId } = props;
  const domRef = useRef(null);
  const chartRef = useRef(null);

  const { data } = useRequest(querySimulationProfit, {
    defaultParams: [
      {
        project_id: projectId,
        s_time: dayjs().subtract(1, 'day').format('YYYY-MM-DD HH:00:00'),
        e_time: dayjs().format('YYYY-MM-DD HH:00:00'),
      },
    ],
    onSuccess(data) {
      console.log(data);
      if (Object.keys(data).length == 0) return;
      let options = getOption(data);

      // chartRef.current.clear();
      chartRef.current.setOption(options);
    },
  });

  const getProfit = () => {
    if (!data?.info) return '-';

    return Object.values(data.info).reduce(
      (total, currentValue) => total + currentValue,
      0,
    );
  };

  useEffect(() => {
    chartRef.current = echarts.init(domRef.current);

    // 在组件卸载时销毁图表实例
    return () => {
      chartRef.current.dispose();
    };
  }, []);

  return (
    <div className="card-box" style={{ padding: 26, marginTop: 30 }}>
      <h2 style={{ textAlign: 'center', fontSize: 30, color: '#4A4A4A' }}>
        通过模拟仿真预计未来一日可省 &nbsp;
        <span style={{ color: '#F5A623' }}>{getProfit()}元</span>
      </h2>
      <div ref={domRef} style={{ height: '25vh' }}></div>
    </div>
  );
};

function getOption(data) {
  let seriesData = [];
  let type = {
    0: '未分类',
    1: '过滤周期优化',
    2: '絮凝剂投加优化',
    3: '膜寿命预测',
    4: '膜反冲洗建议',
    5: '膜化学清洗建议',
    6: 'RO一段优化建议',
    7: 'RO二段优化建议',
    8: 'RO三段优化建议',
    9: 'RO杀菌周期优化',
    10: 'RO冲洗周期优化',
  };
  Object.entries(data.info).map(([key, value]) => {
    if (value > 0) {
      seriesData.push({
        value,
        name: type[key],
      });
    }
  });
  let option = {
    color: [
      '#4B9FEC',
      '#F5A623',
      '#91cc75',
      '#5470c6',
      '#fac858',
      '#ee6666',
      '#73c0de',
      '#3ba272',
      '#fc8452',
      '#9a60b4',
      '#ea7ccc',
    ],
    tooltip: {
      trigger: 'item',
      textStyle: {
        fontSize: 24
      },
    },
    series: [
      {
        type: 'pie',
        radius: ['50%', '70%'],
        label: {
          fontSize: 22,
        },
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)',
          },
        },
        data: seriesData,
      },
    ],
  };

  return option;
}

export default SimulatePie;
