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

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

export default function AntechamberFile({handleLoading}:Props) {
  const [searchParams] = useSearchParams();
  const talentTypeId = searchParams.get("talentTypeId") || "";
  const userId = searchParams.get("userId") || "";
  const token = searchParams.get("token") || "";
  const { toast } = useToast();
  const { getSignal } = useAbortController();
  const { setHasHandledReport,hasHandledReport } = useContext(ReportContext);
  const { handleConnect } = useContext(RealtimeClientContext);

  const useFileFetch = async () => {    
    handleLoading(true)
    const result = await fetchSpecialFile({
      params: { Type:talentTypeId, UserId:userId},
      options: {
        signal: getSignal(),
        headers: { Authorization: `Bearer ${token}` },
      },
    });
    
    if (result.message) {
      toast({
        title: result.message,
      });
    }
    let resp = result.result as FileInfo;
    
    handleConnect({
      fileInfo: {url: resp.url,tableName:"我的特长报告"},
    }).then(() => {
      setHasHandledReport(true);
    });
  };


  useEffect(() => {
    
    if (talentTypeId && userId && !hasHandledReport) {
      useFileFetch();
    }
  }, [talentTypeId, userId,hasHandledReport]);


  return <></>;
}
