import React, { useEffect, useMemo } from 'react';
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 StatCollection from '../vm-stat-collection';
import PropTypes from 'prop-types';
import SubTabs, { SubTabPane } from '../vm-sub-tabs';
import { Carousel } from 'antd';
import { BaseData } from './api';
import './style';

import secondDarkImg from '../../image/vehicle-alarm-second-dark.png';
import secondImg from '../../image/vehicle-alarm-second.png';
import timesDarkImg from '../../image/vehicle-alarm-times-dark.png';
import timesImg from '../../image/vehicle-alarm-times.png';
import dayDarkImg from '../../image/vehicle-alarm-day-dark.png';
import dayImg from '../../image/vehicle-alarm-day.png';
import workMilesImg from '../../image/vehicle-work-miles.png';
import driveMilesImg from '../../image/vehicle-drive-miles.png';
import workOverSpeedImg from '../../image/vehicle-work-overspeed.png';
import workOverSpeedTimeImg from '../../image/vehicle-work-overspeedTime.png';
import workRateImg from '../../image/vehicle-work-rate.png';
import workTimeImg from '../../image/vehicle-work-time.png';

import workMilesDarkImg from '../../image/vehicle-work-miles-dark.png';
import driveMilesDarkImg from '../../image/vehicle-drive-miles-dark.png';
import workOverSpeedDarkImg from '../../image/vehicle-work-overspeed-dark.png';
import workOverSpeedTimeDarkImg from '../../image/vehicle-work-overspeedTime-dark.png';
import workRateDarkImg from '../../image/vehicle-work-rate-dark.png';
import workTimeDarkImg from '../../image/vehicle-work-time-dark.png';

import {
    TimeInfo,
    LocationInfo,
    StatusInfo,
    VehicleRing,
    VehicleDrive,
    VehicleSpeed,
} from './element';

