import React, { useMemo, useEffect } from 'react';
import { useSetState, useRequest } from 'ahooks';
import { message, Space } from 'antd';
import { UnorderedListOutlined, ClockCircleOutlined } from '@ant-design/icons';
import { COLOR_COLLECTION, ECHARTS_COLOR } from '../../config';
import dayjs from 'dayjs';
import { getUrlParam } from '@vtx/utils';
import { VMDatePicker } from '../vm-filter';
import VMTable, { ExportBtn, renderColumnParam, TableTabs, TableTabsPane } from '../vm-table';
import useSettings from '../vm-hooks/useSettings';
import { WarningData, BaseData } from './api';
import SubTabs, { SubTabPane } from '../vm-sub-tabs';
import PropTypes from 'prop-types';
import VMChart from '../vm-chart';
import './style';

const WarningContent = props => {
    const { id, seed, carType } = props;
    const [state, setState] = useSetState({
        start: dayjs(),
        end: dayjs(),
        ids: [],
        tab: 'all',
        totalTab: 'table',
    });
    const { tableProps } = useRequest(
        ({ current, pageSize }) => {
            const func =
                carType === 'jxh' ? WarningData.getJxhWarningList : WarningData.getWarningList;
            return func(
                current,
                pageSize,
                id,
                state.start,
                state.end,
                state.tab === 'all' ? '' : state.tab,
            );
        },

        {
            defaultPageSize: 10,
            paginated: true,
            refreshDeps: [state.tab, state.start, state.end, id],
        },
    );
    // eslint-disable-next-line no-undef
    useEffect(() => {
        if (seed) setState({ start: dayjs(), end: dayjs(), ids: [] });
    }, [id, seed]);
    const statList = WarningData.useStatList(id, state.start, state.end, carType);
    const handleTabChange = activeKey => {
        setState({ tab: activeKey });
    };
    const handleDateChange = (start, end) => {
        setState({ start, end });
    };
    const handleExport = type => {
        let downloadAll = false;
        let ids = '';
        switch (type) {
            case 'all':
                downloadAll = true;
                break;
            case 'select-rows':
                ids = state.ids.join(',');
                break;
            case 'current-page':
                ids = tableProps?.dataSource?.map(i => i.id).join(',');
                break;
            default:
                break;
        }
        if (!downloadAll && ids.length === 0) {
            message.info('当前未选中数据！');
            return;
        }
        console.log(tableProps);
        if (carType === 'jxh') {
            WarningData.exportJxhData({
                tenantId: getUrlParam('tenantId'),
                carIds: id,
                startDate: state.start,
                endDate: state.end,
                subCategoryCode: state.tab === 'all' ? '' : state.tab,
                categoryCode: 'Alarm',
                columnJson: renderColumnParam(columns),
                ids,
            });
            return;
        }
        WarningData.exportData({
            carIds: id,
            startTime: state.start,
            endTime: state.end,
            downloadAll,
            ids,
            alarmStrategyName: state.tab === 'all' ? '' : state.tab,
            columnJson: renderColumnParam(columns),
        });
    };
    return (
        <div className="vehicle-warning-content">
            <Space className="filter">
                <VMDatePicker
                    defaultValue={[state.start, state.end]}
                    onChange={dates => dates && handleDateChange(dates[0], dates[1])}
                />
                {state.totalTab === 'table' && <ExportBtn onClick={handleExport} />}
            </Space>
            <SubTabs
                defaultActiveKey={state.totalTab}
                onChange={activeKey => setState({ totalTab: activeKey })}
            >
                <SubTabPane
                    tab={
                        <span>
                            <UnorderedListOutlined />
                            列表
                        </span>
                    }
                    key="table"
                >
                    <TableTabs activeKey={state.tab} onChange={handleTabChange}>
                        {statList.map(item => (
                            <TableTabsPane
                                tab={`${item.label}(${
                                    carType === 'jxh'
                                        ? tableProps.pagination.total || 0
                                        : item.count
                                })`}
                                key={item.key}
                            >
                                <div className="table-container">
                                    <VMTable
                                        columns={carType === 'jxh' ? jxhColumns : columns}
                                        rowSelection={{
                                            selectedRowKeys: state.ids,
                                            onChange: rowKeys => setState({ ids: rowKeys }),
                                        }}
                                        {...tableProps}
                                    />
                                </div>
                            </TableTabsPane>
                        ))}
                    </TableTabs>
                </SubTabPane>
                <SubTabPane
                    tab={
                        <span>
                            <ClockCircleOutlined />
                            图表
                        </span>
                    }
                    key="chart"
                >
                    <ChartContent
                        id={id}
                        carType={carType}
                        jxhTrendData={tableProps.dataSource}
                        start={state.start.format('YYYY-MM-DD hh:mm:ss')}
                        end={state.end.format('YYYY-MM-DD hh:mm:ss')}
                    />
                </SubTabPane>
            </SubTabs>
            <div className="top-bar"></div>
        </div>
    );
};
WarningContent.propTypes = {
    id: PropTypes.string,
    seed: PropTypes.string,
};

