import { pollCompareTaskResult, retryCompareTask } from '@/service/api';
import { pollReviewTaskStatus, retryReviewTask } from '@/service/api/reviewTask';

interface PollTask {
  taskId: string | number;
  timer: NodeJS.Timeout | null;
  count: number;
  onSuccess?: (taskId: string | number) => void;
  onError?: (taskId: string | number) => void;
}

class PollManager {
  private tasks: Map<string | number, PollTask> = new Map();
  private maxPollCount = 1000;
  private pollInterval = 10000; // 10

  /**
   * 开始轮询合同对比任务
   *
   * @param taskId 任务ID
   * @param onSuccess 成功回调
   * @param onError 错误回调
   */
  startComparePolling(
    taskId: string | number,
    onSuccess?: (taskId: string | number) => void,
    onError?: (taskId: string | number) => void
  ) {
    // 如果已经在轮询，先停止
    this.stopPolling(taskId);

    const task: PollTask = {
      taskId,
      timer: null,
      count: 0,
      onSuccess,
      onError
    };

    task.timer = setInterval(() => {
      task.count += 1;

      // 超过最大轮询次数，停止轮询
      if (task.count > this.maxPollCount) {
        this.stopPolling(taskId);
        if (onError) {
          onError(taskId);
        }
        return;
      }

      // 查询合同对比任务状态
      pollCompareTaskResult(taskId)
        .then(r => {
          console.log(`轮询合同对比任务 ${taskId} 状态:`, r);
          if (!r.error) {
            // 任务完成（成功或失败）
            if (r.data === 3 || r.data === 4) {
              this.stopPolling(taskId);
              if (onSuccess) {
                onSuccess(taskId);
              }
            }
          } else {
            this.stopPolling(taskId);
            if (onError) {
              onError(taskId);
            }
          }
        })
        .catch(error => {
          console.error(`轮询任务 ${taskId} 出错:`, error);
          this.stopPolling(taskId);
          if (onError) {
            onError(taskId);
          }
        });
    }, this.pollInterval);

    this.tasks.set(taskId, task);
    console.log(`开始轮询合同对比任务 ${taskId}`);
  }

  /**
   * 开始轮询合同审查任务
   *
   * @param taskId 任务ID
   * @param onSuccess 成功回调
   * @param onError 错误回调
   * @param onPreStart
   */
  // eslint-disable-next-line max-params
  startReviewPolling(
    taskId: string | number,
    onSuccess?: (taskId: string | number) => void,
    onError?: (taskId: string | number) => void,
    onPreStart?: () => void
  ) {
    // 如果已经在轮询，先停止
    this.stopPolling(taskId);

    const task: PollTask = {
      taskId,
      timer: null,
      count: 0,
      onSuccess,
      onError
    };

    task.timer = setInterval(() => {
      task.count += 1;

      // 超过最大轮询次数，停止轮询
      if (task.count > this.maxPollCount) {
        this.stopPolling(taskId);
        if (onError) {
          onError(taskId);
        }
        return;
      }

      // 查询合同审查任务状态
      pollReviewTaskStatus(taskId)
        .then(r => {
          console.log(`轮询合同审查任务 ${taskId} 状态:`, r);
          if (!r.error) {
            // 任务完成（成功或失败）
            if (r.data === 3 || r.data === 4) {
              this.stopPolling(taskId);
              if (onSuccess) {
                onSuccess(taskId);
              }
            } else if (r.data === 2) {
              // 操作中，获取审查结果
              onPreStart?.();
            }
          } else {
            this.stopPolling(taskId);
            if (onError) {
              onError(taskId);
            }
          }
        })
        .catch(error => {
          console.error(`轮询合同审查任务 ${taskId} 出错:`, error);
          this.stopPolling(taskId);
          if (onError) {
            onError(taskId);
          }
        });
    }, this.pollInterval);

    this.tasks.set(taskId, task);
    console.log(`开始轮询合同审查任务 ${taskId}`);
  }

  /**
   * 停止轮询任务
   *
   * @param taskId 任务ID
   */
  stopPolling(taskId: string | number) {
    const task = this.tasks.get(taskId);
    if (task && task.timer) {
      clearInterval(task.timer);
      task.timer = null;
      this.tasks.delete(taskId);
      console.log(`停止轮询任务 ${taskId}`);
    }
  }

  /**
   * 检查任务是否正在轮询
   *
   * @param taskId 任务ID
   * @returns 是否正在轮询
   */
  isPolling(taskId: string | number): boolean {
    const task = this.tasks.get(taskId);
    return task !== undefined && task.timer !== null;
  }

  /**
   * 重新执行合同对比差异识别并开始轮询
   *
   * @param taskId 任务ID
   * @param onPreStart 开始前
   * @param onSuccess 成功回调
   * @param onError 错误回调
   * @returns Promise
   */
  // eslint-disable-next-line max-params
  async retryCompareAndPoll(
    taskId: string | number,
    onPreStart?: () => void,
    onSuccess?: (taskId: string | number) => void,
    onError?: (taskId: string | number) => void
  ): Promise<void> {
    try {
      // eslint-disable-next-line @typescript-eslint/no-unused-expressions
      onPreStart && (await onPreStart());
      const res = await retryCompareTask(taskId);
      if (!res.error) {
        window.$message?.success('执行成功，请稍等结果更新...');
        this.startComparePolling(taskId, onSuccess, onError);
      } else if (onError) {
        onError(taskId);
      }
    } catch (error) {
      console.error('重新执行差异识别失败:', error);
      if (onError) {
        onError(taskId);
      }
    }
  }

  /**
   * 重新执行合同审查并开始轮询
   *
   * @param taskId 任务ID
   * @param params 重试参数
   * @param onPreStart 开始前
   * @param onSuccess 成功回调
   * @param onError 错误回调
   * @returns Promise
   */
  // eslint-disable-next-line max-params
  async retryReviewAndPoll(
    taskId: string | number,
    params: { type: string },
    onPreStart?: () => void,
    onSuccess?: (taskId: string | number) => void,
    onError?: (taskId: string | number) => void
  ): Promise<void> {
    try {
      // eslint-disable-next-line @typescript-eslint/no-unused-expressions
      if (onPreStart) {
        setTimeout(() => {
          onPreStart();
        }, 3000);
      }

      const res = await retryReviewTask(taskId, params);
      if (!res.error) {
        window.$message?.success('执行成功，请稍等结果更新...');
        this.startReviewPolling(taskId, onSuccess, onError, onPreStart);
      } else if (onError) {
        onError(taskId);
      }
    } catch (error) {
      console.error('重新执行审查识别失败:', error);
      if (onError) {
        onError(taskId);
      }
    }
  }

  /**
   * 获取所有正在轮询的任务ID
   *
   * @returns 正在轮询的任务ID数组
   */
  getPollingTasks(): (string | number)[] {
    return Array.from(this.tasks.keys());
  }

  /** 停止所有轮询任务 */
  stopAllPolling() {
    for (const taskId of this.tasks.keys()) {
      this.stopPolling(taskId);
    }
  }

  /** 销毁管理器，清理所有资源 */
  destroy() {
    this.stopAllPolling();
    this.tasks.clear();
  }
}

// 创建单例实例
export const pollManager = new PollManager();

// 在页面卸载时清理资源
if (typeof window !== 'undefined') {
  window.addEventListener('beforeunload', () => {
    pollManager.destroy();
  });
}
