import React, {useEffect, useMemo, useState, useContext} from 'react';
import {ConfigProvider} from "antd";
import {Selector, Checkbox, Space} from 'antd-mobile/es';
import moment from "moment";
import {getDeviceAlarmScheme, getHistoryInfo} from "./apis";
import SimgleChart from "./SingleChart";
import {handlePx} from "./utils";
import styles from './index.less';

const DATE_FORMAT = 'YYYY-MM-DD HH:mm:ss';
const MobileHistoryChart = (
    {
        date, // 不传默认当天
        deviceParams = [],  // 设备参数，必传
        chartType = 'lineChart', // lineChart boxChart
        // ignoreOutliers = true, // 滤波
        isDilute = true,  // 抽稀去重
        needMarkLine = true,
        showBoxOption = true, // 开启箱线图配置，默认开启
        chartGrid = true, // 开启网格
        ...rest
    }
) => {
    const [deviceAlarmSchemes, setDeviceAlarmSchemes] = useState(null);
    const [chartDataSource, setChartDataSource] = useState(null);
    const [options, setOptions] = useState({
        curveCenter: true,
        ignoreOutliers: true
    });
    const checkboxStyle = {
        '--icon-size': handlePx(18, 'px'),
        '--font-size': handlePx(14, 'px'),
        '--gap': handlePx(6, 'px'),
    }
    const checkBoxOptions = useMemo(() => {
        return Object.keys(options).reduce((final, cur) => {
            if (options[cur]) final.push(cur);
            return final
        }, []);
    }, [options]);
    const [lineType, setLineType] = useState([chartType]);
    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: '60'};
        }
    };

    const getDataSource = () => {
        let dateFrom = date?.dateFrom || moment().subtract(1, 'days').format(`${DATE_FORMAT}`),
            dateTo = date?.dateTo || moment().format(`${DATE_FORMAT}`);
        let diffDays = moment(dateTo).diff(moment(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 = {
            dateFrom,
            dateTo,
            isBoxPlots,
            ignoreOutliers: options.ignoreOutliers,
            isDilute,
            ...thinKey,
            acrossTables
        };
        getHistoryInfo({..._params}).then(res => {
            let data = [];
            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(() => {
        getScheme();
    }, [])
    useEffect(() => {
        getDataSource();
    }, [options.ignoreOutliers, date])
    return deviceAlarmSchemes && chartDataSource ?
        <div style={{width: '100%', height: '100%', display: 'flex', flexDirection: 'column'}}>
            {
                chartDataSource.length === 1 ? <div className={styles[`${prefixCls}-item`]}>
                    <span style={{fontSize: handlePx(14)}}>曲线形态：</span>
                    <Selector
                        style={{display: 'inline-block', fontSize: handlePx(14)}}
                        options={[
                            {label: '线形图', value: 'lineChart'},
                            {label: '箱线图', value: 'boxChart'}
                        ]}
                        defaultValue={lineType}
                        onChange={(arr, extend) => {
                            setLineType(arr)
                        }}
                    />
                </div> : ''
            }
            <div className={styles[`${prefixCls}-item`]}>
                <span style={{fontSize: handlePx(14)}}>曲线设置：</span>
                <Checkbox.Group
                    value={checkBoxOptions}
                    onChange={val => {
                        let _arr = Object.keys(options);
                        let _options = _arr.reduce((final, cur) => {
                            final[cur] = !!val.includes(cur);
                            return final;
                        }, {})
                        setOptions(_options);
                    }}
                >
                    <Space direction='horizontal'>
                        <Checkbox style={checkboxStyle} value='curveCenter'>曲线居中</Checkbox>
                        <Checkbox style={checkboxStyle} value='ignoreOutliers'>滤波</Checkbox>
                    </Space>
                </Checkbox.Group>
            </div>
            <div style={{width: '100%', flex: 1}}>
                <SimgleChart
                    showBoxOption={showBoxOption}
                    curveCenter={options.curveCenter}
                    showGridLine={chartGrid}
                    prefixCls={prefixCls}
                    dataSource={chartDataSource}
                    chartType={isBoxPlots ? lineType[0] : null}
                    deviceAlarmSchemes={deviceAlarmSchemes}
                />
            </div>
        </div> : null
}
export {
    MobileHistoryChart
}