use tauri::{State, AppHandle, Emitter};
use tracing::{info, error, warn};
use anyhow::{Result, anyhow};
use chrono::Utc;
use std::sync::Arc;
use std::time::Duration;
use reqwest;
use serde_json;

use crate::app_state::AppState;
use crate::data::models::outfit_image::{
    OutfitImageRecord, OutfitImageGenerationRequest, OutfitImageGenerationResponse,
    OutfitImageStats, ProductImage, OutfitImage, OutfitImageStatus, OutfitImageRecordsResponse
};
use crate::data::models::outfit_photo_generation::{
    WorkflowProgress
};
use crate::data::repositories::outfit_image_repository::OutfitImageRepository;
use crate::data::repositories::model_repository::ModelRepository;
use crate::data::models::model::PhotoType;
use crate::infrastructure::database::Database;
use crate::business::services::comfyui_service::ComfyUIService;
use crate::business::services::cloud_upload_service::CloudUploadService;
use crate::business::services::error_handling_service::ErrorHandlingService;

use crate::config::AppConfig;

/// 模特个人看板统计信息
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct ModelDashboardStats {
    pub model_id: String,
    pub model_name: String,
    pub total_photos: u32,
    pub portrait_photos: u32,
    pub work_photos: u32,
    pub outfit_stats: OutfitImageStats,
    pub recent_generations: u32,
    pub success_rate: f32,
    pub favorite_count: u32,
    pub total_generation_time_ms: u64,
    pub average_generation_time_ms: u64,
}

/// 获取模特个人看板统计信息
#[tauri::command]
pub async fn get_model_dashboard_stats(
    state: State<'_, AppState>,
    model_id: String,
) -> Result<ModelDashboardStats, String> {
    // 获取数据库连接
    let database = state.get_database();
    let outfit_repo = OutfitImageRepository::new(database.clone());
    let model_repo = ModelRepository::new(database.clone());

    // 获取模特基本信息
    let model = model_repo.get_by_id(&model_id)
        .map_err(|e| format!("获取模特信息失败: {}", e))?
        .ok_or_else(|| "模特不存在".to_string())?;

    // 获取穿搭图片统计
    let outfit_stats = outfit_repo.get_stats_by_model_id(&model_id)
        .map_err(|e| format!("获取穿搭图片统计失败: {}", e))?;

    // 计算照片统计
    let total_photos = model.photos.len() as u32;
    let portrait_photos = model.photos.iter()
        .filter(|photo| matches!(photo.photo_type, PhotoType::Portrait))
        .count() as u32;
    let work_photos = model.photos.iter()
        .filter(|photo| matches!(photo.photo_type, PhotoType::Commercial | PhotoType::Artistic))
        .count() as u32;

    // 计算成功率
    let success_rate = if outfit_stats.total_records > 0 {
        outfit_stats.completed_records as f32 / outfit_stats.total_records as f32
    } else {
        0.0
    };

    // 获取最近30天的生成记录（简化实现，实际应该查询数据库）
    let recent_generations = outfit_stats.total_records; // TODO: 实现真正的30天统计

    // 计算总生成时间和平均生成时间（简化实现）
    let total_generation_time_ms = outfit_stats.completed_records as u64 * 5000; // 假设平均5秒
    let average_generation_time_ms = if outfit_stats.completed_records > 0 {
        total_generation_time_ms / outfit_stats.completed_records as u64
    } else {
        0
    };

    let dashboard_stats = ModelDashboardStats {
        model_id: model_id.clone(),
        model_name: model.name.clone(),
        total_photos,
        portrait_photos,
        work_photos,
        outfit_stats: outfit_stats.clone(),
        recent_generations,
        success_rate,
        favorite_count: outfit_stats.favorite_images,
        total_generation_time_ms,
        average_generation_time_ms,
    };

    Ok(dashboard_stats)
}

/// 获取模特的穿搭图片生成记录列表
#[tauri::command]
pub async fn get_outfit_image_records(
    state: State<'_, AppState>,
    model_id: String,
) -> Result<Vec<OutfitImageRecord>, String> {
    println!("📋 获取模特穿搭图片生成记录: {}", model_id);

    let database = state.get_database();
    let outfit_repo = OutfitImageRepository::new(database);

    let records = outfit_repo.get_records_by_model_id(&model_id)
        .map_err(|e| format!("获取穿搭图片记录失败: {}", e))?;

    Ok(records)
}

/// 分页获取模特的穿搭图片生成记录列表
#[tauri::command]
pub async fn get_outfit_image_records_paginated(
    state: State<'_, AppState>,
    model_id: String,
    page: u32,
    page_size: u32,
) -> Result<OutfitImageRecordsResponse, String> {

    let database = state.get_database();
    let outfit_repo = OutfitImageRepository::new(database);

    // 计算偏移量
    let offset = (page - 1) * page_size;

    // 获取记录
    let records = outfit_repo.get_records_by_model_id_paginated(&model_id, page_size, offset)
        .map_err(|e| format!("获取穿搭图片记录失败: {}", e))?;

    // 获取总数
    let total_count = outfit_repo.get_records_count_by_model_id(&model_id)
        .map_err(|e| format!("获取记录总数失败: {}", e))?;

    // 计算是否还有更多数据
    let has_more = (offset + page_size) < total_count;

    let response = OutfitImageRecordsResponse {
        records,
        total_count,
        page,
        page_size,
        has_more,
    };

    Ok(response)
}

