import services from '@/services';
import { useSetState } from 'ahooks';
import { Flex } 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 OperationCondition: React.FC = () => {
  const [dataSource, setDataSource] = useSetState<{
    info?: {
      turnOnTime: string;
      turnOnDate: string;
      turnOffTime: string;
      turnOffDate: string;
    };
    list?: {
      name: string;
      value: number;
    }[];
    power?: number;
  }>({});
  const chartRef = useRef<any>();

  const formatTime = (str: string) => {
    return str.slice(0, 5);
  };

  const INFO = useMemo(() => {
    return [
      {
        name: '开灯时间',
        value: dataSource.info?.turnOnTime
          ? formatTime(dataSource.info?.turnOnTime)
          : '--',
        tag: dataSource.info?.turnOnDate
          ? formatTime(dataSource.info?.turnOnDate)
          : '--',
      },
      {
        name: '关灯时间',
        value: dataSource.info?.turnOffTime
          ? formatTime(dataSource.info?.turnOffTime)
          : '--',
        tag: dataSource.info?.turnOffDate
          ? formatTime(dataSource.info?.turnOffDate)
          : '--',
      },
      {
        name: '自然光照度',
        value: dataSource?.power,
        unit: 'lux',
        tag: '实时',
      },
    ];
  }, [dataSource.info, dataSource?.power]);

  /** 获取光照时间 */
  const getLightTime = () => {
    services.DataBase.getGzInfoData({
      typeCode: 'gz-dl-zdpjz',
    }).then((res) => {
      if (res.code === 200) {
        setDataSource({
          power: res.data,
        });
      }
    });
  };

  /** 获取数据*/
  const getData = () => {
    services.DataBase.getSjdzInfoData({
      typeCode: 'hyzm-zmyxjckz',
      params: {
        endTime: dayjs().format('YYYY-MM-DD'),
        startTime: dayjs().subtract(3, 'day').format('YYYY-MM-DD'),
      },
    }).then((res) => {
      if (res.code === 200) {
        const record = res.data?.data?.records;

        setDataSource({
          info: {
            turnOnTime: record[1]?.actualTrunOn,
            turnOffTime: record[0]?.actualTrunOff,
            turnOnDate: dayjs(record[1]?.lightSwitchDate).format('MM月DD日'),
            turnOffDate: dayjs(record[0]?.lightSwitchDate).format('MM月DD日'),
          },
        });
      }
    });
  };

  const getTrend = () => {
    services.DataBase.getSjdzInfoData({
      typeCode: 'hyzm-glqsb',
      params: {
        endTime: dayjs().subtract(1, 'day').format('YYYY-MM-DD'),
      },
    }).then((res) => {
      if (res.code === 200) {
        const record = res.data?.data?.records;

        const list = record.map((v: any) => {
          return {
            value: v.gl,
            name: dayjs().set('hour', v.hour).format('HH:00'),
          };
        });

        setDataSource({
          list: list,
        });
      }
    });
  };

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

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

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

    temp.xAxis[0].data = xAxis;

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

    const lineSeries = [
      {
        name: '功率',
        type: 'line',
        symbol: 'none',
        stack: 'Total',
        lineStyle: {
          color: '#F0FF69',
          width: 3,
        },
        smooth: true,

        areaStyle: {
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [
              {
                offset: 0,
                color: 'rgb(240, 255, 105,0.26)', // 0% 处的颜色
              },
              {
                offset: 1,
                color: 'rgb(240, 255, 105,0)', // 100% 处的颜色
              },
            ],
            global: false, // 缺省为 false
          },
        },
        data:
          dataSource.list?.map((item) => {
            return item.value;
          }) ?? [],
      },
    ];
    temp.series = lineSeries;
    return temp;
  }, [dataSource.list]);
  return (
    <BaseCard w={755} h={303} title="运行情况">
      <Flex justify="space-between" style={{ marginTop: 10 }} align="center">
        {INFO.map((item) => {
          return (
            <Flex className={styles.item} align="center" key={item.name}>
              <div>{item.name}</div>
              <div>{item.value}</div>
              <div>{item.unit}</div>
              <div className={styles.tag}>{item.tag}</div>
            </Flex>
          );
        })}
      </Flex>
      <div>
        <div className={styles.chartTitle}>昨日功率趋势</div>
        <EChartsReact
          ref={chartRef}
          style={{
            height: 110,
          }}
          option={LineOption}
        ></EChartsReact>
      </div>
    </BaseCard>
  );
};

export default OperationCondition;
