import { useContext, useEffect } from "react";
import { ReportContext } from "../Provider/ReportResolveProvider";
import { fetchReport } from "@/apis/user";
import { useSearchParams } from "react-router-dom";
import { useAbortController } from "@/hooks/useAbortController";
import { RealtimeClientContext } from "../Provider/RealtimeClientProvider";

export default function AntechamberReport() {
    const [searchParams] = useSearchParams();
    const token = searchParams.get("token") || '';
    const reportId = searchParams.get("reportId") || '';
    const reportType = searchParams.get("reportType") || '';
    const { setHasHandledReport,hasHandledReport } = useContext(ReportContext);

    const { getSignal } = useAbortController();

    const { handleConnect } = useContext(RealtimeClientContext);

    const getReport = async () => {
        try {
          const { result, message } = await fetchReport({ 
            params:{Type:reportType,Id:reportId}, 
            options: { 
              signal: getSignal(),
              headers: {
                "Authorization": `Bearer ${encodeURIComponent(token)}`
              } 
            } 
          });
          if (message) {
            console.log(message);
          } else {
            handleConnect({initMessage:result as string});
            setHasHandledReport(true)
          }
        } catch (error: any) {
          if (error.name !== 'AbortError') {
            console.error('获取报告失败:', error);
          }
        }
      }
    useEffect(() => {
        if(reportId && reportType && !hasHandledReport){
          getReport();
        }
      }, [reportId, reportType,hasHandledReport]);

  return <></>;
}

