use tauri::{command, State};
use std::sync::{Arc, Mutex};
use std::collections::HashMap;
use tracing::{info, error, warn};
use lazy_static::lazy_static;

use crate::data::models::watermark::{
    WatermarkDetectionConfig, WatermarkRemovalConfig, WatermarkConfig,
    WatermarkTemplate, BatchWatermarkTask, WatermarkOperation,
    BatchTaskStatus, BatchProgress, WatermarkDetectionResult,
    WatermarkProcessingResult
};
use crate::business::services::{
    watermark_detection_service::WatermarkDetectionService,
    watermark_removal_service::WatermarkRemovalService,
    watermark_addition_service::WatermarkAdditionService,
    batch_watermark_processor::BatchWatermarkProcessor,
    task_manager::TASK_MANAGER,
};

// 全局模板存储
lazy_static! {
    static ref TEMPLATE_STORAGE: Mutex<HashMap<String, WatermarkTemplate>> = {
        let mut templates = HashMap::new();

        // 添加一些默认模板
        let default_templates = create_default_templates();
        for template in default_templates {
            templates.insert(template.id.clone(), template);
        }

        Mutex::new(templates)
    };
}

// 创建默认模板
fn create_default_templates() -> Vec<WatermarkTemplate> {
    use crate::data::models::watermark::{WatermarkCategory, WatermarkType};

    vec![
        WatermarkTemplate {
            id: "template_1".to_string(),
            name: "公司Logo".to_string(),
            file_path: "watermarks/logo.png".to_string(),
            thumbnail_path: Some("watermarks/thumbnails/logo.jpg".to_string()),
            category: WatermarkCategory::Logo,
            watermark_type: WatermarkType::Image,
            file_size: 2048,
            width: Some(200),
            height: Some(100),
            description: Some("公司标准Logo水印".to_string()),
            tags: vec!["logo".to_string(), "公司".to_string()],
            is_active: true,
            created_at: chrono::Utc::now(),
            updated_at: chrono::Utc::now(),
        },
        WatermarkTemplate {
            id: "template_2".to_string(),
            name: "版权声明".to_string(),
            file_path: "watermarks/copyright.png".to_string(),
            thumbnail_path: Some("watermarks/thumbnails/copyright.jpg".to_string()),
            category: WatermarkCategory::Copyright,
            watermark_type: WatermarkType::Text,
            file_size: 1024,
            width: Some(300),
            height: Some(50),
            description: Some("标准版权声明水印".to_string()),
            tags: vec!["版权".to_string(), "声明".to_string()],
            is_active: true,
            created_at: chrono::Utc::now(),
            updated_at: chrono::Utc::now(),
        },
    ]
}
use crate::AppState;

/// 检测视频中的水印
#[command]
pub async fn detect_watermarks_in_video(
    state: State<'_, AppState>,
    material_id: String,
    video_path: String,
    config: WatermarkDetectionConfig,
) -> Result<WatermarkDetectionResult, String> {
    info!(
        material_id = %material_id,
        video_path = %video_path,
        "Tauri命令: 检测视频水印"
    );

    let repository = {
        let repo_guard = state.material_repository.lock().unwrap();
        repo_guard.as_ref()
            .ok_or_else(|| "Material repository not initialized".to_string())?
            .clone()
    };

    WatermarkDetectionService::detect_watermarks_in_video(
        &material_id,
        &video_path,
        &config,
        Arc::new(repository.clone()),
    )
    .await
    .map_err(|e| {
        error!(error = %e, "检测视频水印失败");
        e.to_string()
    })
}

/// 检测图片中的水印
#[command]
pub async fn detect_watermarks_in_image(
    material_id: String,
    image_path: String,
    config: WatermarkDetectionConfig,
) -> Result<WatermarkDetectionResult, String> {
    info!(
        material_id = %material_id,
        image_path = %image_path,
        "Tauri命令: 检测图片水印"
    );

    WatermarkDetectionService::detect_watermarks_in_image(
        &material_id,
        &image_path,
        &config,
    )
    .await
    .map_err(|e| {
        error!(error = %e, "检测图片水印失败");
        e.to_string()
    })
}

