// 包件管理模块
use serde::{Deserialize, Serialize};
use crate::models::*;
use crate::database::DB_CONN;
use crate::operation_logs::log_operation;
use crate::error_util;
use crate::permissions::check_permission;
use uuid::Uuid;
use chrono::Local;

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ProductPackageFull {
    pub id: String,
    pub product_id: String,
    pub product_name: String,
    pub package_name: String,
    pub package_code: String,
    pub quantity: i32,
    pub is_shared: bool,
    pub shared_products: String,
    pub sort_order: i32,
    pub created_at: String,
}

#[tauri::command]
pub fn add_product_package(request: CreatePackageRequest, username: String, real_name: String) -> Result<ProductPackageFull, 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 id = Uuid::new_v4().to_string();
    let now = Local::now().format("%Y-%m-%d %H:%M:%S").to_string();
    
    let shared_products_json = serde_json::to_string(&request.shared_products).unwrap_or_default();

    let pname: String = conn.query_row("SELECT name FROM products WHERE id=?1",
        [&request.product_id], |row| row.get(0)).map_err(|e| error_util::to_chinese_error(e))?;

    conn.execute(
        "INSERT INTO product_packages (id, product_id, package_name, package_code, quantity, is_shared, shared_products, sort_order, created_at) 
         VALUES (?1,?2,?3,?4,?5,?6,?7,?8,?9)",
        [&id, &request.product_id, &request.package_name, &request.package_code,
         &request.quantity.to_string(), &(request.is_shared as i32).to_string(),
         &shared_products_json, &request.sort_order.to_string(), &now]
    ).map_err(|e| error_util::to_chinese_error(e))?;

    log_operation(&username, &real_name, "添加", "包件管理", &format!("添加包件: {} (商品: {})", request.package_name, pname));

    Ok(ProductPackageFull {
        id, product_id: request.product_id, product_name: pname,
        package_name: request.package_name, package_code: request.package_code,
        quantity: request.quantity, is_shared: request.is_shared,
        shared_products: shared_products_json, sort_order: request.sort_order, created_at: now,
    })
}

#[tauri::command]
pub fn get_product_packages(product_id: String) -> Result<Vec<ProductPackageFull>, 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 mut stmt = conn.prepare(
        "SELECT p.id, p.product_id, pr.name, p.package_name, p.package_code, p.quantity, p.is_shared, p.shared_products, p.sort_order, p.created_at 
         FROM product_packages p JOIN products pr ON p.product_id=pr.id 
         WHERE p.product_id=?1 OR (p.is_shared=1 AND p.shared_products LIKE '%' || ?1 || '%')
         ORDER BY p.sort_order"
    ).map_err(|e| error_util::to_chinese_error(e))?;
    
    let packages = stmt.query_map([&product_id, &product_id], |row| {
        Ok(ProductPackageFull {
            id: row.get(0)?, product_id: row.get(1)?, product_name: row.get(2)?,
            package_name: row.get(3)?, package_code: row.get(4)?, quantity: row.get(5)?,
            is_shared: row.get::<_, i32>(6)? != 0,
            shared_products: row.get::<_, Option<String>>(7)?.unwrap_or_default(),
            sort_order: row.get(8)?, created_at: row.get(9)?,
        })
    }).map_err(|e| error_util::to_chinese_error(e))?;
    
    packages.collect::<Result<Vec<_>, _>>().map_err(|e| error_util::to_chinese_error(e))
}

#[tauri::command]
pub fn get_all_packages() -> Result<Vec<ProductPackageFull>, 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 mut stmt = conn.prepare(
        "SELECT p.id, p.product_id, pr.name, p.package_name, p.package_code, p.quantity, p.is_shared, p.shared_products, p.sort_order, p.created_at 
         FROM product_packages p JOIN products pr ON p.product_id=pr.id 
         ORDER BY p.sort_order"
    ).map_err(|e| error_util::to_chinese_error(e))?;
    
    let packages = stmt.query_map([], |row| {
        Ok(ProductPackageFull {
            id: row.get(0)?, product_id: row.get(1)?, product_name: row.get(2)?,
            package_name: row.get(3)?, package_code: row.get(4)?, quantity: row.get(5)?,
            is_shared: row.get::<_, i32>(6)? != 0,
            shared_products: row.get::<_, Option<String>>(7)?.unwrap_or_default(),
            sort_order: row.get(8)?, created_at: row.get(9)?,
        })
    }).map_err(|e| error_util::to_chinese_error(e))?;
    
    packages.collect::<Result<Vec<_>, _>>().map_err(|e| error_util::to_chinese_error(e))
}

#[tauri::command]
pub fn delete_product_package(package_id: String, username: String, real_name: 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("系统错误：数据库未初始化")?;
    let pkg_name: String = conn.query_row("SELECT package_name FROM product_packages WHERE id=?1", [&package_id], |row| row.get(0)).unwrap_or_default();
    conn.execute("DELETE FROM product_packages WHERE id=?1", [&package_id])
        .map_err(|e| error_util::to_chinese_error(e))?;
    log_operation(&username, &real_name, "删除", "包件管理", &format!("删除包件: '{}'", pkg_name));
    Ok("删除成功".to_string())
}