import EmptyWithConditions from '@/components/EmptyWithConditions';
import BaseCard from '@/pages/GlobalModalServices/components/BaseCard';
import { BaseDate } from '@/pages/GlobalModalServices/components/BaseDatePicker';
import services from '@/services';
import { CaretDownOutlined, CaretUpOutlined } from '@ant-design/icons';
import { useSetState } from 'ahooks';
import { Flex, Space } from 'antd';
import dayjs from 'dayjs';
import EChartsReact from 'echarts-for-react';
import { cloneDeep } from 'lodash';
import React, {
  memo,
  useEffect,
  useLayoutEffect,
  useMemo,
  useRef,
} from 'react';
import styles from './index.less';
import option from './option';

/** @name 故障趋势 */
const Trend: React.FC<{ date: BaseDate }> = memo((props) => {
  const { date } = props;

  const [dataSource, setDataSource] = useSetState<{
    ringRatio?: number;
    list?: any[];
  }>({});

  const getData = () => {
    let type = date.label === '昨日' ? '1' : '2';
    const diffDays = Math.abs(
      dayjs(date.value.start).diff(dayjs(date.value.end), 'day'),
    );
    if (date.label === 'dateRange') {
      if (diffDays > 60) {
        type = '3';
      }
      if (diffDays == 0) {
        type = '1';
      }
      if (diffDays > 0 && diffDays < 60) {
        type = '2';
      }
    }

    const lastStart = dayjs(date.value.start)
      .subtract(diffDays + 1, 'day')
      .format('YYYY-MM-DD');

    const lastEnd = dayjs(date.value.end)
      .subtract(diffDays + 1, 'day')
      .format('YYYY-MM-DD');

    services.DataBase.getSjdzInfoData({
      typeCode: 'hyzm-zm-gzqs',
      params: {
        type: type, //1:按小时，2:按日，3:按月
        startTime: date.value.start,
        endTime: date.value.end,
      },
    }).then((res) => {
      if (res.code === 200) {
        const record = res.data.data.records[0];

        // 获取上期数据
        services.DataBase.getSjdzInfoData({
          typeCode: 'hyzm-zm-gzqs',
          params: {
            type: type, //1:按小时，2:按日，3:按月
            startTime: lastStart,
            endTime: lastEnd,
          },
        }).then((lastRes) => {
          const lastRecord = lastRes.data.data.records[0];
          const calculateRingRatio = (current: number, last: number) => {
            if (last === 0) return 100; // 避免除以零
            return Number((((current - last) / last) * 100).toFixed(2));
          };

          const ringRatio = calculateRingRatio(record.total, lastRecord.total);

          setDataSource({
            ringRatio,
            list: record.list,
          });
        });
      }
    });
  };

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

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

  const LineOption = useMemo(() => {
    const temp = cloneDeep(option) as any;
    const xAxis =
      dataSource.list?.map((v) => {
        if (Number.isNaN(Number(v.key))) {
          return v.key;
        }

        return dayjs().set('hour', v.key).format('HH:00');
      }) ?? [];

    temp.xAxis[0].data = xAxis;

    const lineSeries = [
      {
        name: '故障数',
        type: 'line',
        symbol: 'none',
        stack: 'Total',
        lineStyle: {
          color: 'rgb(89, 238, 255)',
          width: 3,
        },
        smooth: true,

        areaStyle: {
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [
              {
                offset: 0,
                color: 'rgba(89, 238, 255,0.26)', // 0% 处的颜色
              },
              {
                offset: 1,
                color: 'rgba(89, 238, 255, 0)', // 100% 处的颜色
              },
            ],
            global: false, // 缺省为 false
          },
        },
        data:
          dataSource.list?.map((item) => {
            return item.num;
          }) ?? [],
      },
    ];
    temp.series = lineSeries;
    return temp;
  }, [dataSource.list]);
  return (
    <BaseCard
      w={648}
      h={200}
      title="故障趋势"
      headerRight={
        <Space align="center" className={styles.status}>
          <div>环比</div>
          <Flex
            align="center"
            style={{
              marginLeft: 10,
            }}
          >
            {(dataSource?.ringRatio ?? 0) < 0 ? (
              <CaretDownOutlined style={{ color: 'rgb(29, 187, 138)' }} />
            ) : (
              <CaretUpOutlined
                style={{ color: 'rgb(255, 0, 0)' }}
              ></CaretUpOutlined>
            )}

            <span
              className={styles.value}
              style={{
                color:
                  (dataSource?.ringRatio ?? 0) < 0
                    ? 'rgb(29, 187, 138)'
                    : 'rgb(255, 0, 0)',
              }}
            >
              {Math.abs(dataSource?.ringRatio ?? 0)
                ? Math.abs(dataSource?.ringRatio ?? 0)
                : '--'}
            </span>
            <span>%</span>
          </Flex>
        </Space>
      }
    >
      <EmptyWithConditions conditions={!Boolean(dataSource?.list?.length)}>
        <EChartsReact
          ref={chartRef}
          style={{
            height: 120,
          }}
          option={LineOption}
        ></EChartsReact>
      </EmptyWithConditions>
    </BaseCard>
  );
});

export default Trend;
