import React, {useEffect, useMemo, useState, useContext} from 'react';
import GridChart from "./GridChart";
import {ConfigProvider} from "antd";
import moment from "moment";
import {getDeviceAlarmScheme, getHistoryInfo} from "./apis";
import SimgleChart from "./SingleChart";

// deviceAlarmSchemes 用来获取对应的 方案的最大值/最小值 标记状态

// dataSource 获取的报警信息
//        deviceParams,
//         defaultDate,


//   {
//     deviceCode: 'XMYL00000345',
//     sensors: '进水压力',
//     deviceType: '熊猫压力表',
//     pointAddressID: 4,
//   },
//{
//     "isDilute": true, // 抽稀
//     "zoom": "30",// 抽稀
//     "unit": "min",// 抽稀
//     "ignoreOutliers": false, // 滤波
//     "dateFrom": "2023-07-09 16:38:32",
//     "dateTo": "2023-07-10 16:38:32",
//     "acrossTables": [
//         {
//             "deviceCode": "XMYL00000297",
//             "sensors": "进水压力,是否在线",
//             "deviceType": "熊猫压力表"
//         }
//     ],
//     "isBoxPlots": true // 箱线图
// }
const DATE_FORMAT = 'YYYY-MM-DD';
const MobileHistoryChart = (
    {
        date = {
            dateFrom: moment().format(`${DATE_FORMAT} 00:00:00`),
            dateTo: moment().format(`${DATE_FORMAT} 23:59:59`)
        },
        deviceParams = [],
        ignoreOutliers = true,
        isDilute = true,
        needMarkLine = true,
        showBoxOption = true, //
        chartGrid = true,
        chartType='lineChart', // lineChart boxChart
    }
) => {
    const [deviceAlarmSchemes, setDeviceAlarmSchemes] = useState(null);
    const [chartDataSource, setChartDataSource] = useState(null);
    const {getPrefixCls} = useContext(ConfigProvider.ConfigContext);
    const prefixCls = getPrefixCls('history-view');
    const isBoxPlots =
        deviceParams?.length === 1 && deviceParams[0]?.sensors?.split(',').length === 1;
    const handleDataThinKey = (diffDays) => {
        // 移动端缩放的抽稀一倍
        if (diffDays >= 7 && diffDays < 15) {
            return {unit: 'h', zoom: '4'};
        } else if (diffDays >= 15 && diffDays < 30) {
            return {unit: 'h', zoom: '8'};
        } else if (diffDays >= 30) {
            return {unit: 'h', zoom: '12'};
        } else if (diffDays < 7 && diffDays >= 2) {
            return {unit: 'min', zoom: '80'};
        } else if (diffDays < 2 && diffDays >= 1) {
            return {unit: 'min', zoom: '60'};
        } else {
            return {unit: 'min', zoom: '20'};
        }
    };

    const getDataSource = () => {
        let diffDays = moment(date.dateTo).diff(moment(date.dateFrom), 'days');
        const thinKey = handleDataThinKey(diffDays);
        const acrossTables = deviceParams.map(item => {
            let _item = {...item};
            let _sensorArr = _item.sensors.split(',');
            if (!_sensorArr.includes('是否在线')) {
                _sensorArr.push('是否在线')
            }
            return _item;
        });
        let _params = {
            ...date,
            isBoxPlots,
            ignoreOutliers,
            isDilute,
            ...thinKey,
            acrossTables
        };
        getHistoryInfo({..._params}).then(res => {
            let data = [];
            const {dateFrom, dateTo} = date;
            if (res.code === 0 && res.data.length) {
                res.data.forEach((d) => {
                    d.dateFrom = dateFrom || '';
                    d.dateTo = dateTo || '';
                });
                deviceParams.forEach((p) => {
                    // 返回数据按查询指标顺序排序
                    const sensors = p.sensors?.split(',') ?? [];
                    const list = sensors.map((s) => {
                        const dataItem = res.data.find(
                            (d) => d.stationCode === p.deviceCode && d.sensorName === s,
                        );
                        if (dataItem) {
                            dataItem.dateFrom = dateFrom || '';
                            dataItem.dateTo = dateTo || '';
                            return dataItem;
                        } else {
                            return {};
                        }
                    });
                    data = data.concat(list);
                });
            }
            setChartDataSource(data);
        })
    };
    const getScheme = () => {
        getDeviceAlarmScheme({
            data: deviceParams.map((item) => ({
                deviceType: item.deviceType,
                deviceCode: item.deviceCode,
                pointAddressID: item.pointAddressID,
                sensorName: item.sensors,
            })),
        }).then((res) => {
            if (res.code === 0) setDeviceAlarmSchemes(res.data || []);
            else setDeviceAlarmSchemes([]);
            return Promise.resolve();
        }).catch((err) => {
            setDeviceAlarmSchemes([]);
            return Promise.resolve();
        });
    }
    useEffect(() => {
        getDataSource();
        getScheme();
    }, [])
    return deviceAlarmSchemes && chartDataSource ? <SimgleChart
        showBoxOption={showBoxOption}
        curveCenter={true}
        chartGrid={chartGrid}
        prefixCls={prefixCls}
        dataSource={chartDataSource}
        chartType={isBoxPlots ? chartType : null}
        deviceAlarmSchemes={deviceAlarmSchemes}
    /> : null
}

export {
    MobileHistoryChart
}