import React, { useState, useEffect } from 'react';
import { Line } from '@ant-design/plots';
import { queryPropertyData } from '@/services/ant-design-pro/environment';
export default ({ paramObj, spaceId }) => {
  let [data, setData] = useState([]);
  let [levelMax, setLevelMax] = useState(0);
  const dealTime = (date) => {
    const str = date.substr(8, 4);
    const time = str.slice(0, 2) + ':' + str.slice(2);
    return time;
  };
  useEffect(() => {
    if (paramObj.id && spaceId) {
      fn();
    }
  }, [paramObj, spaceId]);
  const fn = async () => {
    setData([]);
    let dataArr = [];
    if (paramObj.id == 'Tdb,RH') {
      const arrId = paramObj.id.split(',');
      let resArr = [];
      arrId.forEach((item, idx) => {
        const type = item == 'Tdb' ? '温度' : '湿度';
        const resData = getChartData(item, type);
        resArr.push(resData);
      });
      Promise.all(resArr).then((res) => {
        dataArr = [...res[0], ...res[1]];
        setData(dataArr);
      });
    } else {
      const resData = await getChartData(paramObj.id, paramObj.name);
      setData(resData);
    }
  };
  const getChartData = (objId, type) => {
    const params = {
      spaceId: spaceId,
      funcid: objId,
    };
    return queryPropertyData(params).then((res) => {
      let chartArr = [];
      if (res.dayTarget) {
        const max = res.dayTarget[0] && res.dayTarget[0][paramObj.maxType];
        setLevelMax(max); // 最大值
        res.propertyData.shift();
        const arr = res.propertyData;

        arr.forEach((itemArr) => {
          const scales =
            itemArr[1] == '-9999' ? '--' : Number(itemArr[1].toFixed(paramObj.pointNum));
          chartArr.push({ Date: dealTime(itemArr[0]), scales: scales, type: type });
        });
      }
      return chartArr;
    });
  };
  const config = {
    data,
    xField: 'Date',
    yField: 'scales',
    seriesField: 'type',
    xAxis: {
      range: [0, 1],
    },
    yAxis: {
      tickCount: 6,
    },
    legend: {
      layout: 'horizontal',
      position: 'top-right',
    },
    annotations: [
      // 辅助线
      {
        type: 'line',
        start: [0, levelMax],
        end: [data.length - 1, levelMax],
        top: true,
        style: {
          stroke: paramObj.id == 'Tdb,RH' ? 'white' : 'red',
          lineWidth: 1,
        },
      },
    ],
  };
  return <Line {...config} />;
};