/// 移除视频中的水印
#[command]
pub async fn remove_watermarks_from_video(
    state: State<'_, AppState>,
    material_id: String,
    input_path: String,
    output_path: String,
    config: WatermarkRemovalConfig,
) -> Result<WatermarkProcessingResult, String> {
    info!(
        material_id = %material_id,
        input_path = %input_path,
        output_path = %output_path,
        "Tauri命令: 移除视频水印"
    );

    let repository = {
        let repo_guard = state.material_repository.lock().unwrap();
        repo_guard.as_ref()
            .ok_or_else(|| "Material repository not initialized".to_string())?
            .clone()
    };

    WatermarkRemovalService::remove_watermarks_from_video(
        &material_id,
        &input_path,
        &output_path,
        &config,
        Arc::new(repository.clone()),
    )
    .await
    .map_err(|e| {
        error!(error = %e, "移除视频水印失败");
        e.to_string()
    })
}

/// 移除图片中的水印
#[command]
pub async fn remove_watermarks_from_image(
    material_id: String,
    input_path: String,
    output_path: String,
    config: WatermarkRemovalConfig,
) -> Result<WatermarkProcessingResult, String> {
    info!(
        material_id = %material_id,
        input_path = %input_path,
        output_path = %output_path,
        "Tauri命令: 移除图片水印"
    );

    WatermarkRemovalService::remove_watermarks_from_image(
        &material_id,
        &input_path,
        &output_path,
        &config,
    )
    .await
    .map_err(|e| {
        error!(error = %e, "移除图片水印失败");
        e.to_string()
    })
}

/// 为视频添加水印
#[command]
pub async fn add_watermark_to_video(
    state: State<'_, AppState>,
    material_id: String,
    input_path: String,
    output_path: String,
    watermark_path: String,
    config: WatermarkConfig,
) -> Result<WatermarkProcessingResult, String> {
    info!(
        material_id = %material_id,
        input_path = %input_path,
        output_path = %output_path,
        watermark_path = %watermark_path,
        "Tauri命令: 为视频添加水印"
    );

    let repository = {
        let repo_guard = state.material_repository.lock().unwrap();
        repo_guard.as_ref()
            .ok_or_else(|| "Material repository not initialized".to_string())?
            .clone()
    };

    WatermarkAdditionService::add_watermark_to_video(
        &material_id,
        &input_path,
        &output_path,
        &watermark_path,
        &config,
        Arc::new(repository.clone()),
    )
    .await
    .map_err(|e| {
        error!(error = %e, "为视频添加水印失败");
        e.to_string()
    })
}

/// 为图片添加水印
#[command]
pub async fn add_watermark_to_image(
    material_id: String,
    input_path: String,
    output_path: String,
    watermark_path: String,
    config: WatermarkConfig,
) -> Result<WatermarkProcessingResult, String> {
    info!(
        material_id = %material_id,
        input_path = %input_path,
        output_path = %output_path,
        watermark_path = %watermark_path,
        "Tauri命令: 为图片添加水印"
    );

    WatermarkAdditionService::add_watermark_to_image(
        &material_id,
        &input_path,
        &output_path,
        &watermark_path,
        &config,
    )
    .await
    .map_err(|e| {
        error!(error = %e, "为图片添加水印失败");
        e.to_string()
    })
}

