import React, { useState, useEffect, useRef } from 'react';
import { Chart } from '@antv/g2';
import { useHomeStore } from './store';
import { Select } from 'antd';

import RagApplicationsTable from './components/RagApplicationsTable'
import RagApplicationsModel from './components/RagApplicationsModel'
import RagKnowledgModel from './components/RagKnowledgModel'
import { apis } from '@/apis';
import './style.less'
const App: React.FC = () => {

    const {
        monthDay,
        topData,
        onlineUserData,
        conversationData,
        conversationDetailData,
        overviewTokenData,
        init,
    } = useHomeStore();

    // 图表容器引用
    const allSessionsChartRef = useRef<HTMLDivElement>(null);
    const activeUsersChartRef = useRef<HTMLDivElement>(null);
    const avgInteractionsChartRef = useRef<HTMLDivElement>(null);
    const tokenSpeedChartRef = useRef<HTMLDivElement>(null);
    const [tenantDetail, setTenantDetail] = React.useState<any>({})
    const [percent, setPercent] = React.useState<any>(0)
    const onGetTenantSize = async () => {
        const res: any = await apis.getTenantSize()
        if (res.code === 200) {
            setTenantDetail(res.data)
            const num = (res.data.ossSize / res.data.tenantSize) * 100
            setPercent(num)
        }
    }

    // 初始化图表的函数
    const initChart = (
        containerRef: React.RefObject<HTMLDivElement>,
        data: any[],
        title: string,
        color: string,
        tickInterval: number = 0
    ) => {
        if (!containerRef.current) return;

        const chart = new Chart({
            container: containerRef.current,
            autoFit: true,
            height: 250,
        });

        chart.data(data);

        // 面积图
        chart.area()
            .position(`${monthDay}*value`)
            .color(color)
            .style({ fillOpacity: 0.2 });

        // 折线图
        chart.line()
            .position(`${monthDay}*value`)
            .color(color)
            .size(2);

        chart.scale('value', {
            min: 0,
            tickInterval: tickInterval,
        });

        chart.axis(monthDay, {
            // title: false,
        });

        chart.render();

        // 返回销毁函数
        return () => chart.destroy();
    };

    // 初始化所有图表
    useEffect(() => {
        init()
        onGetTenantSize()
    }, []);

    useEffect(() => {
        // 第二个图表 - 活跃用户数 (绿色)
        const cleanup2 = initChart(
            activeUsersChartRef,
            state.onlineUserData,
            '活跃用户数',
            '#52C41A',
            1
        );
        // 清理函数
        return () => {
            cleanup2?.();
        };
    }, [state.onlineUserData])
    useEffect(() => {
        // 第二个图表 - 全部会话数 (绿色)
        const cleanup1 = initChart(
            allSessionsChartRef,
            state.conversationData,
            '全部会话数',
            '#1890FF',
            0
        );
        // 清理函数
        return () => {
            cleanup1?.();
        };
    }, [state.conversationData])
    useEffect(() => {
        // 第三个图表 - 平均会话互动数 (绿色)
        const cleanup3 = initChart(
            avgInteractionsChartRef,
            state.conversationDetailData,
            '平均会话互动数',
            '#FA8C16',
            0
        );
        // 清理函数
        return () => {
            cleanup3?.();
        };
    }, [state.conversationDetailData])
    useEffect(() => {
        // 第四个图表 - Token输出速度 (红色)
        const cleanup4 = initChart(
            tokenSpeedChartRef,
            state.overviewTokenData,
            'Token输出速度',
            '#F5222D',
            0
        );
        // 清理函数
        return () => {
            cleanup4?.();
        };
    }, [state.overviewTokenData])


    const [visible, setVisible] = useState(false);
    const [visibleKnow, setVisibleKnow] = useState(false);
    const gradientPresets = [
        'bg-gradient-to-r from-[#95D3F4] to-white',
        'bg-gradient-to-r from-[#9ABEFF] to-white',
        'bg-gradient-to-r from-[#87CEFA] to-white',
    ];

    const statusRingMap: Record<any, string> = {
        wait: 'ring-1 ring-slate-200',
        process: 'ring-2 ring-[#4195E5]',
        finish: 'ring-2 ring-emerald-300',
    };

    const statusTitleMap: Record<any, string> = {
        wait: 'text-gray-900',
        process: 'text-[#1d5fbf]',
        finish: 'text-emerald-700',
    };
    const cx = (...classNames: Array<string | false | undefined>) => classNames.filter(Boolean).join(' ');
    const gradient = gradientPresets[0 % gradientPresets.length];

    return (
        <div className="flex flex-col space-y-4 mt-6 px-6">
            <div className="grid grid-cols-1 md:grid-cols-4 gap-6">
                {/* 接口调用总量 */}
                <div className={cx(
                            'relative flex-1 rounded-lg p-4 shadow-md transition-all duration-200 flex flex-col justify-center',
                            gradient,
                            statusRingMap[1],
                            'cursor-pointer hover:-translate-y-1',
                        )}>
                    <div className="text-gray-500 text-sm">接口调用总量</div>
                    <div className="text-2xl font-bold text-green-700 mt-1">
                        {topData.totalNum}
                    </div>
                    <div className="text-green-600 text-xs mt-1">较上月 {topData.bjNum>0 ? '↑+' + topData.bjNum : '↓' +topData.bjNum}</div>
                </div>

                {/* 今日调用量 */}
                <div className={cx(
                            'relative flex-1 rounded-lg p-4 shadow-md transition-all duration-200 flex flex-col justify-center',
                            gradient,
                            statusRingMap[1],
                            'cursor-pointer hover:-translate-y-1',
                        )}>
                    <div className="text-gray-500 text-sm">今日调用量</div>
                    <div className="text-2xl font-bold text-blue-600 mt-1">
                        {topData.todayNum}
                    </div>
                    <div className="text-green-600 text-xs mt-1">📈 较上日{topData?.bjYNum}</div>
                </div>

                {/* 接口成功率 */}
                {/* className="bg-[#76D169] rounded-lg shadow-sm border p-4"  */}
                <div className={cx(
                            'relative flex-1 rounded-lg p-4 shadow-md transition-all duration-200 flex flex-col justify-center',
                            gradient,
                            statusRingMap[1],
                            'cursor-pointer hover:-translate-y-1',
                        )}>
                    <div className="text-gray-500 text-sm">接口成功率</div>
                    <div className="text-2xl font-bold text-blue-600 mt-1">
                        {Number(topData.successRate) * 100}%
                    </div>
                    <div className="text-green-600 text-xs mt-1">
                        运行状态 • 正常
                        {/* {Number(topData.successRate) * 100>95&&'运行状态 • 极佳'}
                        {Number(topData.successRate) * 100>95&&'运行状态 • 极佳'} */}
                    </div>
                </div>
                <div className={cx(
                            'relative flex-1 rounded-lg p-4 shadow-md transition-all duration-200 flex flex-col justify-center',
                            gradient,
                            statusRingMap[1],
                            'cursor-pointer hover:-translate-y-1',
                        )}>
                    <div className="text-gray-500 text-sm">知识库空间使用率</div>
                    <div className="text-2xl font-bold text-blue-600 mt-1">
                        {(percent).toFixed(2)}%
                    </div>
                    <div className="text-green-600 text-xs mt-1">空间总量：{tenantDetail.tenantSize}G</div>
                </div>
            </div>
            <div>
                <Select
                    defaultValue="day"
                    style={{ width: 120 }}
                    onChange={(e) => {
                        onSetMonthDay(e)
                        onOverviewData()
                    }}
                    options={[
                        { value: 'day', label: '日' },
                        { value: 'month', label: '月' }
                    ]}
                >
                </Select>
            </div>

            {/* 四个图表，两列布局 */}
            <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                {/* 全部会话数图表 */}
                <div className="bg-white rounded-lg shadow-sm border p-4">
                    <div className="text-gray-700 font-medium mb-2">全部会话数</div>
                    <div ref={allSessionsChartRef} style={{ width: '100%', height: '250px' }} />
                </div>

                {/* 活跃用户数图表 */}
                <div className="bg-white rounded-lg shadow-sm border p-4">
                    <div className="text-gray-700 font-medium mb-2">活跃用户数</div>
                    <div ref={activeUsersChartRef} style={{ width: '100%', height: '250px' }} />
                </div>

                {/* 平均会话互动数图表 */}
                <div className="bg-white rounded-lg shadow-sm border p-4">
                    <div className="text-gray-700 font-medium mb-2">平均会话互动数</div>
                    <div ref={avgInteractionsChartRef} style={{ width: '100%', height: '250px' }} />
                </div>

                {/* Token输出速度图表 */}
                <div className="bg-white rounded-lg shadow-sm border p-4">
                    <div className="text-gray-700 font-medium mb-2">Token输出速度（token/秒）</div>
                    <div ref={tokenSpeedChartRef} style={{ width: '100%', height: '250px' }} />
                </div>
            </div>
            <RagApplicationsTable onOpenApp={() => {
                setVisible(true)
            }} onOpenKnow={() => {
                setVisibleKnow(true)
            }} />
            <RagApplicationsModel visible={visible} onCancel={() => {
                setVisible(false)
            }} />
            <RagKnowledgModel visible={visibleKnow} onCancel={() => {
                setVisibleKnow(false)
            }} />
        </div>
    );
};

export default App;