/// 创建穿搭图片生成记录
#[tauri::command]
pub async fn create_outfit_image_record(
    state: State<'_, AppState>,
    request: OutfitImageGenerationRequest,
) -> Result<String, String> {
    println!("🎨 创建穿搭图片生成记录: {:?}", request);

    let database = state.get_database();
    let outfit_repo = OutfitImageRepository::new(database);

    // 创建生成记录
    let mut record = OutfitImageRecord::new(
        request.model_id,
        request.model_image_id,
        request.generation_prompt,
    );

    println!("📝 开始处理商品图片，共 {} 个", request.product_image_paths.len());

    // 创建商品图片记录（使用异步文件操作）
    for (index, product_path) in request.product_image_paths.iter().enumerate() {
        println!("📷 处理商品图片 {}/{}: {}", index + 1, request.product_image_paths.len(), product_path);

        let file_name = std::path::Path::new(product_path)
            .file_name()
            .and_then(|n| n.to_str())
            .unwrap_or(&format!("product_{}", index))
            .to_string();

        // 使用异步文件操作，添加超时
        let file_size = match tokio::time::timeout(
            std::time::Duration::from_secs(5),
            tokio::fs::metadata(product_path)
        ).await {
            Ok(Ok(metadata)) => {
                println!("📊 获取文件大小成功: {} bytes", metadata.len());
                metadata.len()
            },
            Ok(Err(e)) => {
                println!("⚠️ 获取文件元数据失败: {}, 使用默认大小", e);
                0
            },
            Err(_) => {
                println!("⚠️ 获取文件元数据超时，使用默认大小");
                0
            }
        };

        let product_image = ProductImage::new(
            record.id.clone(),
            product_path.clone(),
            file_name,
            file_size,
        );

        record.product_images.push(product_image);
    }

    println!("💾 开始保存到数据库");

    // 使用事务保存所有数据
    match outfit_repo.create_record_with_products(&record) {
        Ok(_) => {
            println!("✅ 穿搭图片生成记录创建成功: {}", record.id);
            Ok(record.id)
        },
        Err(e) => {
            println!("❌ 创建穿搭图片记录失败: {}", e);
            Err(format!("创建穿搭图片记录失败: {}", e))
        }
    }
}

/// 删除穿搭图片生成记录
#[tauri::command]
pub async fn delete_outfit_image_record(
    state: State<'_, AppState>,
    record_id: String,
) -> Result<(), String> {
    println!("🗑️ 删除穿搭图片生成记录: {}", record_id);

    let database = state.get_database();
    let outfit_repo = OutfitImageRepository::new(database);

    outfit_repo.delete_record(&record_id)
        .map_err(|e| format!("删除穿搭图片记录失败: {}", e))?;

    println!("✅ 穿搭图片生成记录删除成功");
    Ok(())
}

/// 获取穿搭图片生成记录详情
#[tauri::command]
pub async fn get_outfit_image_record_detail(
    state: State<'_, AppState>,
    record_id: String,
) -> Result<Option<OutfitImageRecord>, String> {
    println!("🔍 获取穿搭图片生成记录详情: {}", record_id);

    let database = state.get_database();
    let outfit_repo = OutfitImageRepository::new(database);

    let record = outfit_repo.get_record_by_id(&record_id)
        .map_err(|e| format!("获取穿搭图片记录详情失败: {}", e))?;

    println!("✅ 穿搭图片生成记录详情获取成功");
    Ok(record)
}

/// 执行穿搭图片生成
#[tauri::command]
pub async fn execute_outfit_image_generation(
    state: State<'_, AppState>,
    app_handle: AppHandle,
    request: OutfitImageGenerationRequest,
) -> Result<OutfitImageGenerationResponse, String> {
    info!("🎨 执行穿搭图片生成: {:?}", request);
    // 检查是否使用 ComfyUI（本地模式）
    if request.use_comfyui.unwrap_or(false) {
        // 本地ComfyUI模式：调用本地ComfyUI生成逻辑
        let database = state.get_database();
        return perform_local_comfyui_generation(database, app_handle, request).await;
    } else {
        // 云端Modal模式：使用云端API
        return execute_modal_cloud_generation(state, app_handle, request).await;
    }
}

