import PageContent from '@/components/PageContent';
import PageTitle from '@/components/PageTitle';
import {
  patrolOverview,
  patrolOverviewLine,
  patrolOverviewPie,
} from '@/services/eqSelfInspection';
import { useParams, useRequest } from '@umijs/max';
import { Spin } from 'antd';
import dayjs from 'dayjs';
import * as echarts from 'echarts';
import { useEffect, useRef } from 'react';
import styles from './index.less';

const defaultTime = {
  s_time: dayjs().subtract(7, 'days').format('YYYY-MM-DD'),
  e_time: dayjs().format('YYYY-MM-DD'),
};

const Statistics = (props) => {
  const { projectId } = useParams();
  const lineDomRef = useRef(null);
  const LineChartRef = useRef(null);

  const pieDomRef = useRef(null);
  const pieChartRef = useRef(null);

  const renderChart = () => {
    if (!LineChartRef.current || !pieChartRef.current) return;
    if (!lineData || !pieData) return;
    LineChartRef.current.clear();
    const lineOptions = getLineOption(
      lineData?.time,
      lineData?.data,
      '系统自测异常统计',
    );

    // 设置图表配置项
    LineChartRef.current.setOption(lineOptions);

    pieChartRef.current.clear();
    const pieOptions = getPieOption(pieData, '异常类型统计');

    // 设置图表配置项
    pieChartRef.current.setOption(pieOptions);
    // 构建图表的配置项
  };

  const {
    data: lineData,
    run,
    loading,
  } = useRequest(patrolOverviewLine, {
    defaultParams: [
      {
        projectId: Number(projectId),
        ...defaultTime,
      },
    ],
    formatResult(resData) {
      let data = [];
      let time = [];
      resData?.data?.forEach((item) => {
        data.push(item.val);
        time.push(dayjs(item.key).format('MM-DD'));
      });
      return { data, time };
    },
  });

  const {
    data: pieData,
    run: pieRun,
    loading: pieLoading,
  } = useRequest(patrolOverviewPie, {
    defaultParams: [
      {
        projectId: Number(projectId),
        ...defaultTime,
      },
    ],
    formatResult(resData) {
      return resData?.data?.map((item) => {
        return { name: item.key, value: item.val };
      });
    },
  });

  const { data: overviewData, loading: overviewLoading } = useRequest(
    patrolOverview,
    {
      defaultParams: [
        {
          projectId: Number(projectId),
        },
      ],
      formatResult(resData) {
        return [
          { num: resData?.data?.today_check_num, label: '今日自检次数' },
          { num: resData?.data?.today_exception_num, label: '今日异常次数' },
          { num: resData?.data?.all_check_num, label: '累计自检次数' },
          { num: resData?.data?.all_check_day, label: '累计自检天数' },
        ];
      },
    },
  );

  const getChartData = ({ s_time, e_time }) => {
    run({ projectId: Number(projectId), s_time, e_time });
    pieRun({ projectId: Number(projectId), s_time, e_time });
  };
  const onRadioChange = (e) => {
    console.log(e);
    let params = { s_time: defaultTime.s_time, e_time: defaultTime.e_time };
    if (e == 'month')
      params = {
        s_time: dayjs().subtract(1, 'month').format('YYYY-MM-DD'),
        e_time: dayjs().format('YYYY-MM-DD'),
      };
    else if (e == 'year')
      params = {
        s_time: dayjs().subtract(1, 'year').format('YYYY-MM-DD'),
        e_time: dayjs().format('YYYY-MM-DD'),
      };
    getChartData(params);
  };

  useEffect(() => {
    renderChart();
  }, [lineData, pieData]);

  useEffect(() => {
    LineChartRef.current = echarts.init(lineDomRef.current);
    pieChartRef.current = echarts.init(pieDomRef.current);
    return () => {
      LineChartRef.current.dispose();
      pieChartRef.current.dispose();
    };
  }, []);
  return (
    <PageContent closeable={false}>
      <PageTitle returnable>系统自检统计</PageTitle>
      <div className={`${styles.itemMain2} card-box`} style={{padding: '44px 0'}}>
        <div style={{ display: 'flex' }}>
          {overviewData?.map((item) => (
            <Text num={item.num} label={item.label} />
          ))}
        </div>
      </div>
      <div className={`${styles.itemMain2} card-box`}>
        <div className={styles.tabs}>近一周数据统计</div>
        <Spin spinning={loading}>
          <div
            ref={lineDomRef}
            style={{ height: '340px', margin: '10px 0 10px 0' }}
          />
        </Spin>
      </div>
      <div className={`${styles.itemMain2} card-box`}>
        <Spin spinning={pieLoading}>
          <div
            ref={pieDomRef}
            style={{ height: '340px', margin: '10px 0 10px 0' }}
          />
        </Spin>
      </div>
    </PageContent>
  );
};
export default Statistics;

