import React, { useState } from 'react';
import ReactEcharts from 'echarts-for-react';
import VmSubTitle from '../../../vm-sub-title';
import VmButton from '../../../vm-button';
import {Gauge1, Line1, Line1Props} from '../../../vm-charts';
import { overViewService } from '../../api';
import type {AlarmByTypeResp, AlarmByDateResp} from '../../types'
import groupBy from "lodash/groupBy";

const getPieOption = (data: AlarmByTypeResp[]) => {
    return {
        tooltip: {
            trigger: 'item',
        },
        legend: {
            top: 'center',
            left: '35%',
            type: 'scroll',
            orient: 'vertical',
            formatter: (name: string) => {
                const obj = data?.find?.(item => item.alarmTypeName === name);
                return `{a|${name}}{a|${obj?.count || 0}次}{a|均值：${obj?.countAvg || 0}次}`;
            },
            textStyle: {
                color: '#fff',
                rich: {
                    a: {
                        width: 60,
                    },
                },
            },
        },
        series: [
            {
                name: '事件类型分布',
                type: 'pie',
                radius: ['50%', '80%'],
                center: ['15%', '50%'],
                avoidLabelOverlap: false,
                labelLine: {
                    show: false,
                },
                label: {
                    show: false,
                },
                data: data.map(item => ({
                    name: item.alarmTypeName,
                    value: item.count,
                }))
            },
        ],
    };
};

interface OverViewRightBottomProps {
    classPrefix?: string;
    id: string;
}

enum PieCharType {
    SJLX = '事件类型分布',
    QS = '近一周趋势',
}

function getMinHundred(num: number) {
    return Math.ceil(num / 100) * 100 || 100;
}
function transferLineData(data: AlarmByDateResp[] = []): Line1Props {
    const groupByThrowPoint = groupBy(data || [], 'throwPointId');
    const groupByDay = groupBy(data || [], 'day');
    const lineData = [];
    for (const key in groupByThrowPoint) {
        const item = (groupByThrowPoint[key] as AlarmByDateResp[]);
        lineData.push({
            name: item[0].alarmTypeName || '',
            data: item.map(item => item.count || 0),
        });
    }
    // 去除日期中的年
    const xAxis = Object.keys(groupByDay).map(item => item.substring(5))
    return { xAxis, data: lineData };
}


const RightBottom: React.FC<OverViewRightBottomProps> = ({ classPrefix, id }) => {
    const [pieChartType, setPieChartType] = useState<PieCharType>(PieCharType.SJLX);
    // 事件类型分布
    const alarmByTypeData = overViewService.alarmSumByType({ housingEstateId: id });
    // 近一周趋势
    const alarmByDateData = overViewService.alarmSumByDate({ housingEstateId: id });
    // 工单处理效率
    const efficiencyData = overViewService.resolveEfficiency({
        housingEstateId: id,
    });
    return (
        <div className={`${classPrefix}-rightbottom`}>
            <VmSubTitle title="AI工单" />
            <div className={`${classPrefix}-rightbottom--buttons`}>
                <VmButton
                    onClick={() => setPieChartType(PieCharType.SJLX)}
                    name="事件类型分布"
                    active={pieChartType === PieCharType.SJLX}
                    style={{ marginRight: 10 }}
                />
                <VmButton
                    onClick={() => setPieChartType(PieCharType.QS)}
                    name="近一周趋势"
                    active={pieChartType === PieCharType.QS}
                />
            </div>
            <div className={`${classPrefix}-rightbottom--pie`}>
                {
                    pieChartType === PieCharType.SJLX &&  <ReactEcharts option={getPieOption(alarmByTypeData || [])} style={{ height: 150 }} />
                }
                {
                    pieChartType === PieCharType.QS &&  <Line1 {...transferLineData(alarmByDateData)} style={{ height: 150 }}/>
                }
            </div>
            <VmSubTitle title="工单处理效率" />
            <div className={`${classPrefix}-rightbottom--gauges`}>
                <div className="gauges-chart">
                    <Gauge1
                        name="AI工单关闭率"
                        unit="%"
                        min={0}
                        max={100}
                        num={efficiencyData?.closeRate || 0}
                        average={efficiencyData?.closeRateAverage || 0}
                    />
                </div>
                <div className="gauges-chart">
                    <Gauge1
                        name="AI工单处理时长"
                        unit="分"
                        min={0}
                        max={getMinHundred(
                            Math.max(
                                efficiencyData?.resolveMinute || 0,
                                efficiencyData?.resolveMinuteAverage || 0,
                            ),
                        )}
                        num={efficiencyData?.resolveMinute || 0}
                        average={efficiencyData?.resolveMinuteAverage || 0}
                    />
                </div>
                <div className="gauges-chart">
                    <Gauge1
                        name="AI工单及时关闭率"
                        unit="%"
                        min={0}
                        max={100}
                        num={efficiencyData?.closeInTimeRate || 0}
                        average={efficiencyData?.closeInTimeRateAverage || 0}
                    />
                </div>
            </div>
        </div>
    );
};

export default RightBottom;
