import { message } from "antd";
import dayjs from "dayjs";
import { createContext, useContext, useState } from "react";
import { env } from "@web/src/env";
import { api } from "@nice/client";
interface QuickFileContextType {
    saveCodeRecord: (data: ShareCodeResponse, recordName: string) => void;
    handleValidSuccess: (fileUrl: string, fileName: string) => void;
    isGetingFileId: boolean;
    downloadCode: string | null;
    setDownloadCode: (code: string | null) => void;
    refetchShareCodeWithResource: () => Promise<{ data: any }>;
    isLoading: boolean;
    downloadResult: ShareCodeResponse | null;
}
export interface ShareCodeResponse {
    id?: string;
    code?: string;
    fileName?: string;
    expiresAt?: Date;
    canUseTimes?: number;
    resource?: {
        id: string;
        type: string;
        url: string;
        meta: ResourceMeta
    }
}
interface ResourceMeta {
    filename: string;
    filetype: string;
    size: string;
}

export const QuickFileContext = createContext<QuickFileContextType | null>(null);

export const QuickFileProvider = ({ children }: { children: React.ReactNode }) => {
    const [isGetingFileId, setIsGetingFileId] = useState(false);
    const [downloadCode, setDownloadCode] = useState<string | null>(null);
    const saveCodeRecord = (data: ShareCodeResponse, recordName: string) => {
        const newRecord = {
            id: `${Date.now()}`, // 生成唯一ID
            code: data.code,
            expiresAt: dayjs(data.expiresAt).format('YYYY-MM-DD HH:mm:ss'),
            fileName: data.fileName || `文件_${data.code}`,
            canUseTimes: data.canUseTimes,
            resource: {
                id: data.resource.id,
                type: data.resource.type,
                url: data.resource.url,
                meta: {
                    size: data.resource.meta.size,
                    filename: data.resource.meta.filename,
                    filetype: data.resource.meta.filetype
                }
            }
        };
        // 获取已有记录并添加新记录
        const existingGeneratorRecords = localStorage.getItem(recordName);
        const generatorRecords = existingGeneratorRecords ? JSON.parse(existingGeneratorRecords) : [];
        generatorRecords.unshift(newRecord); // 添加到最前面
        localStorage.setItem(recordName, JSON.stringify(generatorRecords));
    }
    const handleValidSuccess = async (fileUrl: string, fileName: string) => {
        setIsGetingFileId(true);
        try {
            const downloadUrl = `http://${env.SERVER_IP}:${env.FILE_PORT}/uploads/${fileUrl}`;
            const link = document.createElement('a');
            link.href = downloadUrl;
            link.download = fileName;
            link.target = '_blank';
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
            message.success('文件下载开始');
        } catch (error) {
            console.error('下载失败:', error);
            message.error('文件下载失败');
        } finally {
            setIsGetingFileId(false);
        }
    };
    const { data: downloadResult, isLoading, refetch: refetchShareCodeWithResource } = api.shareCode.getFileByShareCode.useQuery(
        { code: downloadCode?.trim() },
        {
            enabled: false
        }
    )
    return <>
        <QuickFileContext.Provider value={{
            saveCodeRecord,
            handleValidSuccess,
            isGetingFileId,
            downloadCode,
            setDownloadCode,
            refetchShareCodeWithResource,
            isLoading,
            downloadResult: downloadResult as any as ShareCodeResponse
        }}>
            {children}
        </QuickFileContext.Provider>
    </>
};

export const useQuickFileContext = () => {
    const context = useContext(QuickFileContext);
    if (!context) {
        throw new Error("useQuickFileContext must be used within a QuickFileProvider");
    }
    return context;
};