const Text = (props) => {
  const { num, label } = props;
  return (
    <div className={styles.statisticsText}>
      <div className={styles.num}>{num}</div>
      <div className={styles.label} style={{ fontSize: 22 }}>
        {label}
      </div>
    </div>
  );
};

const getLineOption = (time, chartData, name) => {
  const y1Max = getMax(chartData);
  const dataType = 'line';
  const option = {
    color: [
      '#5470c6',
      '#91cc75',
      '#fac858',
      '#ee6666',
      '#73c0de',
      '#3ba272',
      '#fc8452',
      '#9a60b4',
      '#ea7ccc',
    ],
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross',
        crossStyle: {
          color: '#333',
        },
      },
      textStyle: {
        fontSize: 24
      },
    },
    // grid: {
    //   bottom: 30,
    //   left: 60,
    //   right: 30,
    // },
    xAxis: {
      type: 'category',
      axisPointer: {
        type: 'shadow',
      },
      axisLine: {
        lineStyle: {
          color: '#555',
        },
      },
      axisLabel: {
        fontSize: 16,
      },
      data: time,
    },
    yAxis: [
      {
        type: 'value',
        top: 20,
        // max: y1Max,
        // interval: y1Max / 5,
        // splitNumber: 5,
        // nameTextStyle: {
        //   color: '#fff',
        //   fontSize: 16,
        //   padding: [0, 0, 20, 0],
        // },
        axisLabel: {
          color: '#555',
        },
        axisLabel: {
          fontSize: 16,
          color: '#555',
        },
        axisLine: {
          show: false,
        },
        splitLine: {
          lineStyle: {
            type: 'dashed',
          },
        },
      },
    ],
    series: [
      {
        data: chartData,
        type: dataType,
        name: '次数',
        yAxisIndex: 0,
        smooth: true,
      },
    ],
    legend: {
      textStyle: {
        color: '#555',
        fontSize: 18,
      },
      lineStyle: {},
    },
    title: {
      text: name,
      top: '92%',
      left: '50%',
      textAlign: 'center',
      textStyle: {
        color: '#555',
        fontWeight: 'normal',
        fontSize: 18,
      },
    },
    // textStyle: {
    //   fontSize: 50
    // }
  };

  // if (chartData2) {
  //   const y2Max = getMax(chartData2);
  //   option.yAxis.push({
  //     type: 'value',
  //     max: y2Max,
  //     interval: y2Max / 5,
  //     splitNumber: 5,
  //     top: 20,
  //     position: 'right',
  //     nameTextStyle: {
  //       color: '#fff',
  //       fontSize: 16,
  //       // align: 'left',
  //       padding: [0, 0, 20, 0],
  //     },
  //     axisLabel: {
  //       color: '#fff',
  //     },
  //     axisLine: {
  //       show: false,
  //     },
  //     splitLine: {
  //       lineStyle: {
  //         type: 'dashed',
  //       },
  //     },
  //   });
  //   option.series.push({
  //     data: chartData2,
  //     type: 'line',
  //     name: active,
  //     yAxisIndex: 1,
  //   });
  // }

  return option;
};

const getPieOption = (chartData, name) => {
  const option = {
    title: {
      text: name,
      top: '92%',
      left: '50%',
      textAlign: 'center',
      textStyle: {
        color: '#555',
        fontWeight: 'normal',
        fontSize: 18,
      },
    },
    color: [
      '#5470c6',
      '#91cc75',
      '#fac858',
      '#ee6666',
      '#73c0de',
      '#3ba272',
      '#fc8452',
      '#9a60b4',
      '#ea7ccc',
    ],
    tooltip: {
      trigger: 'item',
      textStyle: {
        fontSize: 24
      },
    },
    legend: {
      orient: 'horizontal',
      // left: 'left',
      textStyle: {
        color: '#555',
        fontSize: 18,
      },
    },
    series: [
      {
        type: 'pie',
        radius: '50%',
        data: chartData,
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)',
          },
        },
      },
    ],
  };
  return option;
};

function getMax(arr) {
  const max = Math.max(...arr);
  if (max == 100) return 100;
  const exponent = Math.floor(Math.log10(max));
  const base = Math.pow(10, exponent);
  const remainder = max % base;
  const maxRoundUp = max - remainder + base;
  const maxFixed = maxRoundUp.toFixed(1); // 将最大值的小数位数限制为 1
  return Number(maxFixed); // 将字符串转换为数字并返回
}
