import ChartModule from '@/components/ManagementPage/chartModule';
import PageContent from '@/components/PageContent';
import { getDeviceRealDataByTime } from '@/services/SmartOps';
import { useParams, useSearchParams } from '@umijs/max';
import { Button, DatePicker, Empty, Form, Spin } from 'antd';
import dayjs from 'dayjs';
import { useEffect, useState } from 'react';
import styles from './index.less';

const { RangePicker } = DatePicker;
const tabs = [
  {
    label: '近一天',
    value: 24,
    timeRange: [dayjs().subtract(1, 'day'), dayjs()],
  },
  {
    label: '近一周',
    value: 24 * 7,
    timeRange: [dayjs().subtract(7, 'day'), dayjs()],
  },
  {
    label: '近一个月',
    value: 24 * 30,
    timeRange: [dayjs().subtract(1, 'month'), dayjs()],
  },
];

const ChartPage = (props) => {
  const {
    // location: {
    //   query: { type = 2, data },
    // },
  } = props;

  const { projectId } = useParams();
  const [searchParams, setSearchParams] = useSearchParams();
  const type = searchParams.get('type') || 2;
  const data = searchParams.get('data');

  const [loading, setLoading] = useState(false);
  const [options, setOptions] = useState({});
  const [timeActive, setTimeActive] = useState(0);
  const [timeRange, setTimeRange] = useState([
    dayjs().subtract(1, 'day'),
    dayjs(),
  ]);

  const defaultSearch = {
    deviceid: '',
    dataitemid: '',
    project_id: projectId,
    stime: dayjs().subtract(1, 'day').valueOf(),
    etime: dayjs().valueOf(),
    size: 10,
    interval: 'minute',
    aggregator: 'realtime',
  };

  const changeTime = async (timeType, date) => {
    const values = { ...defaultSearch };
    let diffDay;
    // values.timeType = timeType;
    if (date) {
      const [startDate, endDate] = date;
      values.etime = endDate * 1;
      values.stime = startDate * 1;
      diffDay = endDate.diff(startDate, 'days');
    } else {
      let currentDate = dayjs();
      values.etime = currentDate * 1;
      values.stime = currentDate.subtract(timeType, 'hour') * 1;
      diffDay = (timeType / 24).toFixed(0);
    }
    if (diffDay >= 15 && diffDay < 30) {
      // 15-30天 时间间隔不能为分钟
      values.interval = 'h';
      values.size = 1;
    } else if (diffDay >= 30) {
      // 超过30天 时间间隔只能为天
      values.interval = 'day';
      values.size = 1;
    }

    setLoading(true);
    const list = JSON.parse(data);
    const paramsList = list?.map((item) => {
      return { ...values, ...item }; // deviceid: item.deviceid, dataitemid: item.dataitemid
    });

    getData(paramsList);
  };

  const handleTabChange = (tab) => {
    const params = { ...defaultSearch };
    switch (tab) {
      case 1: //日
        break;
      case 2: //月
        params.size = 1;
        params.interval = 'h';
        params.stime = dayjs().subtract(1, 'month').valueOf();
        params.etime = dayjs().valueOf();
        break;
      case 3: //年
        params.size = 1;
        params.interval = 'day';
        params.stime = dayjs().subtract(1, 'year').valueOf();
        params.etime = dayjs().valueOf();
        break;
    }

    const list = JSON.parse(data);
    const paramsList = list?.map((item) => {
      return {
        ...params,
        deviceid: item.deviceid,
        dataitemid: item.dataitemid,
      };
    });
    getData(paramsList);
  };

  useEffect(() => {
    handleTabChange(1);
  }, []);

  const getData = async (list) => {
    const data = await Promise.all(
      list?.map((item) => {
        return getDeviceRealDataByTime(item).then((res) => res.data);
      }),
    );
    setLoading(false);
    const options = {
      yName: '',
      xData: data.length > 0 && data[0]?.map((item) => item.htime_at),
      legend: {
        textStyle: {
          color: '#ffffff',
        },
      },
      dataList: data?.map((item) => {
        return {
          type: 0,
          name: item?.[0]?.name,
          data: item?.map((item) => item.val * 1),
        };
      }),
    };
    // console.log(options);

    if (
      options.dataList?.every((item) => !item.data || item.data.length == 0)
    ) {
      setOptions(null);
    } else {
      setOptions(options);
    }
  };

  return (
    <PageContent closeable={false}>
      <div
        style={{
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'space-between',
        }}
      >
        <div className={styles.form}>
          <Form.Item style={{ marginBottom: 0 }}>
            <RangePicker
              dropdownClassName={styles.formDropDown}
              value={timeRange}
              showTime={false}
              inputReadOnly
              disabledDate={(current) =>
                current && current > dayjs().endOf('day')
              }
              onChange={(date) => {
                setTimeRange(date);
                setTimeActive(null);
                changeTime(-1, date);
              }}
              allowClear={false}
            />
          </Form.Item>
          <div>
            {tabs.map((item, index) => (
              <Button
                key={item.type}
                type="primary"
                style={{
                  marginRight: 20,
                  fontSize: 24,
                  height: 50,
                  background: timeActive == index ? '#329BFE' : '#2F4D83',
                }}
                onClick={() => {
                  setTimeActive(index);
                  changeTime(item.value);
                  setTimeRange(item.timeRange);
                }}
              >
                {item.label}
              </Button>
            ))}
          </div>
        </div>
      </div>

      <Spin spinning={loading}>
        <div style={{ height: 'calc(100vh - 100px)' }}>
          {options ? (
            <ChartModule chartType="line" {...options} />
          ) : (
            <Empty style={{ marginTop: 140 }} />
          )}
        </div>
      </Spin>
    </PageContent>
  );
};
export default ChartPage;