/// 执行单个穿搭图片生成任务（异步模式）
#[tauri::command]
pub async fn execute_outfit_image_task(
    state: State<'_, AppState>,
    app_handle: AppHandle,
    record_id: String,
) -> Result<(), String> {
    info!("🚀 开始执行穿搭图片生成任务: {}", record_id);

    // 获取数据库和仓库
    let database = state.get_database();
    let outfit_repo = OutfitImageRepository::new(database.clone());

    // 获取任务记录
    let record = match outfit_repo.get_record_by_id(&record_id) {
        Ok(Some(record)) => record,
        Ok(None) => {
            error!("任务记录不存在: {}", record_id);
            return Err(format!("任务记录不存在: {}", record_id));
        }
        Err(e) => {
            error!("获取任务记录失败: {} - {}", record_id, e);
            return Err(format!("获取任务记录失败: {}", e));
        }
    };

    // 构建生成请求
    let request = OutfitImageGenerationRequest {
        record_id: Some(record_id.clone()), // 传递记录ID用于精确匹配
        model_id: record.model_id.clone(),
        model_image_id: record.model_image_id.clone(),
        product_image_paths: record.product_images.iter().map(|img| img.file_path.clone()).collect(),
        generation_prompt: record.generation_prompt.clone(),
        style_preferences: None,
        product_index: Some(0), // 默认商品编号为0
        use_comfyui: record.generation_type.as_ref().map(|t| t == "comfyui"),
    };

    // 立即更新记录状态为"生成中"
    if let Ok(Some(mut record)) = outfit_repo.get_record_by_id(&record_id) {
        record.start_processing();
        if let Err(e) = outfit_repo.update_record(&record) {
            error!("更新记录状态为生成中失败: {}", e);
        } else {
            info!("📝 更新记录状态为生成中: {}", record_id);
        }
    }

    // 在后台异步执行生成任务
    let app_handle_clone = app_handle.clone();
    let record_id_clone = record_id.clone();

    // 获取数据库实例用于后台任务
    let database = state.get_database();

    tokio::spawn(async move {
        // 直接调用本地ComfyUI生成逻辑，不通过command函数
        match perform_local_comfyui_generation(database, app_handle_clone.clone(), request).await {
            Ok(response) => {
                info!("✅ 后台任务执行完成: {}", record_id_clone);

                // 发送任务完成事件
                let completion_event = serde_json::json!({
                    "type": "outfit_generation_completed",
                    "record_id": record_id_clone,
                    "success": response.success,
                    "generated_images": response.generated_images,
                    "error_message": response.error_message
                });

                if let Err(e) = app_handle_clone.emit("outfit_generation_completed", &completion_event) {
                    error!("发送任务完成事件失败: {}", e);
                }
            }
            Err(e) => {
                error!("❌ 后台任务执行失败: {} - {}", record_id_clone, e);

                // 发送任务失败事件
                let failure_event = serde_json::json!({
                    "type": "outfit_generation_failed",
                    "record_id": record_id_clone,
                    "error_message": e
                });

                if let Err(e) = app_handle_clone.emit("outfit_generation_failed", &failure_event) {
                    error!("发送任务失败事件失败: {}", e);
                }
            }
        }
    });

    info!("✅ 穿搭图片生成任务已提交到后台: {}", record_id);
    Ok(())
}

/// 重试失败的穿搭图片生成任务
#[tauri::command]
pub async fn retry_outfit_image_generation(
    state: State<'_, AppState>,
    app_handle: AppHandle,
    record_id: String,
) -> Result<(), String> {
    info!("🔄 重试穿搭图片生成任务: {}", record_id);

    // 获取数据库和仓库
    let database = state.get_database();
    let outfit_repo = OutfitImageRepository::new(database.clone());

    // 获取任务记录
    let record = match outfit_repo.get_record_by_id(&record_id) {
        Ok(Some(record)) => record,
        Ok(None) => {
            error!("重试任务记录不存在: {}", record_id);
            return Err(format!("任务记录不存在: {}", record_id));
        }
        Err(e) => {
            error!("获取重试任务记录失败: {} - {}", record_id, e);
            return Err(format!("获取任务记录失败: {}", e));
        }
    };

    // 检查记录状态是否为失败状态
    if record.status != OutfitImageStatus::Failed {
        warn!("任务记录状态不是失败状态，无法重试: {} - 当前状态: {:?}", record_id, record.status);
        return Err(format!("任务状态不是失败状态，无法重试。当前状态: {:?}", record.status));
    }

    // 重置记录状态为待处理，清除错误信息
    if let Ok(Some(mut record)) = outfit_repo.get_record_by_id(&record_id) {
        record.reset_for_retry();
        if let Err(e) = outfit_repo.update_record(&record) {
            error!("重置记录状态失败: {}", e);
            return Err(format!("重置记录状态失败: {}", e));
        } else {
            info!("📝 重置记录状态为待处理: {}", record_id);
        }
    }

    // 调用执行任务命令重新执行
    execute_outfit_image_task(state, app_handle, record_id.clone()).await?;

    info!("✅ 穿搭图片生成任务重试成功: {}", record_id);
    Ok(())
}

