/**
 * 穿搭照片生成服务
 * 基于 ComfyUI 工作流的穿搭照片生成功能
 */

import { invoke } from '@tauri-apps/api/core';
import { listen } from '@tauri-apps/api/event';
import type {
  OutfitPhotoGenerationRequest,
  OutfitPhotoGenerationResponse,
  GenerationHistoryQuery,
  GenerationHistoryResponse,
  ComfyUISettings,
  CloudUploadStatistics,
  WorkflowProgress,
  BatchGenerationProgress,
  WorkflowTemplate,
  GenerationPreset
} from '../types/outfitPhotoGeneration';

export class OutfitPhotoGenerationService {
  /**
   * 创建穿搭照片生成任务
   */
  static async createGenerationTask(request: OutfitPhotoGenerationRequest): Promise<string> {
    try {
      const taskId = await invoke<string>('create_outfit_photo_generation_task', { request });
      return taskId;
    } catch (error) {
      console.error('创建穿搭照片生成任务失败:', error);
      throw new Error(`创建生成任务失败: ${error}`);
    }
  }

  /**
   * 执行穿搭照片生成
   */
  static async executeGeneration(
    generationId: string,
    onProgress?: (progress: WorkflowProgress) => void
  ): Promise<OutfitPhotoGenerationResponse> {
    try {
      // 监听进度事件
      let progressUnlisten: (() => void) | null = null;
      if (onProgress) {
        progressUnlisten = await listen<WorkflowProgress>('outfit_generation_progress', (event) => {
          if (event.payload) {
            onProgress(event.payload);
          }
        });
      }

      const response = await invoke<OutfitPhotoGenerationResponse>('execute_outfit_photo_generation', {
        generationId
      });

      // 清理进度监听器
      if (progressUnlisten) {
        progressUnlisten();
      }

      return response;
    } catch (error) {
      console.error('执行穿搭照片生成失败:', error);
      throw new Error(`生成失败: ${error}`);
    }
  }

  /**
   * 批量执行穿搭照片生成
   */
  static async executeBatchGeneration(
    requests: OutfitPhotoGenerationRequest[],
    onProgress?: (progress: BatchGenerationProgress) => void
  ): Promise<OutfitPhotoGenerationResponse[]> {
    try {
      // 监听批量进度事件
      let progressUnlisten: (() => void) | null = null;
      if (onProgress) {
        progressUnlisten = await listen<BatchGenerationProgress>('outfit_generation_batch_progress', (event) => {
          if (event.payload) {
            onProgress(event.payload);
          }
        });
      }

      const responses = await invoke<OutfitPhotoGenerationResponse[]>('execute_outfit_photo_generation_batch', {
        requests
      });

      // 清理进度监听器
      if (progressUnlisten) {
        progressUnlisten();
      }

      return responses;
    } catch (error) {
      console.error('批量执行穿搭照片生成失败:', error);
      throw new Error(`批量生成失败: ${error}`);
    }
  }

  /**
   * 重试失败的穿搭照片生成
   */
  static async retryGeneration(generationId: string): Promise<OutfitPhotoGenerationResponse> {
    try {
      const response = await invoke<OutfitPhotoGenerationResponse>('retry_outfit_photo_generation', {
        generationId
      });
      return response;
    } catch (error) {
      console.error('重试穿搭照片生成失败:', error);
      throw new Error(`重试失败: ${error}`);
    }
  }

  /**
   * 获取生成历史记录
   */
  static async getGenerationHistory(query: GenerationHistoryQuery): Promise<GenerationHistoryResponse> {
    try {
      const response = await invoke<GenerationHistoryResponse>('get_outfit_photo_generation_history', {
        query
      });
      return response;
    } catch (error) {
      console.error('获取生成历史记录失败:', error);
      throw new Error(`获取历史记录失败: ${error}`);
    }
  }

