import React, { useMemo } from 'react';
import { VtxMap } from '@vtx/map/lib/VtxMap';
import { useSetState } from 'ahooks';
import moment from 'moment';
// import { COLOR_COLLECTION, ECHARTS_COLOR } from '../../config';
import { VMDatePicker } from '../vm-filter';
import BaseInfo from '../vm-info-collection';
import VMChart, { ChartTitle } from '../vm-chart';
import useSettings from '../vm-hooks/useSettings';
import PropTypes from 'prop-types';
import { BaseData } from './api';
import './style';

import jquery from 'jquery';
window.$ = jquery;
window.jQuery = jquery;
const ECHARTS_COLOR = {
    ['blue']: '#6494F9',
    ['yellow']: '#F6BD16',
    ['green']: '#63DAAA',
    ['red']: '#FF6767',
    ['orange']: '#FF9844',
    ['cyan_blue']: '#6DC8EC',
    ['purple']: '#945FB9',
    ['gray']: '#AEAEAE',
};
const COLOR_COLLECTION = ['#6494F9', '#63DAAA', '#FF6767', '#AEAEAE'];
const BaseContent = props => {
    const { id } = props;
    const [state, setState] = useSetState({
        start: moment().subtract(7, 'd'),
        end: moment(),
    });
    const { coords, info } = BaseData.useBaseInfo(id);
    const handleDateChange = (start, end) => {
        setState({ start, end });
    };
    return (
        <div className="community-base-content" style={{ width: '100%', height: '100%' }}>
            <div className="left">
                <div className="map-container">
                    {coords && (
                        <VtxMap
                            mapId="view"
                            mapCenter={coords}
                            mapPoints={[
                                {
                                    id: 'view',
                                    longitude: coords[0],
                                    latitude: coords[1],
                                },
                            ]}
                        />
                    )}
                </div>
                <BaseInfo data={info} />
            </div>
            <div className="right">
                <VMDatePicker
                    value={[state.start, state.end]}
                    onChange={dates => dates && handleDateChange(dates[0], dates[1])}
                    style={{ position: 'absolute', top: 24, right: 32 }}
                />
                <div className="chart-container">
                    <ChartTitle title="投放情况统计" />
                    <StatChart
                        start={state.start.format('YYYY-MM-DD')}
                        end={state.end.format('YYYY-MM-DD')}
                        id={id}
                    />
                </div>
                <div className="chart-container">
                    <ChartTitle title="投放量趋势分析" />
                    <TrendChart
                        start={state.start.format('YYYY-MM-DD')}
                        end={state.end.format('YYYY-MM-DD')}
                        id={id}
                    />
                </div>
            </div>
        </div>
    );
};

BaseContent.propTypes = {
    id: PropTypes.string,
};

const StatChart = props => {
    const { id, start, end } = props;
    const data = BaseData.useBaseProdStat(id, start, end) || [];
    const { isDark } = useSettings();
    const total = useMemo(() => {
        let result = 0;
        for (const item of data) {
            result += item.garbageWeight;
        }
        return result;
    }, [data]);
    const chartData = data.map((item, index) => ({
        value: item.garbageWeight,
        name: item.garbageType,
        itemStyle: {
            color: item.garbageColor ? ECHARTS_COLOR[item.garbageColor] : 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.garbageType === name)?.garbageWeight || 0;
                return `{a|${name}}      {b|${num}吨}`;
            },
        },
        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 = {
    id: PropTypes.string,
    start: PropTypes.string,
    end: PropTypes.string,
};

const TrendChart = props => {
    const { id, start, end } = props;
    const data = BaseData.useBaseProdTrend(id, start, end) || [];
    const xAxisData = [];
    const firstItem = data[0];
    const legendData = firstItem?.throwProductionDTOList.map(i => i.garbageType) || [];
    const getSeries = () => {
        if (!firstItem) return [];
        const typeCount = firstItem.throwProductionDTOList.length;
        const series = [];
        for (let i = 0; i < typeCount; i++) {
            const item = firstItem.throwProductionDTOList[i];
            series.push({
                name: item.garbageType,
                type: 'line',
                itemStyle: {
                    color: item.garbageColor
                        ? ECHARTS_COLOR[item.garbageColor]
                        : COLOR_COLLECTION[i],
                },
                data: [],
            });
        }
        for (const item of data) {
            xAxisData.push(item.date);
            for (let i = 0; i < typeCount; i++) {
                series[i].data.push(item.throwProductionDTOList[i].garbageWeight);
            }
        }
        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={260} width="100%" />;
};
TrendChart.propTypes = {
    id: PropTypes.string,
    start: PropTypes.string,
    end: PropTypes.string,
};
export default BaseContent;
