// 仓库操作模块（入库、出库、盘点、批量出入库）
use serde::Deserialize;
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, Deserialize)]
pub struct StockOperationRequest {
    pub product_id: String,
    pub product_name: String,
    pub quantity: f64,
    pub price: f64,
    pub operation_time: String,
    pub warehouse_id: String,
    pub location_id: String,
    pub remark: String,
}

#[derive(Debug, Deserialize)]
pub struct StockCountRequest {
    pub items: Vec<StockCountItem>,
    pub remark: String,
}

#[derive(Debug, Deserialize)]
pub struct StockCountItem {
    pub product_id: String,
    pub actual_stock: f64,
    pub remark: String,
}

// 批量出入库请求
#[derive(Debug, Deserialize)]
pub struct BatchStockItem {
    pub product_id: String,
    pub product_name: String,
    pub quantity: f64,
    pub price: f64,
    pub operation_time: String,
    pub warehouse_id: String,
    pub warehouse_name: String,
    pub location_id: String,
    pub location_name: String,
    pub remark: String,
}

#[derive(Debug, Deserialize)]
pub struct BatchStockRequest {
    pub items: Vec<BatchStockItem>,
    pub remark: String,
}

// 入库
#[tauri::command]
pub fn stock_in(request: StockOperationRequest, username: String, real_name: String) -> Result<String, String> {
    if !check_permission(&username, "inventory_ops") {
        return Err("权限不足：没有入库操作的权限".to_string());
    }
    let mut conn_guard = DB_CONN.lock().map_err(|e| error_util::to_chinese_error(e))?;
    let conn = conn_guard.as_mut().ok_or("系统错误：数据库未初始化")?;
    let product_id = &request.product_id;
    let qty = request.quantity;
    let op_time = if request.operation_time.is_empty() {
        Local::now().format("%Y-%m-%d %H:%M:%S").to_string()
    } else {
        request.operation_time.clone()
    };

    let current: f64 = conn.query_row("SELECT COALESCE(stock,0.0) FROM products WHERE id=?1",
        [product_id], |row| row.get(0)).unwrap_or(0.0);
    let new_stock = current + qty;
    // 入库时同步更新成本价（如果有输入价格）
    if request.price > 0.0 {
        conn.execute("UPDATE products SET stock=?1, cost=?2 WHERE id=?3",
            [&new_stock.to_string(), &request.price.to_string(), product_id]).map_err(|e| error_util::to_chinese_error(e))?;
    } else if request.warehouse_id.is_empty() && request.location_id.is_empty() {
        conn.execute("UPDATE products SET stock=?1 WHERE id=?2",
            [&new_stock.to_string(), product_id]).map_err(|e| error_util::to_chinese_error(e))?;
    } else if request.location_id.is_empty() {
        conn.execute("UPDATE products SET stock=?1, warehouse_id=?2 WHERE id=?3",
            [&new_stock.to_string(), &request.warehouse_id, product_id]).map_err(|e| error_util::to_chinese_error(e))?;
    } else {
        conn.execute("UPDATE products SET stock=?1, warehouse_id=?2, location_id=?3 WHERE id=?4",
            [&new_stock.to_string(), &request.warehouse_id, &request.location_id, product_id]).map_err(|e| error_util::to_chinese_error(e))?;
    }
    let price_remark = if request.price > 0.0 { format!(" 单价:¥{:.2}", request.price) } else { String::new() };
    conn.execute(
        "INSERT INTO inventory_records (id, product_id, product_name, change_type, quantity, before_stock, after_stock, remark, created_at) VALUES (?1,?2,?3,'in',?4,?5,?6,?7,?8)",
        [&Uuid::new_v4().to_string(), product_id, &request.product_name, &qty.to_string(), &current.to_string(), &new_stock.to_string(), &format!("{}{}", request.remark, price_remark), &op_time]
    ).map_err(|e| error_util::to_chinese_error(e))?;
    log_operation(&username, &real_name, "入库", "仓库管理", &format!("商品'{}'入库{}", request.product_name, qty));
    Ok("入库成功".to_string())
}

