// 商品文档附件管理模块
use serde::{Deserialize, Serialize};
use crate::database::DB_CONN;
use crate::error_util;
use crate::permissions::check_permission;
use uuid::Uuid;
use chrono::Local;
use std::fs;

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ProductDocument {
    pub id: String,
    pub product_id: String,
    pub file_name: String,
    pub file_type: String,
    pub file_size: i64,
    pub file_data: String, // base64 encoded
    pub created_at: String,
}

#[derive(Debug, Deserialize)]
pub struct SaveDocumentRequest {
    pub product_id: String,
    pub source_path: String,
}

#[tauri::command]
pub fn save_product_document(request: SaveDocumentRequest, username: String) -> Result<ProductDocument, String> {
    if !check_permission(&username, "products_edit") {
        return Err("权限不足：没有保存商品附件的权限".to_string());
    }
    let conn_guard = DB_CONN.lock().map_err(|e| error_util::to_chinese_error(e))?;
    let conn = conn_guard.as_ref().ok_or("系统错误：数据库未初始化")?;
    
    let file_bytes = fs::read(&request.source_path).map_err(|e| format!("读取文件失败: {}", e))?;
    let file_size = file_bytes.len() as i64;
    if file_size > 20 * 1024 * 1024 {
        return Err("文件大小超过20MB限制".to_string());
    }
    
    // 提取文件名和扩展名
    let path = std::path::Path::new(&request.source_path);
    let file_name = path.file_name()
        .and_then(|n| n.to_str())
        .unwrap_or("unknown")
        .to_string();
    let ext = path.extension()
        .and_then(|e| e.to_str())
        .unwrap_or("")
        .to_lowercase();
    let file_type = match ext.as_str() {
        "pdf" => "application/pdf",
        "doc" | "docx" => "application/msword",
        "xls" | "xlsx" => "application/vnd.ms-excel",
        "ppt" | "pptx" => "application/vnd.ms-powerpoint",
        "dwg" | "dxf" => "application/acad",
        "txt" => "text/plain",
        "png" => "image/png",
        "jpg" | "jpeg" => "image/jpeg",
        _ => "application/octet-stream",
    };
    
    let id = Uuid::new_v4().to_string();
    let now = Local::now().format("%Y-%m-%d %H:%M:%S").to_string();
    let b64 = base64::Engine::encode(&base64::engine::general_purpose::STANDARD, &file_bytes);
    let file_name_owned = file_name.to_string();
    let file_type_owned = file_type.to_string();
    
    conn.execute(
        "INSERT INTO product_documents (id, product_id, file_name, file_type, file_size, file_data, created_at) 
         VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)",
        [&id, &request.product_id, &file_name_owned, &file_type_owned, &file_size.to_string(), &b64, &now]
    ).map_err(|e| error_util::to_chinese_error(e))?;
    
    Ok(ProductDocument {
        id,
        product_id: request.product_id,
        file_name: file_name_owned,
        file_type: file_type_owned,
        file_size,
        file_data: b64,
        created_at: now,
    })
}

#[tauri::command]
pub fn get_product_documents(product_id: String) -> Result<Vec<ProductDocument>, String> {
    let conn_guard = DB_CONN.lock().map_err(|e| e.to_string())?;
    let conn = conn_guard.as_ref().ok_or("Database not initialized")?;
    
    let mut stmt = conn.prepare(
        "SELECT id, product_id, file_name, file_type, file_size, file_data, created_at 
         FROM product_documents WHERE product_id=?1 ORDER BY created_at DESC"
    ).map_err(|e| e.to_string())?;
    
    let docs = stmt.query_map([&product_id], |row| {
        Ok(ProductDocument {
            id: row.get(0)?,
            product_id: row.get(1)?,
            file_name: row.get(2)?,
            file_type: row.get(3)?,
            file_size: row.get(4)?,
            file_data: row.get(5)?,
            created_at: row.get(6)?,
        })
    }).map_err(|e| e.to_string())?;
    
    let mut result = Vec::new();
    for doc in docs {
        result.push(doc.map_err(|e| e.to_string())?);
    }
    Ok(result)
}

#[tauri::command]
pub fn read_file_base64(source_path: String) -> Result<String, String> {
    let bytes = std::fs::read(&source_path).map_err(|e| format!("读取文件失败: {}", e))?;
    Ok(base64::Engine::encode(&base64::engine::general_purpose::STANDARD, &bytes))
}

#[tauri::command]
pub fn delete_product_document(doc_id: String, username: String) -> Result<String, String> {
    if !check_permission(&username, "products_edit") {
        return Err("权限不足：没有删除商品附件的权限".to_string());
    }
    let conn_guard = DB_CONN.lock().map_err(|e| error_util::to_chinese_error(e))?;
    let conn = conn_guard.as_ref().ok_or("系统错误：数据库未初始化")?;
    
    conn.execute("DELETE FROM product_documents WHERE id=?1", [&doc_id])
        .map_err(|e| error_util::to_chinese_error(e))?;
    
    Ok("删除成功".to_string())
}