const ChartContent = props => {
    const { id, start, end, carType, jxhTrendData } = props;
    const { statChartInfo, statLineInfo } = BaseData.useAlarmStat(id, start, end);

    return (
        <div style={{ height: '100%' }}>
            {carType === 'jxh' ? (
                <JxhTrendChart data={jxhTrendData} start={start} end={end} />
            ) : (
                <>
                    <StatChart data={statChartInfo} />
                    <TrendChart data={statLineInfo} height={260} />
                </>
            )}
        </div>
    );
};
ChartContent.propTypes = {
    id: PropTypes.string,
    start: PropTypes.string,
    end: PropTypes.string,
};

const StatChart = props => {
    const { data } = props;
    const { isDark } = useSettings();
    const total = useMemo(() => {
        let result = 0;
        for (const item of data) {
            result += item.count;
        }
        return result;
    }, [data]);
    const chartData = data.map((item, index) => ({
        value: item.count,
        name: item.alarmTypeName,
        itemStyle: {
            color: item.color ? ECHARTS_COLOR[item.color] : COLOR_COLLECTION[index],
        },
    }));
    const option = {
        tooltip: {
            trigger: 'item',
        },
        legend: {
            icon: 'circle',
            orient: 'vertical',
            top: '35%',
            left: '65%',
            itemHeight: 8,
            itemWidth: 8,
            itemGap: 14,
            textStyle: {
                fontSize: 14,
                fontFamily: 'PingFangSC-Regular',
                rich: {
                    a: {
                        color: isDark ? 'white' : '#666',
                    },
                    b: {
                        color: isDark ? 'white' : '#222',
                    },
                },
            },
            formatter: name => {
                const num = data.find(i => i.alarmTypeName === name)?.count || 0;
                return `{a|${name}}      {b|${num}次(${
                    total === 0 ? 0 : Math.round((num * 100) / total)
                }%)}`;
            },
        },
        graphic: [
            {
                type: 'group',
                left: '40%',
                top: '50%',
                bounding: 'raw',
                children: [
                    {
                        type: 'text',
                        style: {
                            text: '违规次数',
                            fontFamily: 'PingFangSC-Regular',
                            fontSize: 14,
                            fill: '#858A91',
                            align: 'center',
                            y: -20,
                        },
                    },
                    {
                        type: 'text',
                        style: {
                            text: total,
                            fontWeight: 'bold',
                            fontSize: 20,
                            fill: isDark ? 'white' : '#222',
                            fontFamily: 'DIN-Regular',
                            align: 'center',
                            y: 10,
                        },
                    },
                ],
            },
        ],
        series: [
            {
                name: '',
                type: 'pie',
                radius: ['45%', '70%'],
                center: ['40%', '50%'],
                label: {
                    show: false,
                },
                labelLine: {
                    show: false,
                },
                data: chartData,
            },
        ],
    };
    return <VMChart option={option} height={260} width="100%" />;
};

StatChart.propTypes = {
    data: PropTypes.array,
};

