use serde::{Deserialize, Serialize};
use chrono::{DateTime, Utc};

/// 导出记录实体模型
/// 遵循 Tauri 开发规范的数据模型设计原则
/// 记录每次导出操作的详细信息
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ExportRecord {
    pub id: String,
    pub matching_result_id: String, // 关联的匹配结果ID
    pub project_id: String,         // 项目ID
    pub template_id: String,        // 模板ID
    pub export_type: ExportType,    // 导出类型
    pub export_format: ExportFormat, // 导出格式
    pub file_path: String,          // 导出文件路径
    pub file_size: Option<u64>,     // 文件大小（字节）
    pub export_status: ExportStatus, // 导出状态
    pub export_duration_ms: u64,   // 导出耗时（毫秒）
    pub error_message: Option<String>, // 错误信息
    pub metadata: Option<String>,   // JSON格式的额外元数据
    pub created_at: DateTime<Utc>,
    pub updated_at: DateTime<Utc>,
    pub is_active: bool,
}

/// 导出类型
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub enum ExportType {
    /// 剪映导出 V1
    JianYingV1,
    /// 剪映导出 V2
    JianYingV2,
    /// JSON格式导出
    Json,
    /// CSV格式导出
    Csv,
    /// Excel格式导出
    Excel,
}

impl Default for ExportType {
    fn default() -> Self {
        Self::JianYingV2
    }
}

/// 导出格式
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub enum ExportFormat {
    /// JSON文件
    Json,
    /// CSV文件
    Csv,
    /// Excel文件
    Excel,
    /// 其他格式
    Other(String),
}

impl Default for ExportFormat {
    fn default() -> Self {
        Self::Json
    }
}

/// 导出状态
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub enum ExportStatus {
    /// 导出成功
    Success,
    /// 导出失败
    Failed,
    /// 导出进行中
    InProgress,
    /// 导出被取消
    Cancelled,
}

impl Default for ExportStatus {
    fn default() -> Self {
        Self::Success
    }
}

impl ExportRecord {
    /// 创建新的导出记录实例
    pub fn new(
        id: String,
        matching_result_id: String,
        project_id: String,
        template_id: String,
        export_type: ExportType,
        export_format: ExportFormat,
        file_path: String,
    ) -> Self {
        let now = Utc::now();
        Self {
            id,
            matching_result_id,
            project_id,
            template_id,
            export_type,
            export_format,
            file_path,
            file_size: None,
            export_status: ExportStatus::InProgress,
            export_duration_ms: 0,
            error_message: None,
            metadata: None,
            created_at: now,
            updated_at: now,
            is_active: true,
        }
    }

    /// 标记导出成功
    pub fn mark_success(&mut self, file_size: Option<u64>, duration_ms: u64) {
        self.export_status = ExportStatus::Success;
        self.file_size = file_size;
        self.export_duration_ms = duration_ms;
        self.updated_at = Utc::now();
    }

    /// 标记导出失败
    pub fn mark_failed(&mut self, error_message: String, duration_ms: u64) {
        self.export_status = ExportStatus::Failed;
        self.error_message = Some(error_message);
        self.export_duration_ms = duration_ms;
        self.updated_at = Utc::now();
    }

    /// 设置元数据
    pub fn set_metadata(&mut self, metadata: String) {
        self.metadata = Some(metadata);
        self.updated_at = Utc::now();
    }

    /// 获取导出类型的显示名称
    pub fn get_export_type_display(&self) -> &'static str {
        match self.export_type {
            ExportType::JianYingV1 => "剪映导出 V1",
            ExportType::JianYingV2 => "剪映导出 V2",
            ExportType::Json => "JSON导出",
            ExportType::Csv => "CSV导出",
            ExportType::Excel => "Excel导出",
        }
    }

    /// 获取导出状态的显示名称
    pub fn get_export_status_display(&self) -> &'static str {
        match self.export_status {
            ExportStatus::Success => "成功",
            ExportStatus::Failed => "失败",
            ExportStatus::InProgress => "进行中",
            ExportStatus::Cancelled => "已取消",
        }
    }
}

/// 创建导出记录请求
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CreateExportRecordRequest {
    pub matching_result_id: String,
    pub export_type: ExportType,
    pub export_format: ExportFormat,
    pub file_path: String,
    pub metadata: Option<String>,
}

/// 导出记录查询选项
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ExportRecordQueryOptions {
    pub project_id: Option<String>,
    pub matching_result_id: Option<String>,
    pub template_id: Option<String>,
    pub export_type: Option<ExportType>,
    pub export_status: Option<ExportStatus>,
    pub limit: Option<u32>,
    pub offset: Option<u32>,
    pub search_keyword: Option<String>,
    pub sort_by: Option<String>, // "created_at", "export_duration_ms", "file_size"
    pub sort_order: Option<String>, // "asc", "desc"
    pub date_range: Option<DateRange>,
}

/// 日期范围
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DateRange {
    pub start_date: DateTime<Utc>,
    pub end_date: DateTime<Utc>,
}

/// 导出记录统计信息
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ExportRecordStatistics {
    pub total_exports: u32,
    pub successful_exports: u32,
    pub failed_exports: u32,
    pub total_file_size: u64,
    pub average_export_duration_ms: u64,
    pub export_type_counts: std::collections::HashMap<String, u32>,
}