/// 上传图片到云存储并返回可访问的URL
async fn upload_image_to_cloud(file_path: &str, cloud_service: &CloudUploadService) -> Result<String> {
    info!("📤 正在上传图片到云存储: {}", file_path);

    // 生成远程文件名
    let file_name = std::path::Path::new(file_path)
        .file_name()
        .and_then(|n| n.to_str())
        .unwrap_or("image.jpg");

    let remote_key = format!("outfit-generation/images/{}", file_name);

    // 上传文件
    let upload_result = cloud_service
        .upload_file(file_path, Some(remote_key), None)
        .await?;

    if upload_result.success {
        if let Some(remote_url) = upload_result.remote_url {
            // 将S3 URL转换为可访问的CDN地址
            let accessible_url = convert_s3_to_cdn_url(&remote_url);
            Ok(accessible_url)
        } else if let Some(urn) = upload_result.urn {
            // 将S3 URN转换为可访问的CDN地址
            let accessible_url = convert_s3_to_cdn_url(&urn);
            Ok(accessible_url)
        } else {
            warn!("⚠️ 上传成功但未返回URL或URN");
            Err(anyhow!("上传成功但未返回URL"))
        }
    } else {
        let error_msg = upload_result.error_message
            .unwrap_or_else(|| "未知上传错误".to_string());
        error!("❌ 图片上传失败: {}", error_msg);
        Err(anyhow!("图片上传失败: {}", error_msg))
    }
}

/// 将S3 URL转换为CDN URL
fn convert_s3_to_cdn_url(s3_url: &str) -> String {
    if s3_url.starts_with("s3://ap-northeast-2/modal-media-cache/") {
        // 将 s3://ap-northeast-2/modal-media-cache/ 替换为 https://cdn.roasmax.cn/
        s3_url.replace("s3://ap-northeast-2/modal-media-cache/", "https://cdn.roasmax.cn/")
    } else if s3_url.starts_with("s3://") {
        // 处理其他 s3:// 格式，转换为通用CDN格式
        s3_url.replace("s3://", "https://cdn.roasmax.cn/")
    } else if s3_url.contains("amazonaws.com") {
        // 如果是完整的S3 HTTPS URL，提取key部分
        if let Some(key_start) = s3_url.find(".com/") {
            let key = &s3_url[key_start + 5..];
            format!("https://cdn.roasmax.cn/{}", key)
        } else {
            s3_url.to_string()
        }
    } else {
        // 如果不是预期的S3格式，返回原URL
        s3_url.to_string()
    }
}