// 出库
#[tauri::command]
pub fn stock_out(request: StockOperationRequest, username: String, real_name: String) -> Result<String, String> {
    if !check_permission(&username, "inventory_ops") {
        return Err("权限不足：没有出库操作的权限".to_string());
    }
    let mut conn_guard = DB_CONN.lock().map_err(|e| error_util::to_chinese_error(e))?;
    let conn = conn_guard.as_mut().ok_or("系统错误：数据库未初始化")?;
    let product_id = &request.product_id;
    let qty = request.quantity;
    let op_time = if request.operation_time.is_empty() {
        Local::now().format("%Y-%m-%d %H:%M:%S").to_string()
    } else {
        request.operation_time.clone()
    };

    let current: f64 = conn.query_row("SELECT COALESCE(stock,0.0) FROM products WHERE id=?1",
        [product_id], |row| row.get(0)).unwrap_or(0.0);
    if current < qty { return Err("操作失败：库存不足！当前库存: ".to_string() + &current.to_string() + ", 需求: " + &qty.to_string()); }
    let new_stock = current - qty;
    conn.execute("UPDATE products SET stock=?1 WHERE id=?2",
        [&new_stock.to_string(), product_id]).map_err(|e| error_util::to_chinese_error(e))?;
    let price_remark = if request.price > 0.0 { format!(" 单价:¥{:.2}", request.price) } else { String::new() };
    conn.execute(
        "INSERT INTO inventory_records (id, product_id, product_name, change_type, quantity, before_stock, after_stock, remark, created_at) VALUES (?1,?2,?3,'out',?4,?5,?6,?7,?8)",
        [&Uuid::new_v4().to_string(), product_id, &request.product_name, &(-qty).to_string(), &current.to_string(), &new_stock.to_string(), &format!("{}{}", request.remark, price_remark), &op_time]
    ).map_err(|e| error_util::to_chinese_error(e))?;
    log_operation(&username, &real_name, "出库", "仓库管理", &format!("商品'{}'出库{}", request.product_name, qty));
    Ok("出库成功".to_string())
}

// 批量入库
#[tauri::command]
pub fn batch_stock_in(request: BatchStockRequest, username: String, real_name: String) -> Result<String, String> {
    if !check_permission(&username, "inventory_batch") {
        return Err("权限不足：没有批量入库的权限".to_string());
    }
    let mut conn_guard = DB_CONN.lock().map_err(|e| error_util::to_chinese_error(e))?;
    let conn = conn_guard.as_mut().ok_or("系统错误：数据库未初始化")?;
    let now = Local::now().format("%Y-%m-%d %H:%M:%S").to_string();
    let mut success_count = 0;
    let mut error_msgs = Vec::new();

    for item in &request.items {
        if item.quantity <= 0.0 {
            error_msgs.push(format!("商品'{}'数量必须大于0", item.product_name));
            continue;
        }
        let op_time = if item.operation_time.is_empty() { now.clone() } else { item.operation_time.clone() };
        let current: f64 = conn.query_row("SELECT COALESCE(stock,0.0) FROM products WHERE id=?1",
            [&item.product_id], |row| row.get(0)).unwrap_or(0.0);
        let new_stock = current + item.quantity;
        if item.price > 0.0 {
            let _ = conn.execute("UPDATE products SET stock=?1, cost=?2, warehouse_id=?3, location_id=?4 WHERE id=?5",
                [&new_stock.to_string(), &item.price.to_string(), &item.warehouse_id, &item.location_id, &item.product_id]);
        } else if let Err(e) = conn.execute("UPDATE products SET stock=?1, warehouse_id=?2, location_id=?3 WHERE id=?4",
            [&new_stock.to_string(), &item.warehouse_id, &item.location_id, &item.product_id]) {
            error_msgs.push(format!("商品'{}'入库失败: {}", item.product_name, e));
            continue;
        }
        // 更新分仓库存
        if !item.warehouse_id.is_empty() {
            let _ = conn.execute(
                "INSERT INTO warehouse_stock (id, product_id, warehouse_id, warehouse_name, stock) VALUES (?1,?2,?3,?4,?5)
                 ON CONFLICT(product_id, warehouse_id) DO UPDATE SET stock = stock + ?5",
                [&Uuid::new_v4().to_string(), &item.product_id, &item.warehouse_id, &item.warehouse_name, &item.quantity.to_string()]
            );
        }
        let price_note = if item.price > 0.0 { format!(" 单价:¥{:.2}", item.price) } else { String::new() };
        let remark = format!("批量入库{} {}{}", if item.warehouse_name.is_empty() { "".to_string() } else { format!("[{}]", item.warehouse_name) }, item.remark, price_note);
        let _ = conn.execute(
            "INSERT INTO inventory_records (id, product_id, product_name, change_type, quantity, before_stock, after_stock, remark, created_at) VALUES (?1,?2,?3,'batch_in',?4,?5,?6,?7,?8)",
            [&Uuid::new_v4().to_string(), &item.product_id, &item.product_name, &item.quantity.to_string(), &current.to_string(), &new_stock.to_string(), &remark, &op_time]
        );
        success_count += 1;
    }

    let result = format!("批量入库完成：成功{}项", success_count);
    log_operation(&username, &real_name, "批量入库", "仓库管理", &result);
    if !error_msgs.is_empty() {
        return Err(format!("{}，失败{}项：{}", result, error_msgs.len(), error_msgs.join("\n")));
    }
    Ok(result)
}