const JxhTrendChart = ({ data = [], start, end }) => {
    const startDay = dayjs(start);
    const endDay = dayjs(end);
    const days = endDay.diff(startDay, 'd') + 1;
    const chartData = {};
    let xAxis = [...new Array(days)].map((e, i) => {
        const currentDay = startDay.add(i, 'd').format('YYYY-MM-DD');
        chartData[currentDay] = {
            count: 0,
            duration: 0,
        };
        const dayAlarmArr = data.filter(
            item => currentDay === dayjs(item.startTime).format('YYYY-MM-DD'),
        );
        const currentDayAlarmCount = dayAlarmArr.length;
        const currentDayDuration = dayAlarmArr.reduce((pre, cur) => pre + cur.currentDuration, 0);
        let hour = (currentDayDuration / 1000 / 3600).toFixed(2);
        chartData[currentDay].count = currentDayAlarmCount;
        chartData[currentDay].duration = hour;

        return currentDay;
    });

    const option = {
        tooltip: {
            trigger: 'axis',
        },
        grid: {
            left: '5%',
            right: '5%',
            bottom: '10%',
        },
        xAxis: {
            data: xAxis,
        },
        yAxis: [
            {
                name: 'h',
                type: 'value',
                min: 0,
            },
            {
                type: 'value',
                name: '次',
                min: 0,
            },
        ],
        series: [
            {
                name: '超速时长',
                type: 'bar',
                data: xAxis.map(date => chartData[date].duration),
            },
            {
                name: '超速次数',
                type: 'line',
                data: xAxis.map(date => chartData[date].count),
                yAxisIndex: 1,
            },
        ],
    };
    return <VMChart option={option} height="100%" width="100%" />;
};
const TrendChart = props => {
    const { data, height } = props;
    const xAxisData = [];
    const legendData = [];
    const getSeries = () => {
        const series = [];
        for (const item of data) {
            if (xAxisData.findIndex(x => x === item.day) === -1) {
                xAxisData.push(item.day);
            }
            if (legendData.findIndex(l => l === item.alarmTypeName) === -1) {
                legendData.push(item.alarmTypeName);
            }
            const s = series.find(s => s.name === item.alarmTypeName);
            if (s) {
                s.data.push(item.count);
            } else {
                series.push({
                    name: item.alarmTypeName,
                    type: 'line',
                    itemStyle: {
                        color: item.color
                            ? ECHARTS_COLOR[item.color]
                            : COLOR_COLLECTION[xAxisData.findIndex(x => x === item.alarmTypeName)],
                    },
                    data: [item.count],
                });
            }
        }
        return series;
    };
    const option = {
        tooltip: {
            trigger: 'axis',
        },
        legend: {
            data: legendData,
        },
        grid: {
            left: '5%',
            right: '5%',
            bottom: '10%',
        },
        xAxis: {
            data: xAxisData,
        },
        yAxis: {
            name: '(次)',
        },
        series: getSeries(),
    };
    return <VMChart option={option} height={height} width="100%" />;
};
TrendChart.propTypes = {
    data: PropTypes.array,
    height: PropTypes.number,
};

const columns = [
    {
        title: '报警类型',
        dataIndex: 'alarmTypeName',
        key: 'alarmTypeName',
        width: 80,
    },
    {
        title: '报警等级',
        dataIndex: 'alarmLevelName',
        key: 'alarmLevelName',
        width: 80,
    },
    {
        title: '报警开始时间',
        dataIndex: 'alarmBeginTime',
        key: 'alarmBeginTime',
        width: 120,
    },
    {
        title: '报警结束时间',
        dataIndex: 'alarmEndTime',
        key: 'alarmEndTime',
        width: 120,
    },
    {
        title: '报警时长',
        dataIndex: 'beginDuration',
        key: 'beginDuration',
        width: 120,
    },
    {
        title: '当前速度(km/h)',
        dataIndex: 'positionSpeed',
        key: 'positionSpeed',
        width: 100,
    },
    {
        title: '报警地址',
        dataIndex: 'alarmAddress',
        key: 'alarmAddress',
        width: 300,
    },
];

const jxhColumns = [
    {
        title: '报警类型',
        dataIndex: 'subCategoryName',
        key: 'subCategoryName',
        width: 80,
    },
    {
        title: '报警开始时间',
        dataIndex: 'startTime',
        key: 'startTime',
        width: 120,
    },
    {
        title: '报警结束时间',
        dataIndex: 'endTime',
        key: 'endTime',
        width: 120,
    },
    {
        title: '报警时长',
        dataIndex: 'currentDurationStr',
        key: 'currentDurationStr',
        width: 120,
    },
    {
        title: '当前速度(km/h)',
        dataIndex: 'currentSpeed',
        key: 'currentSpeed',
        width: 100,
    },
    {
        title: '报警地址',
        dataIndex: 'roadName',
        key: 'roadName',
        width: 300,
    },
];
export default WarningContent;