/// 启动批量水印处理任务
#[command]
pub async fn start_batch_watermark_task(
    state: State<'_, AppState>,
    operation: WatermarkOperation,
    material_ids: Vec<String>,
    config: serde_json::Value,
) -> Result<String, String> {
    info!(
        operation = ?operation,
        material_count = material_ids.len(),
        "Tauri命令: 启动批量水印处理任务"
    );

    let task_id = uuid::Uuid::new_v4().to_string();
    
    let now = chrono::Utc::now();
    let task = BatchWatermarkTask {
        task_id: task_id.clone(),
        operation,
        material_ids: material_ids.clone(),
        config,
        status: BatchTaskStatus::Pending,
        progress: BatchProgress {
            total_items: material_ids.len() as u32,
            processed_items: 0,
            failed_items: 0,
            current_item: None,
            progress_percentage: 0.0,
            estimated_remaining_ms: None,
            errors: Vec::new(),
            detection_results: Vec::new(),
            processing_results: Vec::new(),
        },
        created_at: now,
        updated_at: now,
        started_at: None,
        completed_at: None,
    };

    let repository = {
        let repo_guard = state.material_repository.lock().unwrap();
        repo_guard.as_ref()
            .ok_or_else(|| "Material repository not initialized".to_string())?
            .clone()
    };

    // 在后台启动任务
    let task_id_clone = task_id.clone();
    tokio::spawn(async move {
        if let Err(e) = BatchWatermarkProcessor::start_batch_task(task, Arc::new(repository.clone())).await {
            error!(task_id = %task_id_clone, error = %e, "批量水印处理任务失败");
        }
    });

    Ok(task_id)
}

/// 获取水印模板列表
#[command]
pub async fn get_watermark_templates(
    category: Option<String>,
    watermark_type: Option<String>,
) -> Result<Vec<WatermarkTemplate>, String> {
    info!(
        category = ?category,
        watermark_type = ?watermark_type,
        "Tauri命令: 获取水印模板列表"
    );

    // 从内存存储获取模板
    let storage = TEMPLATE_STORAGE.lock().unwrap();
    let mut templates: Vec<WatermarkTemplate> = storage.values()
        .filter(|template| template.is_active)
        .cloned()
        .collect();

    // 根据分类过滤
    if let Some(cat) = category {
        templates.retain(|t| format!("{:?}", t.category).contains(&cat));
    }

    // 根据类型过滤
    if let Some(wtype) = watermark_type {
        templates.retain(|t| format!("{:?}", t.watermark_type).contains(&wtype));
    }

    info!(template_count = templates.len(), "返回水印模板列表");
    Ok(templates)
}

/// 上传水印模板
#[command]
pub async fn upload_watermark_template(
    name: String,
    file_path: String,
    category: String,
    watermark_type: String,
    description: Option<String>,
    tags: Vec<String>,
) -> Result<WatermarkTemplate, String> {
    info!(
        name = %name,
        file_path = %file_path,
        category = %category,
        watermark_type = %watermark_type,
        "Tauri命令: 上传水印模板"
    );

    // 简单实现：创建模板记录
    // 在实际应用中，这里应该：
    // 1. 验证文件存在和格式
    // 2. 复制文件到模板目录
    // 3. 生成缩略图
    // 4. 保存到数据库

    let template = WatermarkTemplate {
        id: uuid::Uuid::new_v4().to_string(),
        name: name.clone(),
        file_path: format!("watermarks/templates/{}", file_path), // 模拟路径
        thumbnail_path: Some(format!("watermarks/thumbnails/{}.jpg", name)),
        category: match category.as_str() {
            "Logo" => crate::data::models::watermark::WatermarkCategory::Logo,
            "Copyright" => crate::data::models::watermark::WatermarkCategory::Copyright,
            "Signature" => crate::data::models::watermark::WatermarkCategory::Signature,
            "Decoration" => crate::data::models::watermark::WatermarkCategory::Decoration,
            "Custom" => crate::data::models::watermark::WatermarkCategory::Custom,
            _ => return Err(format!("无效的分类: {}", category)),
        },
        watermark_type: match watermark_type.as_str() {
            "Image" => crate::data::models::watermark::WatermarkType::Image,
            "Vector" => crate::data::models::watermark::WatermarkType::Vector,
            "Text" => crate::data::models::watermark::WatermarkType::Text,
            "Animated" => crate::data::models::watermark::WatermarkType::Animated,
            _ => return Err(format!("无效的水印类型: {}", watermark_type)),
        },
        file_size: 1024, // 模拟文件大小
        width: Some(200),
        height: Some(100),
        description,
        tags,
        is_active: true,
        created_at: chrono::Utc::now(),
        updated_at: chrono::Utc::now(),
    };

    // 将模板添加到存储中
    {
        let mut storage = TEMPLATE_STORAGE.lock().unwrap();
        storage.insert(template.id.clone(), template.clone());
    }

    info!(template_id = %template.id, name = %template.name, "水印模板上传成功");
    Ok(template)
}