/// 执行本地ComfyUI生成的核心逻辑（用于后台任务）
async fn perform_local_comfyui_generation(
    database: Arc<Database>,
    app_handle: AppHandle,
    request: OutfitImageGenerationRequest,
) -> Result<OutfitImageGenerationResponse, String> {
    info!("🎨 后台执行本地ComfyUI穿搭图片生成: {:?}", request);
    let start_time = Utc::now();

    // 创建仓库实例
    let outfit_repo = OutfitImageRepository::new(database.clone());

    // 获取记录ID：优先使用传入的record_id，否则通过查找获取（向后兼容）
    let record_id = if let Some(id) = &request.record_id {
        id.clone()
    } else {
        // 兼容旧逻辑：根据model_id和model_image_id获取生成记录
        let records = outfit_repo
            .get_records_by_model_id(&request.model_id)
            .map_err(|e| format!("获取生成记录失败: {}", e))?;

        // 找到匹配的记录（最新的一个）
        let record = records.into_iter()
            .find(|r| r.model_image_id == request.model_image_id)
            .ok_or_else(|| "未找到对应的生成记录".to_string())?;

        record.id.clone()
    };

    // 验证记录是否存在
    let record = outfit_repo
        .get_record_by_id(&record_id)
        .map_err(|e| format!("获取记录失败: {}", e))?
        .ok_or_else(|| format!("记录不存在: {}", record_id))?;

    // 初始化错误处理服务
    let error_service = ErrorHandlingService::new();

    // 定义简单错误类型
    #[derive(Debug)]
    struct SimpleError(String);
    impl std::fmt::Display for SimpleError {
        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
            write!(f, "{}", self.0)
        }
    }
    impl std::error::Error for SimpleError {}

    // 加载配置
    let config = AppConfig::load();

    // 检查 ComfyUI 是否启用
    if !config.is_comfyui_enabled() {
        let simple_error = SimpleError("ComfyUI 功能未启用".to_string());
        let user_error = error_service.handle_error(&simple_error, None);

        return Ok(OutfitImageGenerationResponse {
            record_id,
            generated_images: Vec::new(),
            generation_time_ms: 0,
            success: false,
            error_message: Some(user_error.message),
            generation_type: Some("comfyui".to_string()),
            task_id: None,
        });
    }

    // 创建 ComfyUI 服务
    let comfyui_service = ComfyUIService::new(config.get_comfyui_settings().clone());

    // 创建云上传服务
    let cloud_upload_service = CloudUploadService::new();

    // 检查 ComfyUI 连接
    if !comfyui_service.check_connection().await.unwrap_or(false) {
        let simple_error = SimpleError("ComfyUI 服务器连接失败".to_string());
        let user_error = error_service.handle_error(&simple_error, None);

        return Ok(OutfitImageGenerationResponse {
            record_id,
            generated_images: Vec::new(),
            generation_time_ms: 0,
            success: false,
            error_message: Some(user_error.message),
            generation_type: Some("comfyui".to_string()),
            task_id: None,
        });
    }

    // 获取模特图片URL（使用model_image_id）
    let model_repo = ModelRepository::new(database.clone());

    // 首先获取模特的所有照片，然后找到指定的照片
    let model_image_local_path = match model_repo.get_photos(&request.model_id) {
        Ok(photos) => {
            // 查找指定ID的照片
            if let Some(photo) = photos.iter().find(|p| p.id == request.model_image_id) {
                photo.file_path.clone()
            } else {
                let simple_error = SimpleError(format!("模特图片不存在: {}", request.model_image_id));
                let user_error = error_service.handle_error(&simple_error, None);
                return Ok(OutfitImageGenerationResponse {
                    record_id,
                    generated_images: Vec::new(),
                    generation_time_ms: 0,
                    success: false,
                    error_message: Some(user_error.message),
                    generation_type: Some("comfyui".to_string()),
                    task_id: None,
                });
            }
        }
        Err(e) => {
            let simple_error = SimpleError(format!("获取模特图片失败: {}", e));
            let user_error = error_service.handle_error(&simple_error, None);
            return Ok(OutfitImageGenerationResponse {
                record_id,
                generated_images: Vec::new(),
                generation_time_ms: 0,
                success: false,
                error_message: Some(user_error.message),
                generation_type: Some("comfyui".to_string()),
                task_id: None,
            });
        }
    };

    // 上传模特图片到云端获取外网链接
    let model_image_url = if model_image_local_path.starts_with("https://") {
        // 如果已经是HTTPS URL，直接使用
        info!("📷 使用已有的云端模特图片URL: {}", model_image_local_path);
        model_image_local_path
    } else {
        // 如果是本地路径，上传到云存储
        info!("📤 本地模特图片需要上传到云存储: {}", model_image_local_path);
        match upload_image_to_cloud(&model_image_local_path, &cloud_upload_service).await {
            Ok(url) => url,
            Err(e) => {
                let simple_error = SimpleError(format!("上传模特图片失败: {}", e));
                let user_error = error_service.handle_error(&simple_error, None);
                return Ok(OutfitImageGenerationResponse {
                    record_id,
                    generated_images: Vec::new(),
                    generation_time_ms: 0,
                    success: false,
                    error_message: Some(user_error.message),
                    generation_type: Some("comfyui".to_string()),
                    task_id: None,
                });
            }
        }
    };

    // 更新记录状态为处理中
    if let Ok(Some(mut record)) = outfit_repo.get_record_by_id(&record_id) {
        record.start_processing();
        let _ = outfit_repo.update_record(&record);
        info!("📝 更新穿搭图片生成记录状态为处理中");
    }

    // 处理多个商品图片，为每个商品图片创建生成任务
    let mut all_generated_images = Vec::new();
    let mut has_errors = false;
    let mut error_messages = Vec::new();

    // 获取工作流文件路径
    let workflow_path_str = match config.get_comfyui_settings().workflow_directory.as_ref() {
        Some(path) if !path.is_empty() => path.clone(),
        _ => {
            let simple_error = SimpleError("请先在设置中选择ComfyUI工作流文件".to_string());
            let user_error = error_service.handle_error(&simple_error, None);
            return Ok(OutfitImageGenerationResponse {
                record_id,
                generated_images: Vec::new(),
                generation_time_ms: 0,
                success: false,
                error_message: Some(user_error.message),
                generation_type: Some("comfyui".to_string()),
                task_id: None,
            });
        }
    };

    // 验证请求只包含一个商品图片（工作流模板设计为单商品）
    if request.product_image_paths.len() != 1 {
        let error_msg = format!(
            "当前工作流模板只支持单个商品图片，但重试请求包含 {} 个商品图片。",
            request.product_image_paths.len()
        );
        error!("{}", error_msg);

        let simple_error = SimpleError(error_msg.clone());
        let user_error = error_service.handle_error(&simple_error, None);

        // 更新记录状态为失败
        if let Ok(Some(mut record)) = outfit_repo.get_record_by_id(&record_id) {
            record.fail(user_error.message.clone());
            let _ = outfit_repo.update_record(&record);
        }

        return Ok(OutfitImageGenerationResponse {
            record_id,
            generated_images: Vec::new(),
            generation_time_ms: 0,
            success: false,
            error_message: Some(user_error.message),
            generation_type: Some("local_comfyui".to_string()),
            task_id: None,
        });
    }

    let product_image_path = &request.product_image_paths[0];
    info!("重试处理单个商品图片: {}", product_image_path);

    // 上传商品图片到云端获取外网链接
    let product_image_url = if product_image_path.starts_with("https://") {
        // 如果已经是HTTPS URL，直接使用
        info!("📷 使用已有的云端商品图片URL: {}", product_image_path);
        product_image_path.clone()
    } else {
        // 如果是本地路径，上传到云存储
        info!("📤 本地商品图片需要上传到云存储: {}", product_image_path);
        match upload_image_to_cloud(product_image_path, &cloud_upload_service).await {
            Ok(url) => url,
            Err(e) => {
                has_errors = true;
                let error_msg = format!("商品图片上传失败: {}", e);
                error_messages.push(error_msg.clone());
                error!("{}", error_msg);

                let simple_error = SimpleError(error_msg.clone());
                let user_error = error_service.handle_error(&simple_error, None);

                // 更新记录状态为失败
                if let Ok(Some(mut record)) = outfit_repo.get_record_by_id(&record_id) {
                    record.fail(user_error.message.clone());
                    let _ = outfit_repo.update_record(&record);
                }

                return Ok(OutfitImageGenerationResponse {
                    record_id,
                    generated_images: Vec::new(),
                    generation_time_ms: 0,
                    success: false,
                    error_message: Some(user_error.message),
                    generation_type: Some("local_comfyui".to_string()),
                    task_id: None,
                });
            }
        }
    };

    // 创建进度回调（基于 record_id 的直接匹配）
    let app_handle_clone = app_handle.clone();
    let record_id_clone = record_id.clone();
    let outfit_repo_clone = OutfitImageRepository::new(database.clone());

    let progress_callback = move |progress: WorkflowProgress| {
        // 更新数据库中的进度
        if let Ok(Some(mut record)) = outfit_repo_clone.get_record_by_id(&record_id_clone) {
            record.progress = progress.progress_percentage / 100.0; // 转换为0-1范围
            if let Err(e) = outfit_repo_clone.update_record(&record) {
                warn!("更新记录进度失败: {}", e);
            }
        }

        // 发送进度事件到前端
        let progress_event = serde_json::json!({
            "type": "outfit_generation_progress",
            "record_id": record_id_clone,
            "progress_percentage": progress.progress_percentage,
            "current_step": progress.current_step,
            "total_steps": progress.total_steps,
            "status_message": progress.status_message,
            "current_node_id": progress.current_node_id
        });

        if let Err(e) = app_handle_clone.emit("outfit_generation_progress", &progress_event) {
            warn!("发送进度事件失败: {}", e);
        }
        info!("生成进度 - 记录ID: {}, 进度: {}%", record_id_clone, progress.progress_percentage);
    };

    // 只有当用户明确提供了 prompt 时才进行替换，否则保持工作流原始设置
    let prompt = match request.generation_prompt.as_ref() {
        Some(p) if !p.trim().is_empty() => p.clone(),
        _ => {
            // 如果没有提供 prompt 或为空，使用空字符串，让工作流保持原始设置
            info!("重试时未提供生成提示词，将保持工作流模板的原始设置");
            String::new()
        }
    };

    // 执行 ComfyUI 工作流并自动上传结果
    let remote_key_prefix = format!("outfit-images/{}", record_id);

    match comfyui_service.execute_workflow_with_upload_indexed_with_prompt_id(
        &cloud_upload_service,
        &workflow_path_str,
        &model_image_url,
        &product_image_url,
        &prompt,
        None, // 负面提示词
        Some(&remote_key_prefix),
        progress_callback,
        request.product_index, // 使用请求中的商品编号
    ).await {
        Ok((prompt_id, upload_results)) => {
            // 保存 ComfyUI prompt_id 到数据库记录
            if let Ok(Some(mut record)) = outfit_repo.get_record_by_id(&record_id) {
                record.set_comfyui_prompt_id(prompt_id.clone());
                if let Err(e) = outfit_repo.update_record(&record) {
                    warn!("保存 ComfyUI prompt_id 失败: {}", e);
                } else {
                    info!("✅ 已保存 ComfyUI prompt_id: {} 到记录: {}", prompt_id, record_id);
                }
            }

            // 处理上传结果
            let mut successful_uploads = 0;

            for upload_result in upload_results {
                if upload_result.success {
                    if let Some(remote_url) = upload_result.remote_url {
                        all_generated_images.push(remote_url.clone());
                        successful_uploads += 1;
                    }
                } else {
                    warn!("图片上传失败: {}", upload_result.error_message.unwrap_or_default());
                }
            }

            if successful_uploads == 0 {
                has_errors = true;
                error_messages.push("所有图片上传失败".to_string());
            } else {
                info!("商品图片重试生成成功，上传 {} 张图片", successful_uploads);
            }
        }
        Err(e) => {
            has_errors = true;
            let error_msg = format!("商品图片重试生成异常: {}", e);
            error_messages.push(error_msg.clone());
            error!("{}", error_msg);
        }
    }

    let end_time = Utc::now();
    let total_duration = (end_time - start_time).num_milliseconds() as u64;

    // 构建响应并更新数据库状态
    let response = if all_generated_images.is_empty() {
        let error_message = if error_messages.is_empty() {
            "未生成任何图片".to_string()
        } else {
            error_messages.join("; ")
        };

        let simple_error = SimpleError(error_message.clone());
        let user_error = error_service.handle_error(&simple_error, None);

        // 更新记录状态为失败
        if let Ok(Some(mut record)) = outfit_repo.get_record_by_id(&record_id) {
            record.fail(user_error.message.clone());
            let _ = outfit_repo.update_record(&record);
            info!("📝 更新穿搭图片生成记录状态为失败");
        }

        OutfitImageGenerationResponse {
            record_id,
            generated_images: Vec::new(),
            generation_time_ms: total_duration,
            success: false,
            error_message: Some(user_error.message),
            generation_type: Some("local_comfyui".to_string()),
            task_id: None,
        }
    } else {
        let success_message = if has_errors {
            format!("部分生成成功，共生成 {} 张图片", all_generated_images.len())
        } else {
            format!("生成成功，共生成 {} 张图片", all_generated_images.len())
        };

        info!("{}", success_message);

        // 转换S3 URL为CDN URL
        let cdn_urls: Vec<String> = all_generated_images.iter()
            .map(|url| convert_s3_to_cdn_url(url))
            .collect();

        // 更新记录状态为完成并创建OutfitImage记录
        if let Ok(Some(mut record)) = outfit_repo.get_record_by_id(&record_id) {
            record.complete(cdn_urls.clone());

            // 创建OutfitImage记录
            for (index, image_url) in cdn_urls.iter().enumerate() {
                let outfit_image = OutfitImage::new(
                    record_id.clone(),
                    image_url.clone(),
                    index as u32,
                );

                // 保存OutfitImage到数据库
                if let Err(e) = outfit_repo.create_outfit_image(&outfit_image) {
                    warn!("创建OutfitImage记录失败: {}", e);
                } else {
                    record.outfit_images.push(outfit_image);
                }
            }

            let _ = outfit_repo.update_record(&record);
            info!("📝 更新穿搭图片生成记录状态为完成，保存 {} 张图片", cdn_urls.len());
        }

        OutfitImageGenerationResponse {
            record_id,
            generated_images: cdn_urls,
            generation_time_ms: total_duration,
            success: true,
            error_message: if has_errors { Some(error_messages.join("; ")) } else { None },
            generation_type: Some("local_comfyui".to_string()),
            task_id: None,
        }
    };

    info!("✅ 后台穿搭图片生成完成，耗时: {}ms", total_duration);
    Ok(response)
}

