import services from '@/services';
import { QuestionCircleFilled } from '@ant-design/icons';
import { useSetState } from 'ahooks';
import { Flex, Popover, Space } from 'antd';
import dayjs from 'dayjs';
import EChartsReact from 'echarts-for-react';
import { cloneDeep } from 'lodash';
import React, { useEffect, useLayoutEffect, useMemo, useRef } from 'react';
import BaseCard from '../../../components/BaseCard';
import styles from './index.less';
import option from './option';
/** @name 情况 */
const LightingOperationSituation: React.FC = () => {
  const chartRef = useRef<any>();

  /** 数据源 */
  const [dataSource, setDataSource] = useSetState<{
    chartData?: {
      lightRate: number;
      faultRate: number;
      serviceabilityRatio: number;
      date: string;
    }[];
  }>({
    chartData: [],
  });

  const INFO = useMemo(() => {
    const latest = dataSource.chartData?.at(-1);
    return [
      {
        name: '完好率',
        value: latest?.serviceabilityRatio,
        unit: '%',
      },
      {
        name: '亮灯率',
        value: latest?.lightRate,
        unit: '%',
      },
      {
        name: '故障处置及时率',
        value: latest?.faultRate,
        unit: '%',
      },
    ];
  }, [dataSource.chartData]);

  /** 获取半年运行趋势 */
  const getHalfYearTrend = () => {
    services.DataBase.getSjdzInfoData({
      typeCode: 'hyzm-zmyxqkyd',
      params: {
        endTime: dayjs().format('YYYY-MM-DD'),
        startTime: dayjs().subtract(6, 'month').format('YYYY-MM-DD'),
      },
    }).then((res) => {
      if (res.code === 200) {
        const records = res.data?.data?.records;

        const data = records.map((record: any) => ({
          lightRate: record.ldl,
          faultRate: record.czl,
          serviceabilityRatio: record.whl,
          date: record.day,
        }));

        setDataSource({
          chartData: data,
        });
      }
    });
  };

  useEffect(() => {
    getHalfYearTrend();
  }, []);

  useLayoutEffect(() => {
    chartRef.current?.resize();
  }, []);

  const LineOption = useMemo(() => {
    const temp = cloneDeep(option) as any;
    const xAxis = dataSource.chartData?.map((v) => v.date) ?? [];

    temp.xAxis[0].data = xAxis;

    temp.legend.data = INFO.map((v) => v.name);

    const seriesData1 =
      dataSource.chartData?.map((v) => v.serviceabilityRatio) ?? [];
    const seriesData2 = dataSource.chartData?.map((v) => v.lightRate) ?? [];
    const seriesData3 = dataSource.chartData?.map((v) => v.faultRate) ?? [];

    const max = 100;
    /** 计算最小值 */
    const min = Math.min(...seriesData1, ...seriesData2, ...seriesData3);

    temp.yAxis[0].min = min === Infinity ? 0 : min;
    temp.yAxis[0].max = max;

    const lineSeries = [
      {
        name: '完好率',
        type: 'line',
        symbol: 'none',
        stack: 'Total',

        lineStyle: {
          width: 3,
        },
        data: seriesData1,
      },
      {
        name: '亮灯率',
        type: 'line',
        symbol: 'none',

        lineStyle: {
          width: 3,
        },
        smooth: true,
        data: seriesData2,
      },
      {
        name: '故障处置及时率',
        type: 'line',
        symbol: 'none',

        lineStyle: {
          width: 3,
        },
        smooth: true,
        data: seriesData3,
      },
    ];
    temp.series = lineSeries;
    return temp;
  }, [dataSource.chartData]);
  return (
    <BaseCard
      w={755}
      h={422}
      title="市管功能照明运行态势"
      headerRight={
        <Space style={{ fontSize: 16 }}>
          {`统计时间范围：${dataSource.chartData?.at(-1)?.date ?? '--'}`}
          <Popover title="统计时间到:" content="上月25号到本月24号">
            <QuestionCircleFilled />
          </Popover>
        </Space>
      }
    >
      <Flex justify="space-between" style={{ marginTop: 20 }} align="center">
        {INFO.map((item) => {
          return (
            <Flex
              className={styles.item}
              align="center"
              justify="center"
              key={item.name}
            >
              <div>{item.name}</div>
              <div>{item.value ?? '--'}</div>
              <div>{item.unit}</div>
            </Flex>
          );
        })}
      </Flex>
      <div>
        <div className={styles.chartTitle}>近半年运行趋势</div>
        <EChartsReact
          ref={chartRef}
          style={{
            height: 180,
          }}
          option={LineOption}
        ></EChartsReact>
      </div>
    </BaseCard>
  );
};

export default LightingOperationSituation;