const BaseContent = props => {
    const { id, seed, carType } = props;
    const { isDark } = useSettings();
    const [state, setState] = useSetState({
        start: moment().subtract(7, 'd'),
        end: moment(),
    });
    const {
        info,
        jxhInfo,
        realTimeInfo,
        permissionInfo,
        workSummary,
        workChart,
    } = BaseData.useBaseInfo(id, state.start, state.end);
    const { statInfo, statChartInfo } = BaseData.useAlarmStat(id, state.start, state.end);
    const workMileage = BaseData.getTodayWorkMile(id);
    useEffect(() => {
        if (seed) setState({ start: moment().subtract(7, 'd'), end: moment() });
    }, [id, seed]);

    const statData = [
        {
            icon: isDark ? timesDarkImg : timesImg,
            label: '违规次数',
            value: statInfo?.times,
            unit: '次',
        },
        {
            icon: isDark ? dayDarkImg : dayImg,
            label: '累计违规天数',
            value: statInfo?.days,
            unit: '天',
        },
        {
            icon: isDark ? secondDarkImg : secondImg,
            label: '累计违规时长',
            value: [statInfo?.hour, statInfo.minute, statInfo.second],
            unit: ['时', '分', '秒'],
        },
    ];
    // 机械化车辆统计信息
    const jxhStatData = [
        {
            icon: isDark ? driveMilesDarkImg : driveMilesImg,
            label: '行驶里程',
            value: workSummary?.total_mileage,
            unit: 'km',
        },
        {
            icon: isDark ? workMilesDarkImg : workMilesImg,
            label: '作业里程',
            value: workSummary?.work_mileage,
            unit: 'km',
        },
        {
            icon: isDark ? workRateDarkImg : workRateImg,
            label: '作业率',
            value: workSummary?.rate,
            unit: '%',
        },
        {
            icon: isDark ? workTimeDarkImg : workTimeImg,
            label: '作业时长',
            value: [
                workSummary.duration?.hour || 0,
                workSummary.duration?.minute || 0,
                workSummary?.duration?.seconds || 0,
            ],
            unit: ['时', '分', '秒'],
        },
        // {
        //     icon: isDark ? workOverSpeedDarkImg : workOverSpeedImg,
        //     label: '作业超速',
        //     value: 0,
        //     unit: '%',
        // },
        // {
        //     icon: isDark ? workOverSpeedTimeDarkImg : workOverSpeedTimeImg,
        //     label: '作业超速时长',
        //     value: 0,
        //     unit: ['时', '分', '秒'],
        // },
    ];

    const handleDateChange = (start, end) => {
        setState({ start, end });
    };
    return (
        <div className="vehicle-base-content" style={{ width: '100%', height: '100%' }}>
            <div className="left">
                <div className="info-container">
                    <TimeInfo value={realTimeInfo.time} />
                    <LocationInfo value={realTimeInfo.location} />
                </div>
                <StatusInfo value={realTimeInfo.status} />
                <VehicleRing />
                <VehicleSpeed value={realTimeInfo.speed} />
                <VehicleDrive
                    percent={realTimeInfo.percent}
                    drive={realTimeInfo.mile}
                    showWork={carType === 'jxh'}
                    work={workMileage}
                />
            </div>
            <div className="right">
                <div className="top">
                    <VMDatePicker
                        value={[state.start, state.end]}
                        onChange={dates => dates && handleDateChange(dates[0], dates[1])}
                        style={{ position: 'absolute', top: 24, right: 32 }}
                    />
                    <div className="info">
                        <SubTabs defaultActiveKey="base">
                            <SubTabPane tab="基础信息" key="base">
                                <BaseInfo data={info} />
                            </SubTabPane>
                            {carType === 'jxh' ? (
                                <SubTabPane
                                    tab="属性信息"
                                    key="info"
                                    style={{ height: 200, overflow: 'auto' }}
                                >
                                    <BaseInfo data={jxhInfo} />
                                </SubTabPane>
                            ) : (
                                <SubTabPane tab="道路许可证" key="permission">
                                    <Carousel>
                                        {permissionInfo.map(info => (
                                            <BaseInfo key={info.code} data={info} />
                                        ))}
                                    </Carousel>
                                </SubTabPane>
                            )}
                        </SubTabs>
                    </div>
                    <div className="stat">
                        <ChartTitle title="统计信息" />
                        <StatCollection items={carType === 'jxh' ? jxhStatData : statData} />
                    </div>
                </div>
                <div className="hr"></div>
                <div className="chart-container">
                    <ChartTitle title={carType === 'jxh' ? '作业分析' : '违规分析'} />
                    {carType === 'jxh' ? (
                        <WorkChart data={workChart || []} />
                    ) : (
                        <StatChart data={statChartInfo || []} />
                    )}
                </div>
            </div>
        </div>
    );
};

BaseContent.propTypes = {
    id: PropTypes.string,
    seed: PropTypes.string,
    carType: 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%" />;
};

const WorkChart = ({ data = [] }) => {
    const { isDark } = useSettings();
    const rateData = data.map(item => (item.rate ? item.rate.toFixed(2) : 0));
    const mileData = data.map(item => (item.work_mileage ? item.work_mileage.toFixed(2) : 0));
    const xAxis = data.map(item => item.work_date || 0);

    const option = {
        tooltip: {
            trigger: 'axis',
        },
        legend: {
            icon: 'circle',
            itemHeight: 8,
            itemWidth: 8,
            itemGap: 14,
            textStyle: {
                fontSize: 14,
                fontFamily: 'PingFangSC-Regular',
                rich: {
                    a: {
                        color: isDark ? 'white' : '#666',
                    },
                    b: {
                        color: isDark ? 'white' : '#222',
                    },
                },
            },
        },
        xAxis: [
            {
                type: 'category',
                data: xAxis,
            },
        ],
        yAxis: [
            {
                type: 'value',
                name: 'km',
                min: 0,
            },
            {
                type: 'value',
                min: 0,
                max: 100,
                axisLabel: {
                    formatter: '{value} %',
                },
            },
        ],
        series: [
            {
                name: '作业里程',
                type: 'bar',
                data: mileData,
            },
            {
                name: '作业率',
                type: 'line',
                data: rateData,
                yAxisIndex: 1,
            },
        ],
    };
    return <VMChart option={option} height={260} width="100%" />;
};
StatChart.propTypes = {
    data: PropTypes.array,
};

WorkChart.propTypes = {
    data: PropTypes.array,
};
export default BaseContent;
