import { useEffect, useRef, useCallback } from 'react';
import Taro from '@tarojs/taro';
import { AsyncTaskManager, TaskStatus, TaskConfig } from '../utils/AsyncTaskManager';
import { PlatformFactory } from '../platforms/factory';
/**
 * 平台类型枚举
 */
export enum PlatformType {
  WECHAT = 'wechat', // 微信小程序 - 腾讯微信生态
  ALIPAY = 'alipay', // 支付宝小程序 - 蚂蚁金服生态
  BAIDU = 'baidu', // 百度智能小程序 - 百度生态
  BYTEDANCE = 'bytedance', // 字节跳动小程序 - 抖音、今日头条等
  JD = 'jd', // 京东小程序 - 京东购物生态
  QQ = 'qq', // QQ小程序 - 腾讯QQ生态
  FEISHU = 'feishu', // 飞书小程序 - 企业办公生态
  KUAISHOU = 'kuaishou', // 快手小程序 - 快手短视频生态
  H5 = 'h5', // H5网页版 - 浏览器端应用
  RN = 'rn', // React Native应用 - 原生移动应用
}

/**
 * 审核状态枚举
 */
export enum AuditStatus {
  PENDING = 'pending', // 待审核
  PROCESSING = 'processing', // 审核中
  COMPLETED = 'completed', // 审核完成
  FAILED = 'failed', // 审核失败
  TIMEOUT = 'timeout', // 审核超时
}

/**
 * 审核结果枚举
 */
export enum AuditConclusion {
  PASS = 'pass', // 通过
  REJECT = 'reject', // 拒绝
  REVIEW = 'review', // 人工复审
  UNCERTAIN = 'uncertain', // 不确定
}

/**
 * 图片审核结果接口
 */
export interface ImageAuditResult {
  taskId: string;
  platform?: PlatformType;
  status: AuditStatus;
  conclusion?: AuditConclusion;       // 审核结果
  imageUrl: string;
  result?: {
    safe?: boolean;                    // 内容是否安全
    score?: number;                   // 审核分数
    riskLevel?: 'low' | 'medium' | 'high'; // 风险等级
    categories?: Array<{              // 违规分类
      name: string;
      score: number;
    }>;
    suggestion?: 'pass' | 'review' | 'block'; // 建议操作
    details?: string;                 // 详细信息
  };
  processingTime?: number;
  timestamp: number;
  errorMessage?: string;              // 错误信息（失败时）
}

/**
 * 图片审核任务提交参数
 */
export interface ImageAuditParams {
  imageUrl: string;                   // 图片URL
  platform?: PlatformType;           // 平台类型（可选，自动检测）
  options?: {
    maxSize?: number;                 // 最大图片大小(KB)
    quality?: number;                 // 压缩质量 0-100
    enableCache?: boolean;            // 是否启用缓存
    timeout?: number;                 // 自定义超时时间(毫秒)
  };
}

/**
 * 图片内容审核任务管理器 Hook
 * 专门用于管理图片内容审核相关的异步任务
 */
