import * as React from 'react';
import { Link, useLocation, useNavigate } from 'react-router-dom';
import { Breadcrumb as AntdBreadcrumb, Button, Progress } from 'antd';
import { PlusOutlined, QuestionCircleOutlined, LayoutOutlined } from '@ant-design/icons';
import { State } from '../types';
import router from '@/router';
import LocalStorage from '@/LocalStorage';
import { apis } from '@/apis';

interface Props {
    routerMatchList: State['routerMatchList'],
    onKnowledgeLibCreate?: () => void; // 知识库创建回调
    ref2?: React.RefObject<any>;
    ref4?: React.RefObject<any>;
};

const Breadcrumb: React.FC<Props> = (props: Props) => {
    const { routerMatchList, onKnowledgeLibCreate, ref2, ref4 } = props;
    const [ragCreateFlag, setRagCreateFlag] = React.useState<boolean>(false);
    const [knowledgeLibCreate, setKnowledgeLibCreate] = React.useState<boolean>(false);
    const [evaluationTaskCreate, setEvaluationTaskCreate] = React.useState<boolean>(false);
    const [datasetManagementCreate, setDatasetManagementCreate] = React.useState<boolean>(false);
    const navigate = useNavigate()
    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)
        }
    }



    React.useEffect(() => {
        setRagCreateFlag(LocalStorage.getStatusFlag('appCenter:questionAnswer:add'));
        setKnowledgeLibCreate(LocalStorage.getStatusFlag('knowledge:knowledgeLib:add'));
        setEvaluationTaskCreate(LocalStorage.getStatusFlag('evaluationTool:evaluationTask:add'));
        setDatasetManagementCreate(LocalStorage.getStatusFlag('evaluationTool:datasetManagement:add'));
        if (LocalStorage.getToken()) {
            onGetTenantSize()
        }
    }, [])
    const userGuide = () => {
        return (
            <>
                <div className='flex items-center mr-[15px]'>
                    <p className='w-auto'>知识库空间已用：</p>
                    <Progress style={{ width: '150px', marginRight: '8px' }} percent={percent?.toFixed(2)} />
                    <p>空间总量:{tenantDetail.tenantSize}G</p>
                </div>
                <p className='flex items-center cursor-pointer'><QuestionCircleOutlined className='mr-[5px]' />使用指南</p>
            </>
        )
    }
    // 根据当前路由生成动态按钮
    const getDynamicButton = () => {
        const path = location.pathname;
        // 问答应用列表页面
        if (path === '/appCenter/questionAnswer/list') {
            return (
                <div className='flex items-center'>
                    {userGuide()}
                    {ragCreateFlag && <Button
                        ref={ref4}
                        className='ml-[10px]'
                        type="primary"
                        icon={<PlusOutlined />}
                        onClick={() => {
                            navigate(`/appCenter/questionAnswer/create`);
                        }}
                    >
                        创建RAG应用
                    </Button>}
                </div>
            );
        }

        // 知识库列表页面
        if (path.includes('/knowledge/knowledgeLib')) {
            return (
                <div className='flex items-center'>
                    {userGuide()}
                    {knowledgeLibCreate && path === '/knowledge/knowledgeLib' && <Button
                        ref={ref2}
                        className='ml-[10px]'
                        type="primary"
                        icon={<PlusOutlined />}
                        onClick={() => {
                            // 触发自定义事件，让页面组件监听并处理
                            const event = new CustomEvent('knowledgeLibCreate', {
                                detail: { platform: 'deepseek' }
                            });
                            window.dispatchEvent(event);
                        }}
                    >
                        创建知识库
                    </Button>}
                </div>
            );
        }
        // 评测任务列表页面
        if (path === '/evaluationTool/evaluationTask' && evaluationTaskCreate) {
            return (
                <>
                    <Button
                        type="primary"
                        icon={<PlusOutlined />}
                        onClick={() => {
                            // 触发自定义事件，让页面组件监听并处理
                            const event = new CustomEvent('evaluationTask', {
                                detail: { platform: 'Task' }
                            });
                            window.dispatchEvent(event);
                        }}
                    >
                        创建评测任务
                    </Button>
                </>
            );
        }
        // 创建数据集页面
        if (path === '/evaluationTool/datasetManagement' && datasetManagementCreate) {
            return (
                <Button
                    type="primary"
                    icon={<PlusOutlined />}
                    onClick={() => {
                        // 触发自定义事件，让页面组件监听并处理
                        const event = new CustomEvent('datasetManagement', {
                            detail: { platform: 'Management' }
                        });
                        window.dispatchEvent(event);
                    }}
                >
                    创建数据集
                </Button>
            );
        }
        if (path === '/deepseek/audit') {
            return (
                <Button
                    type="primary"
                    icon={<LayoutOutlined />}
                    onClick={() => {
                        // 触发自定义事件，让页面组件监听并处理
                        const event = new CustomEvent('auditHistory', {
                            detail: { platform: 'auditHistory' }
                        });
                        window.dispatchEvent(event);
                    }}
                >
                    审核历史
                </Button>
            );
        }

        // 其他页面不显示按钮
        return null;
    };

    const items = routerMatchList.map((item, index) => {
        const color = (index === 0 || index < routerMatchList.length - 1) ? '#595959' : '#1a1a1a';
        return {
            key: index,
            title: (item.path !== '/knowledge/knowledgeLib' && item.path.includes('/knowledge/knowledgeLib')) ? item.breadcrumbName : <Link
                style={{ color: color }}
                to={item.path}>
                {item.breadcrumbName}
            </Link>,
        }
    });

    return (
        <div className='breadcrumb-container'>
            <AntdBreadcrumb className='breadcrumb' items={items} />
            <div className='breadcrumb-actions'>
                {getDynamicButton()}
            </div>
        </div>
    );
};

export default Breadcrumb;