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";

type Props = {
  handleLoading:(val:boolean) => void
}

export default function AntechamberReport({handleLoading}:Props) {
    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 {
            handleLoading(true)
            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 <></>;
}