/// 删除水印模板
#[command]
pub async fn delete_watermark_template(
    template_id: String,
) -> Result<bool, String> {
    info!(
        template_id = %template_id,
        "Tauri命令: 删除水印模板"
    );

    // 从存储中删除模板
    let mut storage = TEMPLATE_STORAGE.lock().unwrap();
    let removed = storage.remove(&template_id);

    match removed {
        Some(_) => {
            info!(template_id = %template_id, "水印模板删除成功");
            Ok(true)
        }
        None => {
            warn!(template_id = %template_id, "要删除的模板不存在");
            Err(format!("模板不存在: {}", template_id))
        }
    }
}

/// 获取批量任务状态
#[command]
pub async fn get_batch_task_status(
    task_id: String,
) -> Result<BatchWatermarkTask, String> {
    info!(
        task_id = %task_id,
        "Tauri命令: 获取批量任务状态"
    );

    match TASK_MANAGER.get_task(&task_id) {
        Some(task) => {
            info!(
                task_id = %task_id,
                status = ?task.status,
                progress = task.progress.progress_percentage,
                "返回任务状态"
            );
            Ok(task)
        }
        None => {
            warn!(task_id = %task_id, "任务不存在");
            Err(format!("任务不存在: {}", task_id))
        }
    }
}

/// 获取水印模板缩略图
#[command]
pub async fn get_watermark_template_thumbnail(
    template_id: String,
) -> Result<String, String> {
    info!(
        template_id = %template_id,
        "Tauri命令: 获取水印模板缩略图"
    );

    let storage = TEMPLATE_STORAGE.lock().unwrap();

    match storage.get(&template_id) {
        Some(template) => {
            // 模拟生成base64缩略图数据
            // 在实际应用中，这里应该读取实际的缩略图文件
            let mock_thumbnail = generate_mock_thumbnail(&template.name, &template.watermark_type);
            info!(template_id = %template_id, "返回模板缩略图");
            Ok(mock_thumbnail)
        }
        None => {
            warn!(template_id = %template_id, "模板不存在");
            Err(format!("模板不存在: {}", template_id))
        }
    }
}

// 生成模拟缩略图数据
fn generate_mock_thumbnail(name: &str, watermark_type: &crate::data::models::watermark::WatermarkType) -> String {
    // 返回一个简单的彩色方块作为缩略图
    let (bg_color, text_color, type_name) = match watermark_type {
        crate::data::models::watermark::WatermarkType::Image => ("lightblue", "darkblue", "图片"),
        crate::data::models::watermark::WatermarkType::Text => ("lightpink", "purple", "文字"),
        crate::data::models::watermark::WatermarkType::Vector => ("lightgreen", "darkgreen", "矢量"),
        crate::data::models::watermark::WatermarkType::Animated => ("lightyellow", "orange", "动画"),
    };

    let svg_content = format!(
        r#"<svg width="200" height="100" xmlns="http://www.w3.org/2000/svg">
            <rect width="200" height="100" fill="{}"/>
            <text x="100" y="45" text-anchor="middle" fill="{}" font-family="Arial" font-size="14" font-weight="bold">{}</text>
            <text x="100" y="65" text-anchor="middle" fill="{}" font-family="Arial" font-size="10">{}水印</text>
        </svg>"#,
        bg_color, text_color, name, text_color, type_name
    );

    use base64::{Engine as _, engine::general_purpose};
    let encoded = general_purpose::STANDARD.encode(svg_content.as_bytes());
    format!("data:image/svg+xml;base64,{}", encoded)
}

/// 取消批量任务
#[command]
pub async fn cancel_batch_task(
    task_id: String,
) -> Result<bool, String> {
    info!(
        task_id = %task_id,
        "Tauri命令: 取消批量任务"
    );

    // TODO: 实现任务取消逻辑
    Ok(true)
}