/// 创建基于 prompt_id 的进度回调函数
/// 这个函数用于批量处理场景，通过 prompt_id 精确匹配任务
pub fn create_prompt_id_based_progress_callback(
    database: Arc<Database>,
    app_handle: AppHandle,
) -> impl Fn(String, WorkflowProgress) + Send + Sync + 'static {
    move |prompt_id: String, progress: WorkflowProgress| {
        let outfit_repo = OutfitImageRepository::new(database.clone());

        // 根据 prompt_id 查找对应的记录
        match outfit_repo.get_record_by_comfyui_prompt_id(&prompt_id) {
            Ok(Some(mut record)) => {
                let record_id = record.id.clone();

                // 更新数据库中的进度
                record.progress = progress.progress_percentage / 100.0; // 转换为0-1范围
                if let Err(e) = outfit_repo.update_record(&record) {
                    warn!("更新记录进度失败: {}", e);
                } else {
                    info!("✅ 通过 prompt_id {} 更新记录 {} 进度: {}%",
                          prompt_id, record_id, progress.progress_percentage);
                }

                // 发送进度事件到前端
                let progress_event = serde_json::json!({
                    "type": "outfit_generation_progress",
                    "record_id": record_id,
                    "prompt_id": prompt_id,
                    "progress_percentage": progress.progress_percentage,
                    "current_step": progress.current_step,
                    "total_steps": progress.total_steps,
                    "status_message": progress.status_message,
                    "current_node_id": progress.current_node_id
                });

                if let Err(e) = app_handle.emit("outfit_generation_progress", &progress_event) {
                    warn!("发送进度事件失败: {}", e);
                }
            }
            Ok(None) => {
                warn!("⚠️ 未找到 prompt_id {} 对应的记录", prompt_id);
            }
            Err(e) => {
                error!("❌ 查找 prompt_id {} 对应记录失败: {}", prompt_id, e);
            }
        }
    }
}