// 批量出库
#[tauri::command]
pub fn batch_stock_out(request: BatchStockRequest, username: String, real_name: String) -> Result<String, String> {
    if !check_permission(&username, "inventory_batch") {
        return Err("权限不足：没有批量出库的权限".to_string());
    }
    let mut conn_guard = DB_CONN.lock().map_err(|e| error_util::to_chinese_error(e))?;
    let conn = conn_guard.as_mut().ok_or("系统错误：数据库未初始化")?;
    let now = Local::now().format("%Y-%m-%d %H:%M:%S").to_string();
    let mut success_count = 0;
    let mut error_msgs = Vec::new();

    for item in &request.items {
        if item.quantity <= 0.0 {
            error_msgs.push(format!("商品'{}'数量必须大于0", item.product_name));
            continue;
        }
        let op_time = if item.operation_time.is_empty() { now.clone() } else { item.operation_time.clone() };
        let current: f64 = conn.query_row("SELECT COALESCE(stock,0.0) FROM products WHERE id=?1",
            [&item.product_id], |row| row.get(0)).unwrap_or(0.0);
        if current < item.quantity {
            error_msgs.push(format!("商品'{}'库存不足(当前:{}, 需求:{})", item.product_name, current, item.quantity));
            continue;
        }
        let new_stock = current - item.quantity;
        if let Err(e) = conn.execute("UPDATE products SET stock=?1 WHERE id=?2",
            [&new_stock.to_string(), &item.product_id]) {
            error_msgs.push(format!("商品'{}'出库失败: {}", item.product_name, e));
            continue;
        }
        // 更新分仓库存
        if !item.warehouse_id.is_empty() {
            let _ = conn.execute(
                "INSERT INTO warehouse_stock (id, product_id, warehouse_id, warehouse_name, stock) VALUES (?1,?2,?3,?4,?5)
                 ON CONFLICT(product_id, warehouse_id) DO UPDATE SET stock = MAX(0, stock - ?5)",
                [&Uuid::new_v4().to_string(), &item.product_id, &item.warehouse_id, &item.warehouse_name, &item.quantity.to_string()]
            );
        }
        let price_note = if item.price > 0.0 { format!(" 单价:¥{:.2}", item.price) } else { String::new() };
        let remark = format!("批量出库{} {}{}", if item.warehouse_name.is_empty() { "".to_string() } else { format!("[{}]", item.warehouse_name) }, item.remark, price_note);
        let _ = conn.execute(
            "INSERT INTO inventory_records (id, product_id, product_name, change_type, quantity, before_stock, after_stock, remark, created_at) VALUES (?1,?2,?3,'batch_out',?4,?5,?6,?7,?8)",
            [&Uuid::new_v4().to_string(), &item.product_id, &item.product_name, &(-item.quantity).to_string(), &current.to_string(), &new_stock.to_string(), &remark, &op_time]
        );
        success_count += 1;
    }

    let result = format!("批量出库完成：成功{}项", success_count);
    log_operation(&username, &real_name, "批量出库", "仓库管理", &result);
    if !error_msgs.is_empty() {
        return Err(format!("{}，失败{}项：{}", result, error_msgs.len(), error_msgs.join("\n")));
    }
    Ok(result)
}

// 库存盘点
#[tauri::command]
pub fn stock_count(request: StockCountRequest, username: String, real_name: String) -> Result<String, String> {
    if !check_permission(&username, "inventory_ops") {
        return Err("权限不足：没有盘点库存的权限".to_string());
    }
    let mut conn_guard = DB_CONN.lock().map_err(|e| error_util::to_chinese_error(e))?;
    let conn = conn_guard.as_mut().ok_or("系统错误：数据库未初始化")?;
    let now = Local::now().format("%Y-%m-%d %H:%M:%S").to_string();
    let mut adjusted = 0;

    for item in &request.items {
        let current: f64 = conn.query_row("SELECT COALESCE(stock,0.0) FROM products WHERE id=?1",
            [&item.product_id], |row| row.get(0)).unwrap_or(0.0);
        if (current - item.actual_stock).abs() > 0.001 {
            let diff = item.actual_stock - current;
            conn.execute("UPDATE products SET stock=?1 WHERE id=?2",
                [&item.actual_stock.to_string(), &item.product_id]).map_err(|e| error_util::to_chinese_error(e))?;
            let item_remark = if item.remark.is_empty() {
                format!("盘点: {}", request.remark)
            } else {
                format!("盘点: {} ({})", item.remark, request.remark)
            };
            conn.execute(
                "INSERT INTO inventory_records (id, product_id, product_name, change_type, quantity, before_stock, after_stock, remark, created_at) VALUES (?1,?2,?3,'adjust',?4,?5,?6,?7,?8)",
                [&Uuid::new_v4().to_string(), &item.product_id, "", &diff.to_string(), &current.to_string(), &item.actual_stock.to_string(), &item_remark, &now]
            ).map_err(|e| error_util::to_chinese_error(e))?;
            adjusted += 1;
        }
    }
    log_operation(&username, &real_name, "库存盘点", "仓库管理", &format!("盘点完成，调整了{}项商品库存", adjusted));
    Ok("盘点完成".to_string())
}