export function useImageDetectionTaskManager() {
  const taskManagerRef = useRef<AsyncTaskManager | null>(null);
  const auditCacheRef = useRef<Map<string, ImageAuditResult>>(new Map());
  const currentPlatform = useRef<PlatformType>(getCurrentPlatform());

  useEffect(() => {
    // 初始化任务管理器
    const storage = {
      setStorage: Taro.setStorage,
      getStorage: Taro.getStorage
    };

    taskManagerRef.current = new AsyncTaskManager(storage);

    // 设置图片审核任务状态检查函数
    taskManagerRef.current.setStatusChecker(async (taskId: string) => {
      try {
        const platform = currentPlatform.current;
        const baseUrl = `https://sd2s2bl25ni4n75na2bog.apigateway-cn-beijing.volceapi.com`;
        const apiUrl = `${baseUrl}/api/v1/content-moderation/${platform}/result/${taskId}`;

        const response = await Taro.request({
          url: apiUrl,
          method: 'GET',
          header: {
            'Authorization': `Bearer ${Taro.getStorageSync('access_token')}`,
            'Content-Type': 'application/json'
          }
        });
        if (![200, 201].includes(response.statusCode)) {
          throw new Error(`提交图片审核任务失败: ${response.data?.message || '未知错误'}`);
        }
        const data = response.data;
        const code = data?.code;
        if (code !== 200) {
          throw new Error(`提交图片审核任务失败: ${response.data?.message || '未知错误'}`);
        }
        const { status, conclusion } = data.data;
        // 映射审核状态到任务状态
        const taskStatus = mapAuditStatusToTaskStatus(status as AuditStatus);
        if (status === AuditStatus.COMPLETED) {
          const auditResult: ImageAuditResult = {
            taskId,
            platform,
            status,
            conclusion: conclusion as AuditConclusion,
            imageUrl: '', // 从任务数据中获取
            result: response.data.result,
            processingTime: response.data.processingTime,
            timestamp: Date.now()
          };
          console.log(`task status: `, auditResult)
          // 使用 taskId 作为唯一标识，这样 onSuccess 回调可以找到结果
          const taskCacheKey = `task_${taskId}`;
          auditCacheRef.current.set(taskCacheKey, auditResult);
        }
        return taskStatus;
      } catch (error) {
        console.error('检查图片审核任务状态失败:', error);
        throw error;
      }
    });

    // 恢复任务
    taskManagerRef.current.resumeTasks();

    return () => {
      if (taskManagerRef.current) {
        taskManagerRef.current.pausePolling();
      }
    };
  }, []);

  // 应用前后台切换处理
  useEffect(() => {
    const handleAppShow = () => {
      taskManagerRef.current?.activatePolling();
    };

    const handleAppHide = () => {
      taskManagerRef.current?.pausePolling();
    };

    Taro.onAppShow(handleAppShow);
    Taro.onAppHide(handleAppHide);

    return () => {
      Taro.offAppShow?.(handleAppShow);
      Taro.offAppHide?.(handleAppHide);
    };
  }, []);

  /**
   * 提交图片审核任务
   */
  const submitAuditTask = useCallback(async (
    params: ImageAuditParams,
    onProgress?: (status: TaskStatus, progress?: number) => void,
    onSuccess?: (result: ImageAuditResult) => void,
    onError?: (error: Error) => void
  ): Promise<string> => {
    if (!taskManagerRef.current) {
      throw new Error('图片审核任务管理器未初始化');
    }

    const { imageUrl, platform, options = {} } = params;
    const targetPlatform = platform || currentPlatform.current;

    // H5平台跳过审核，直接返回通过结果
    if (targetPlatform === PlatformType.H5) {
      const mockTaskId = `h5_mock_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
      const h5Result: ImageAuditResult = {
        taskId: mockTaskId,
        platform: PlatformType.H5,
        status: AuditStatus.COMPLETED,
        conclusion: AuditConclusion.PASS,
        imageUrl,
        result: {
          safe: true,
          score: 100,
          riskLevel: 'low',
          categories: [],
          suggestion: 'pass',
          details: 'H5平台跳过审核，自动通过'
        },
        processingTime: 0,
        timestamp: Date.now()
      };
      
      // 异步触发回调，模拟真实的审核流程
      setTimeout(() => {
        onProgress?.(TaskStatus.SUCCESS);
        onSuccess?.(h5Result);
      }, 100);
      
      return mockTaskId;
    }

    // 检查缓存
    const cacheKey = `${targetPlatform}_${imageUrl}`;
    if (options.enableCache && auditCacheRef.current.has(cacheKey)) {
      const cachedResult = auditCacheRef.current.get(cacheKey)!;
      setTimeout(() => onSuccess?.(cachedResult), 0);
      return cachedResult.taskId;
    }

    try {
      // 预处理图片（如果需要）
      const processedImageUrl = await preprocessImage(imageUrl, options);

      // 提交审核任务
      const baseUrl = `https://sd2s2bl25ni4n75na2bog.apigateway-cn-beijing.volceapi.com`;
      const apiUrl = `${baseUrl}/api/v1/content-moderation/${targetPlatform}/audit-image`;

      const response = await Taro.request({
        url: apiUrl,
        method: 'POST',
        header: {
          'Authorization': `Bearer ${Taro.getStorageSync('access_token')}`,
          'Content-Type': 'application/json'
        },
        data: {
          imageUrl: processedImageUrl
        }
      });

      if (![200, 201].includes(response.statusCode)) {
        throw new Error(`提交图片审核任务失败: ${response.data?.message || '未知错误'}`);
      }
      const data = response.data;
      const code = data?.code;
      if (code !== 200) {
        throw new Error(`提交图片审核任务失败: ${response.data?.message || '未知错误'}`);
      }
      const task = data.data;
      console.log(`response data is: `, task)
      const { taskId } = task;

      // 创建任务配置
      const config: TaskConfig = {
        taskId,
        pollingInterval: 2000,           // 2秒轮询
        maxRetries: 5,                   // 最大重试5次
        timeout: options.timeout || 300000, // 自定义超时时间或默认5分钟
        onProgress: (status, data) => {
          console.log(`图片审核任务 ${taskId} 状态: ${status}`);
          // 显示不同状态的UI反馈
          switch (status) {
            case TaskStatus.RUNNING:
              Taro.showLoading({
                title: '审核中...',
                mask: true
              });
              break;
            case TaskStatus.SUCCESS:
              Taro.hideLoading();
              break;
            case TaskStatus.FAILED:
              Taro.hideLoading();
              Taro.showToast({
                title: '审核失败',
                icon: 'error',
                duration: 2000
              });
              break;
          }
          onProgress?.(status, data?.progress);
        },
        onSuccess: async (result) => {
          console.log(`图片审核任务 ${taskId} 成功完成:`, result);
          // 从缓存中获取完整的审核结果
          const taskCacheKey = `task_${taskId}`;
          const auditResult = auditCacheRef.current.get(taskCacheKey);
          console.log(`audit result is: ${taskCacheKey}`, auditResult)
          if (auditResult) {
            auditResult.imageUrl = processedImageUrl; // 设置图片URL
            // 同时以 imageUrl 为 key 缓存结果，用于后续的缓存查询
            if (options.enableCache) {
              auditCacheRef.current.set(cacheKey, auditResult);
            }
            onSuccess?.(auditResult);
          } else {
            console.warn(`未找到任务 ${taskId} 的缓存结果`);
            // 创建基本的结果对象
            const basicResult: ImageAuditResult = {
              taskId,
              platform,
              status: AuditStatus.COMPLETED,
              conclusion: AuditConclusion.UNCERTAIN,
              imageUrl: processedImageUrl,
              timestamp: Date.now()
            };
            onSuccess?.(basicResult);
          }
        },
        onError: (error) => {
          console.error(`图片审核任务 ${taskId} 失败:`, error);
          onError?.(error);
        },
        onTimeout: () => {
          console.warn(`图片审核任务 ${taskId} 超时`);
          Taro.showToast({
            title: '审核超时，请重试',
            icon: 'none',
            duration: 3000
          });
        }
      };
      // 启动任务监控
      await taskManagerRef.current.startTask(config);
      return taskId;

    } catch (error) {
      console.error('提交图片审核任务失败:', error);
      throw error;
    }
  }, []);

  /**
   * 批量审核多张图片
   */
  const submitBatchAuditTask = useCallback(async (
    imageUrls: string[],
    platform?: PlatformType,
    options?: ImageAuditParams['options'],
    onProgress?: (completed: number, total: number) => void,
    onBatchSuccess?: (results: ImageAuditResult[]) => void,
    onError?: (error: Error) => void
  ): Promise<string[]> => {
    const taskIds: string[] = [];
    const results: ImageAuditResult[] = [];
    let completed = 0;

    for (const imageUrl of imageUrls) {
      try {
        const taskId = await submitAuditTask(
          { imageUrl, platform, options },
          undefined,
          (result) => {
            results.push(result);
            completed++;
            onProgress?.(completed, imageUrls.length);

            if (completed === imageUrls.length) {
              onBatchSuccess?.(results);
            }
          },
          onError
        );
        taskIds.push(taskId);
      } catch (error) {
        onError?.(error as Error);
      }
    }

    return taskIds;
  }, [submitAuditTask]);

  /**
   * 取消审核任务
   */
  const cancelAuditTask = useCallback(async (taskId: string) => {
    if (!taskManagerRef.current) return;

    await taskManagerRef.current.cancelTask(taskId);
    Taro.showToast({
      title: '审核任务已取消',
      icon: 'success',
      duration: 1500
    });
  }, []);

  /**
   * 获取任务状态
   */
  const getTaskStatus = useCallback((taskId: string) => {
    return taskManagerRef.current?.getTaskStatus(taskId) || null;
  }, []);

  /**
   * 清除缓存
   */
  const clearCache = useCallback(() => {
    auditCacheRef.current.clear();
    Taro.showToast({
      title: '缓存已清除',
      icon: 'success'
    });
  }, []);

  /**
   * 获取缓存大小
   */
  const getCacheSize = useCallback(() => {
    return auditCacheRef.current.size;
  }, []);

  return {
    submitAuditTask,
    submitBatchAuditTask,
    cancelAuditTask,
    getTaskStatus,
    clearCache,
    getCacheSize,
    hasTask: (taskId: string) => taskManagerRef.current?.hasTask(taskId) || false
  };
}

