import { useMeetingState } from "@tingwujs/components";
import { useRequest } from "ahooks";
import { useCallback, useEffect, useState } from "react";
import { getTaskApi } from "@tingwujs/service";

const useMeetingGetTaskStatus = ({ callback }: { callback: (result: any) => void }) => {
  const { updateStore: updateMeetingStore } = useMeetingState();
  const [isCompleted, setIsCompleted] = useState(false);
  // 轮训任务状态
  const getTaskStatus = useCallback(async (taskId = "") => {
    if (!taskId) return;
    const result = await getTaskApi(taskId);
    /**
      ‒ 0 -> 成功
      ‒ 1 -> 进行中
      ‒ 2 -> 失败
      ‒ 3 -> 录音中的转写
     */
    if ([2, 3, 0].includes(result.output?.status)) {
      setIsCompleted(true);
      updateMeetingStore(draft => {
        draft.createTaskOutput.status = result.output?.status;
      });
    }
    await callback?.(result);
  }, []);

  const { run: runGetTaskStatus, cancel } = useRequest(getTaskStatus, {
    pollingInterval: 2000, // 每2秒轮询一次
    pollingWhenHidden: false,
    manual: false,
    ready: !isCompleted, // 且任务未完成时才轮询
  });

  // 任务完成后停止轮询
  useEffect(() => {
    if (!isCompleted) {
      cancel();
    }
  }, [isCompleted, cancel]);

  const onReset = useCallback(() => {
    setIsCompleted(false);
  }, []);

  return { runGetTaskStatus, cancel, onReset };
};

export default useMeetingGetTaskStatus;