/// API配置
struct ApiConfig {
    base_url: String,
    bearer_token: String,
}

impl Default for ApiConfig {
    fn default() -> Self {
        Self {
            base_url: "https://bowongai-test--text-video-agent-fastapi-app.modal.run".to_string(),
            bearer_token: "bowong7777".to_string(),
        }
    }
}

/// 执行云端Modal生成
async fn execute_modal_cloud_generation(
    state: State<'_, AppState>,
    app_handle: AppHandle,
    request: OutfitImageGenerationRequest,
) -> Result<OutfitImageGenerationResponse, String> {
    info!("🎨 执行云端Modal穿搭图片生成: {:?}", request);
    let start_time = Utc::now();

    // 首先创建生成记录
    let record_id = create_outfit_image_record(state.clone(), request.clone()).await?;

    // 获取数据库和仓库
    let database = state.get_database();
    let outfit_repo = OutfitImageRepository::new(database.clone());

    // 更新记录为云端Modal生成类型
    if let Ok(Some(mut record)) = outfit_repo.get_record_by_id(&record_id) {
        record.generation_type = Some("modal_cloud".to_string());
        record.start_processing();
        if let Err(e) = outfit_repo.update_record(&record) {
            error!("更新记录为云端Modal类型失败: {}", e);
        }
    }

    let config = ApiConfig::default();
    let client = reqwest::Client::builder()
        .timeout(Duration::from_secs(120))
        .build()
        .map_err(|e| format!("创建HTTP客户端失败: {}", e))?;

    // 1. 提交 ComfyUI 异步任务
    let prompt = build_comfyui_prompt(&request);
    let submit_url = format!("{}/api/comfy/async/submit/task", config.base_url);

    let submit_response = client
        .post(&submit_url)
        .header("Authorization", format!("Bearer {}", config.bearer_token))
        .json(&serde_json::json!({"prompt": prompt}))
        .send()
        .await
        .map_err(|e| format!("提交ComfyUI任务失败: {}", e))?;

    let task_response: serde_json::Value = submit_response.json().await
        .map_err(|e| format!("解析任务响应失败: {}", e))?;

    let task_id = task_response["task_id"].as_str()
        .ok_or("未获取到任务ID")?;

    info!("📝 ComfyUI 任务已提交，任务ID: {}", task_id);

    // 更新记录的 ComfyUI 任务ID
    if let Ok(Some(mut record)) = outfit_repo.get_record_by_id(&record_id) {
        record.comfyui_task_id = Some(task_id.to_string());
        if let Err(e) = outfit_repo.update_record(&record) {
            error!("更新 ComfyUI 任务ID 失败: {}", e);
        }
    }

    // 2. 轮询任务状态直到完成
    let status_url = format!("{}/api/comfy/async/task/status", config.base_url);
    let mut attempts = 0;
    let max_attempts = 60; // 最多等待5分钟

    loop {
        if attempts >= max_attempts {
            // 更新记录为失败状态
            if let Ok(Some(mut record)) = outfit_repo.get_record_by_id(&record_id) {
                record.mark_failed("ComfyUI任务超时".to_string());
                let _ = outfit_repo.update_record(&record);
            }
            return Err("ComfyUI任务超时".to_string());
        }

        tokio::time::sleep(Duration::from_secs(5)).await;
        attempts += 1;

        let status_response = client
            .get(&format!("{}?task_id={}", status_url, task_id))
            .header("Authorization", format!("Bearer {}", config.bearer_token))
            .send()
            .await
            .map_err(|e| format!("查询任务状态失败: {}", e))?;

        let status: serde_json::Value = status_response.json().await
            .map_err(|e| format!("解析状态响应失败: {}", e))?;

        info!("📊 ComfyUI 任务状态: {:?}", status);

        match status["status"].as_str() {
            Some("completed") => {
                let result_urls: Vec<String> = status["result_urls"].as_array()
                    .map(|arr| arr.iter().filter_map(|v| v.as_str().map(String::from)).collect())
                    .unwrap_or_default();

                info!("✅ ComfyUI 生成完成，结果URLs: {:?}", result_urls);

                // 更新记录为完成状态
                if let Ok(Some(mut record)) = outfit_repo.get_record_by_id(&record_id) {
                    record.complete_generation(result_urls.clone());
                    if let Err(e) = outfit_repo.update_record(&record) {
                        error!("更新记录完成状态失败: {}", e);
                    }
                }

                // 发送完成事件
                let _ = app_handle.emit("outfit_generation_completed", &record_id);

                let generation_time = (Utc::now() - start_time).num_milliseconds() as u64;

                return Ok(OutfitImageGenerationResponse {
                    record_id,
                    generated_images: result_urls,
                    generation_time_ms: generation_time,
                    success: true,
                    error_message: None,
                    generation_type: Some("modal_cloud".to_string()),
                    task_id: Some(task_id.to_string()),
                });
            }
            Some("failed") => {
                let error_msg = status["error_message"].as_str()
                    .unwrap_or("ComfyUI任务失败");

                error!("❌ ComfyUI 任务失败: {}", error_msg);

                // 更新记录为失败状态
                if let Ok(Some(mut record)) = outfit_repo.get_record_by_id(&record_id) {
                    record.mark_failed(error_msg.to_string());
                    let _ = outfit_repo.update_record(&record);
                }

                return Err(error_msg.to_string());
            }
            _ => {
                // 继续等待，更新进度
                if let Ok(Some(mut record)) = outfit_repo.get_record_by_id(&record_id) {
                    record.progress = (attempts as f32 / max_attempts as f32) * 100.0;
                    let _ = outfit_repo.update_record(&record);

                    // 发送进度事件
                    let _ = app_handle.emit("outfit_generation_progress", &record_id);
                }
                continue;
            }
        }
    }
}

fn build_comfyui_prompt(request: &OutfitImageGenerationRequest) -> serde_json::Value {
    // 构建 ComfyUI 工作流 prompt
    // 这里需要根据实际的 ComfyUI 工作流结构来构建
    serde_json::json!({
        "model_id": request.model_id,
        "model_image_id": request.model_image_id,
        "product_images": request.product_image_paths,
        "prompt": request.generation_prompt.as_ref().unwrap_or(&"".to_string()),
        "style_preferences": request.style_preferences
    })
}