/**
 * 图片预处理
 */
async function preprocessImage(
  imageUrl: string,
  options: ImageAuditParams['options'] = {}
): Promise<string> {
  const { maxSize, quality } = options;

  // 如果不需要处理，直接返回原URL
  if (!maxSize && !quality) {
    return imageUrl;
  }

  try {
    // 获取图片信息
    const imageInfo = await Taro.getImageInfo({ src: imageUrl });

    // 如果图片已经符合要求，直接返回
    if (!maxSize || (imageInfo.width * imageInfo.height * 4 / 1024) <= maxSize) {
      return imageUrl;
    }

    // 压缩图片
    const canvas = Taro.createCanvasContext('image-compress-canvas');
    const scaleFactor = Math.sqrt(maxSize * 1024 / (imageInfo.width * imageInfo.height * 4));

    const newWidth = Math.floor(imageInfo.width * scaleFactor);
    const newHeight = Math.floor(imageInfo.height * scaleFactor);

    canvas.drawImage(imageUrl, 0, 0, newWidth, newHeight);

    return new Promise((resolve) => {
      Taro.canvasToTempFilePath({
        canvasId: 'image-compress-canvas',
        quality: (quality || 80) / 100,
        success: (res) => resolve(res.tempFilePath),
        fail: () => resolve(imageUrl) // 失败时返回原URL
      });
    });

  } catch (error) {
    console.warn('图片预处理失败，使用原图:', error);
    return imageUrl;
  }
}

/**
 * 获取当前运行平台
 */
function getCurrentPlatform(): PlatformType {
  const platform = PlatformFactory.detectPlatform();
  switch (platform) {
    case 'bytedance':
      return PlatformType.BYTEDANCE;
    case 'wechat':
      return PlatformType.WECHAT;
    case 'alipay':
      return PlatformType.ALIPAY;
    case 'swan':
      return PlatformType.BAIDU;
    case 'qq':
      return PlatformType.QQ;
    case 'h5':
      return PlatformType.H5;
    default:
      return PlatformType.BYTEDANCE;
  }
}

/**
 * 映射审核状态到任务状态
 */
function mapAuditStatusToTaskStatus(auditStatus: AuditStatus): TaskStatus {
  switch (auditStatus) {
    case AuditStatus.PENDING:
    case AuditStatus.PROCESSING:
      return TaskStatus.RUNNING;
    case AuditStatus.COMPLETED:
      return TaskStatus.SUCCESS;
    case AuditStatus.FAILED:
      return TaskStatus.FAILED;
    case AuditStatus.TIMEOUT:
      return TaskStatus.TIMEOUT;
    default:
      return TaskStatus.RUNNING;
  }
}