import React, { useContext, useEffect, useRef, useState } from 'react';
import { ConfigProvider, Modal, Radio, Slider, InputNumber } from 'antd';
import classNames from 'classnames';
import moment from 'moment';
import { BasicChart } from '@wisdom-components/basicchart';
import { getHistoryInfo } from '../apis';
import { std,median } from 'mathjs';
import './index.less';

const LimitCurve = (props) => {
  const { getPrefixCls } = useContext(ConfigProvider.ConfigContext);
  const prefixCls = getPrefixCls('limit-curve');

  const { width, deviceCode, sensors, deviceType, getContainer, title } = props;
  const [open, isOpen] = useState(true);
  const [cluster, setCluster] = useState('K-means'); // 聚集算法
  const [outlier, setOutlier] = useState(1); // 过滤异常
  const [curve, setCurve] = useState('特征曲线'); // 曲线类型
  const [sensitive, setSensitive] = useState(10); // 敏感度
  const [stdVal, setStdVal] = useState(null); // 均方差
  const [medianVal, setMedianVal] = useState(null); // 平均值
  const [sensorData, setSensorData] = useState([]); // 所有数据
  const [chartData, setChartData] = useState([]); // 图表数据
  const [options, setOptions] = useState({});

  const chartRef = useRef(null);

  // 确定
  const onOk = () => {
    props.onOk && props.onOk(123);
  };

  // 取消
  const onCancel = () => {};

  // 获取历史数据
  const getSensorsData = async () => {
    const params = {
      isDilute: true,
      zoom: '',
      unit: '',
      dateFrom: moment().subtract(7, 'day').format('YYYY-MM-DD 00:00:00'),
      dateTo: moment().format('YYYY-MM-DD 23:59:59'),
      acrossTables: [
        { deviceCode: 'EGBF00000120', sensors: '出水瞬时流量', deviceType: '二供泵房' },
      ],
      isBoxPlots: true,
    };
    const results = await getHistoryInfo(params);
    const historyData = results?.data?.[0] || {};
    const dataArr = historyData?.dataModel.map((item) => {
      return item.pv;
    });
    
    setSensorData(() => {
      setStdVal(std(dataArr));
      setMedianVal(median(dataArr));
      return historyData;
    });
    console.log(historyData, std(dataArr),median(dataArr));
  };

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

  useEffect(() => {
    const {dataModel= []} = sensorData;
    const range = {
      min: medianVal - stdVal*outlier,
      min: medianVal + stdVal*outlier,
    }
    const data = dataModel.map((item) => {
      return item.pv >= range.min && item.pv<=range.max;
    })

    console.log(data);
  }, [sensorData, cluster, outlier])

  // useEffect(() => {
  //   const option = {
  //     xAxis: {},
  //     yAxis: {},
  //     series: [
  //       {
  //         symbolSize: 20,
  //         data: [
  //           [10.0, 8.04],
  //           [8.07, 6.95],
  //           [13.0, 7.58],
  //           [9.05, 8.81],
  //           [11.0, 8.33],
  //           [14.0, 7.66],
  //           [13.4, 6.81],
  //           [10.0, 6.33],
  //           [14.0, 8.96],
  //           [12.5, 6.82],
  //           [9.15, 7.2],
  //           [11.5, 7.2],
  //           [3.03, 4.23],
  //           [12.2, 7.83],
  //           [2.02, 4.47],
  //           [1.05, 3.33],
  //           [4.05, 4.96],
  //           [6.03, 7.24],
  //           [12.0, 6.26],
  //           [12.0, 8.84],
  //           [7.08, 5.82],
  //           [5.02, 5.68],
  //         ],
  //         type: 'scatter',
  //       },
  //     ],
  //   };
  //   setOptions(option);
  // }, [sensorData]);

  return (
    <>
      <Modal
        title={`${sensors || ''}近7天历史数据`}
        centered
        okText={'确定'}
        width={width || '1200px'}
        cancelText={'取消'}
        open={open}
        onOk={onOk}
        onCancel={onCancel}
        wrapClassName={classNames(`${prefixCls}`)}
        getContainer={getContainer || document.body}
      >
        <div className={classNames(`${prefixCls}-box`)}>
          <div className={classNames(`${prefixCls}-header`)}>
            <div className={classNames(`${prefixCls}-header-list`)}>
              <span className={classNames(`${prefixCls}-header-item`)}>
                聚类算法：
                <Radio.Group
                  options={clusterArr}
                  optionType={'button'}
                  value={cluster}
                  onChange={(value) => {
                    setCluster(value);
                  }}
                />
              </span>
              <span className={classNames(`${prefixCls}-header-item`)}>
                异常过滤：
                <Radio.Group
                  options={outlierArr}
                  optionType={'button'}
                  value={outlier}
                  onChange={(value) => {
                    setOutlier(value);
                  }}
                />
              </span>
              <span className={classNames(`${prefixCls}-header-item`)}>
                敏感度：
                <Slider
                  min={0}
                  max={100}
                  style={{ width: '100px' }}
                  onChange={(value) => {
                    setSensitive(value);
                  }}
                  value={typeof sensitive === 'number' ? sensitive : 0}
                />
                <InputNumber
                  min={1}
                  max={100}
                  style={{
                    margin: '0 16px',
                    width: '100px',
                  }}
                  addonAfter="%"
                  value={sensitive}
                  onChange={(value) => {
                    setSensitive(value);
                  }}
                />
              </span>
            </div>
            <div className={classNames(`${prefixCls}-header-list`)}>
              <span className={classNames(`${prefixCls}-header-item`)}>
                曲线选择：
                <Radio.Group
                  options={chartArr}
                  optionType={'button'}
                  value={curve}
                  onChange={(value) => {
                    setCurve(value);
                  }}
                />
              </span>
            </div>
          </div>
          <div className={classNames(`${prefixCls}-content`)}>
            <BasicChart
              ref={chartRef}
              option={options}
              notMerge
              style={{ width: '100%', height: '100%' }}
            />
          </div>
        </div>
      </Modal>
    </>
  );
};

const outlierArr = [
  {
    label: '低',
    value: 1,
  },
  {
    label: '中',
    value: 2,
  },
  {
    label: '高',
    value: 3,
  },
];

const clusterArr = [
  {
    label: 'K-means',
    value: 'K-means',
  },
];

const chartArr = [
  {
    label: '特征曲线',
    value: '特征曲线',
  },
  {
    label: '原始曲线',
    value: '原始曲线',
  },
];

export default LimitCurve;