  /**
   * 删除生成记录
   */
  static async deleteGeneration(generationId: string): Promise<void> {
    try {
      await invoke('delete_outfit_photo_generation', { generationId });
    } catch (error) {
      console.error('删除生成记录失败:', error);
      throw new Error(`删除记录失败: ${error}`);
    }
  }

  /**
   * 清理失败的生成记录
   */
  static async cleanupFailedGenerations(maxAgeHours: number): Promise<number> {
    try {
      const cleanedCount = await invoke<number>('cleanup_failed_outfit_generations', {
        maxAgeHours
      });
      return cleanedCount;
    } catch (error) {
      console.error('清理失败记录失败:', error);
      throw new Error(`清理失败: ${error}`);
    }
  }

  /**
   * 获取 ComfyUI 设置
   */
  static async getComfyUISettings(): Promise<ComfyUISettings> {
    try {
      const settings = await invoke<ComfyUISettings>('get_comfyui_settings');
      return settings;
    } catch (error) {
      console.error('获取 ComfyUI 设置失败:', error);
      throw new Error(`获取设置失败: ${error}`);
    }
  }

  /**
   * 更新 ComfyUI 设置
   */
  static async updateComfyUISettings(settings: ComfyUISettings): Promise<void> {
    try {
      await invoke('update_comfyui_settings', { settings });
    } catch (error) {
      console.error('更新 ComfyUI 设置失败:', error);
      throw new Error(`更新设置失败: ${error}`);
    }
  }

  /**
   * 测试 ComfyUI 连接
   */
  static async testComfyUIConnection(): Promise<boolean> {
    try {
      const connected = await invoke<boolean>('test_comfyui_connection');
      return connected;
    } catch (error) {
      console.error('测试 ComfyUI 连接失败:', error);
      return false;
    }
  }

  /**
   * 获取云端上传统计
   */
  static async getCloudUploadStatistics(): Promise<CloudUploadStatistics> {
    try {
      const statistics = await invoke<CloudUploadStatistics>('get_cloud_upload_statistics');
      return statistics;
    } catch (error) {
      console.error('获取云端上传统计失败:', error);
      throw new Error(`获取统计失败: ${error}`);
    }
  }

  /**
   * 测试云端上传连接
   */
  static async testCloudUploadConnection(): Promise<boolean> {
    try {
      const connected = await invoke<boolean>('test_cloud_upload_connection');
      return connected;
    } catch (error) {
      console.error('测试云端上传连接失败:', error);
      return false;
    }
  }

  /**
   * 获取可用的工作流模板
   */
  static async getWorkflowTemplates(): Promise<WorkflowTemplate[]> {
    try {
      const templates = await invoke<WorkflowTemplate[]>('get_workflow_templates');
      return templates;
    } catch (error) {
      console.error('获取工作流模板失败:', error);
      throw new Error(`获取模板失败: ${error}`);
    }
  }

  /**
   * 获取生成预设
   */
  static async getGenerationPresets(): Promise<GenerationPreset[]> {
    try {
      const presets = await invoke<GenerationPreset[]>('get_generation_presets');
      return presets;
    } catch (error) {
      console.error('获取生成预设失败:', error);
      throw new Error(`获取预设失败: ${error}`);
    }
  }

  /**
   * 保存生成预设
   */
  static async saveGenerationPreset(preset: Omit<GenerationPreset, 'id' | 'created_at' | 'updated_at'>): Promise<string> {
    try {
      const presetId = await invoke<string>('save_generation_preset', { preset });
      return presetId;
    } catch (error) {
      console.error('保存生成预设失败:', error);
      throw new Error(`保存预设失败: ${error}`);
    }
  }

  /**
   * 删除生成预设
   */
  static async deleteGenerationPreset(presetId: string): Promise<void> {
    try {
      await invoke('delete_generation_preset', { presetId });
    } catch (error) {
      console.error('删除生成预设失败:', error);
      throw new Error(`删除预设失败: ${error}`);
    }
  }
}
