// 销售管理模块
use serde::Deserialize;
use rusqlite::Connection;
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;

/// 判断订单状态是否需要扣减库存
fn status_deducts_stock(status: &str) -> bool {
    matches!(status, "shipped" | "received" | "invoiced" | "paid" | "completed")
}
/// 判断订单状态是否需要生成应收账单
fn status_generates_billing(status: &str) -> bool {
    matches!(status, "invoiced" | "paid")
}

#[derive(Debug, Deserialize)]
pub struct CreateSaleOrderRequest {
    pub customer_id: String,
    pub customer_name: String,
    pub items: Vec<SaleOrderItemInput>,
    pub remark: String,
    pub status: Option<String>,
}

#[derive(Debug, Deserialize)]
pub struct SaleOrderItemInput {
    pub product_id: String,
    pub product_name: String,
    pub quantity: i32,
    pub price: f64,
}

#[derive(Debug, Deserialize)]
pub struct UpdateOrderStatusRequest {
    pub order_id: String,
    pub new_status: String,
}

#[tauri::command]
pub fn create_sale_order(request: CreateSaleOrderRequest, username: String, real_name: String) -> Result<SaleOrder, String> {
    if !check_permission(&username, "sales_create") {
        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 tx = conn.transaction().map_err(|e| error_util::to_chinese_error(e))?;
    
    let id = Uuid::new_v4().to_string();
    let order_no = format!("SO{}", Local::now().format("%Y%m%d%H%M%S"));
    let now = Local::now().format("%Y-%m-%d %H:%M:%S").to_string();
    let mut total_amount = 0.0;
    
    for item in &request.items {
        total_amount += item.quantity as f64 * item.price;
    }
    
    let status = request.status.clone().unwrap_or_else(|| "pending".to_string());
    
    tx.execute(
        "INSERT INTO sale_orders (id, order_no, customer_id, customer_name, total_amount, status, remark, created_at) 
         VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)",
        [&id, &order_no, &request.customer_id, &request.customer_name, &total_amount.to_string(), &status, &request.remark, &now]
    ).map_err(|e| error_util::to_chinese_error(e))?;
    
    let is_completed = status_deducts_stock(&status);
    
    for item in &request.items {
        tx.execute(
            "INSERT INTO sale_order_items (id, order_id, product_id, product_name, quantity, price, amount) 
             VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)",
            [&Uuid::new_v4().to_string(), &id, &item.product_id, &item.product_name,
             &item.quantity.to_string(), &item.price.to_string(), &(item.quantity as f64 * item.price).to_string()]
        ).map_err(|e| error_util::to_chinese_error(e))?;
        
        if is_completed {
            // 检查并扣减库存
            let current_stock: f64 = {
                let mut stmt = tx.prepare("SELECT stock FROM products WHERE id = ?1")
                    .map_err(|e| error_util::to_chinese_error(e))?;
                stmt.query_row([&item.product_id], |row| {
                    let stock: f64 = row.get(0)?;
                    Ok(stock)
                }).map_err(|e| error_util::to_chinese_error(e))?
            };
            
            let quantity = item.quantity as f64;
            
            if current_stock < quantity {
                return Err(format!("商品 '{}' 库存不足,当前库存: {:.2}, 需求数量: {:.2}",
                    item.product_name, current_stock, quantity));
            }
            
            let new_stock = current_stock - quantity;
            tx.execute(
                "UPDATE products SET stock = ?1 WHERE id = ?2",
                [&new_stock.to_string(), &item.product_id]
            ).map_err(|e| error_util::to_chinese_error(e))?;

            tx.execute(
                "INSERT INTO inventory_records (id, product_id, product_name, change_type, quantity, before_stock, after_stock, remark, created_at) 
                 VALUES (?1, ?2, ?3, 'sale', ?4, ?5, ?6, ?7, ?8)",
                [&Uuid::new_v4().to_string(), &item.product_id, &item.product_name,
                 &(-item.quantity).to_string(), &current_stock.to_string(), &new_stock.to_string(),
                 &format!("销售订单: {}", order_no), &now]
            ).map_err(|e| error_util::to_chinese_error(e))?;
        }
    }

    // 自动生成应收账单（检查是否已存在，避免重复）
    if is_completed {
        let existing: i64 = tx.query_row(
            "SELECT COUNT(*) FROM billing_records WHERE order_id=?1", [&id], |row| row.get(0)
        ).unwrap_or(0);
        if existing == 0 {
            tx.execute(
                "INSERT INTO billing_records (id, party_type, party_id, party_name, order_id, order_no, amount, paid_amount, bill_type, bill_date, due_date, status, remark, created_at) 
                 VALUES (?1,'customer',?2,?3,?4,?5,?6,0.0,'应收货款',?7,'','unpaid','自动生成',?7)",
                [&Uuid::new_v4().to_string(), &request.customer_id, &request.customer_name,
                 &id, &order_no, &total_amount.to_string(), &now]
            ).map_err(|e| error_util::to_chinese_error(e))?;
        }
    }
    
    tx.commit().map_err(|e| error_util::to_chinese_error(e))?;
    
    log_operation(&username, &real_name, "创建销售订单", "销售管理", &format!("订单号{} 客户{} 金额:{}", order_no, request.customer_name, total_amount));
    
    Ok(SaleOrder {
        id,
        order_no,
        customer_id: request.customer_id,
        customer_name: request.customer_name,
        total_amount,
        status,
        remark: request.remark,
        created_at: now,
        is_invoiced: false,
    })
}

#[tauri::command]
pub fn batch_create_sale_orders(requests: Vec<CreateSaleOrderRequest>, username: String, real_name: String) -> Result<Vec<SaleOrder>, String> {
    let mut results = Vec::new();
    for request in requests {
        let order = create_sale_order(request, username.clone(), real_name.clone())?;
        results.push(order);
    }
    Ok(results)
}

#[tauri::command]
pub fn get_sale_orders(username: String) -> Result<Vec<SaleOrder>, String> {
    if !check_permission(&username, "sales_view") {
        return Err("权限不足：没有查看销售的权限".to_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 * FROM sale_orders ORDER BY created_at DESC").map_err(|e| e.to_string())?;
    let orders = stmt.query_map([], |row| {
        Ok(SaleOrder {
            id: row.get(0)?,
            order_no: row.get(1)?,
            customer_id: row.get(2)?,
            customer_name: row.get(3)?,
            total_amount: row.get(4)?,
            status: row.get(5)?,
            remark: row.get(6)?,
            created_at: row.get(7)?,
            is_invoiced: row.get::<_, Option<i32>>(8)?.unwrap_or(0) != 0,
        })
    }).map_err(|e| e.to_string())?;
    
    orders.collect::<Result<Vec<_>, _>>().map_err(|e| e.to_string())
}

fn get_sale_order_items_internal(conn: &Connection, order_id: &str) -> Result<Vec<SaleOrderItem>, String> {
    let mut stmt = conn.prepare("SELECT soi.id, soi.order_id, soi.product_id, soi.product_name, COALESCE(p.code,'') as product_code, COALESCE(p.model,'') as product_model, soi.quantity, soi.price, soi.amount, soi.batch_no FROM sale_order_items soi LEFT JOIN products p ON soi.product_id = p.id WHERE soi.order_id = ?1")
        .map_err(|e| e.to_string())?;
    let items = stmt.query_map([order_id], |row| {
        Ok(SaleOrderItem {
            id: row.get(0)?, order_id: row.get(1)?, product_id: row.get(2)?,
            product_name: row.get(3)?, product_code: row.get::<_, String>(4).unwrap_or_default(),
            product_model: row.get::<_, String>(5).unwrap_or_default(),
            quantity: row.get(6)?, price: row.get(7)?, amount: row.get(8)?,
            batch_no: row.get::<_, Option<String>>(9)?.unwrap_or_default()
        })
    }).map_err(|e| e.to_string())?;
    let mut result = Vec::new();
    for item in items { result.push(item.map_err(|e| e.to_string())?); }
    Ok(result)
}

#[tauri::command]
pub fn update_sale_order_status(request: UpdateOrderStatusRequest, username: String, real_name: String) -> Result<String, String> {
    if !check_permission(&username, "sales_edit") {
        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 tx = conn.transaction().map_err(|e| error_util::to_chinese_error(e))?;
    
    // 检查当前状态
    let current_status: String = tx.query_row(
        "SELECT status FROM sale_orders WHERE id=?1", [&request.order_id], |row| row.get(0)
    ).map_err(|e| error_util::to_chinese_error(e))?;
    
    // 已发货/已完成/更高级状态才扣库存
    let stock_deducted = status_deducts_stock(&current_status);

    // 扣减库存：只要新状态是需要扣库存的，且之前没扣过，就扣
    if status_deducts_stock(&request.new_status) && !stock_deducted {
        let order_no: String = tx.query_row(
            "SELECT order_no FROM sale_orders WHERE id=?1", [&request.order_id], |row| row.get(0)
        ).unwrap_or_default();
        let order_items = get_sale_order_items_internal(&tx, &request.order_id)?;
        for item in &order_items {
            let current_stock: f64 = tx.query_row("SELECT stock FROM products WHERE id = ?1",
                [&item.product_id], |row| { let stock: f64 = row.get(0)?; Ok(stock) }
            ).map_err(|e| error_util::to_chinese_error(e))?;
            let quantity = item.quantity as f64;
            if current_stock < quantity {
                return Err(format!("商品 '{}' 库存不足，当前库存: {:.2}, 需求数量: {:.2}",
                    item.product_name, current_stock, quantity));
            }
            let new_stock = current_stock - quantity;
            tx.execute("UPDATE products SET stock = ?1 WHERE id = ?2",
                [&new_stock.to_string(), &item.product_id]
            ).map_err(|e| error_util::to_chinese_error(e))?;
            let now = Local::now().format("%Y-%m-%d %H:%M:%S").to_string();
            tx.execute(
                "INSERT INTO inventory_records (id, product_id, product_name, change_type, quantity, before_stock, after_stock, remark, created_at) 
                 VALUES (?1,?2,?3,'sale',?4,?5,?6,?7,?8)",
                [&Uuid::new_v4().to_string(), &item.product_id, &item.product_name,
                 &(-item.quantity).to_string(), &current_stock.to_string(), &new_stock.to_string(),
                 &format!("销售出库: {}", order_no), &now]
            ).map_err(|e| error_util::to_chinese_error(e))?;
        }
    }
    
    // 生成应收账单：shipped/received/completed/invoiced/paid 都应生成账单（避免重复）
    let billing_statuses = ["shipped", "received", "completed", "invoiced", "paid"];
    if billing_statuses.contains(&request.new_status.as_str()) {
        if request.new_status == "invoiced" || request.new_status == "paid" {
            tx.execute("UPDATE sale_orders SET is_invoiced=1 WHERE id=?1", [&request.order_id])
                .map_err(|e| error_util::to_chinese_error(e))?;
        }
        let billing_exists: i64 = tx.query_row(
            "SELECT COUNT(*) FROM billing_records WHERE order_id=?1", [&request.order_id], |row| row.get(0)
        ).unwrap_or(0);
        if billing_exists == 0 {
            let (customer_id, customer_name, total_amount, order_no): (String, String, f64, String) = tx.query_row(
                "SELECT customer_id, customer_name, total_amount, order_no FROM sale_orders WHERE id=?1",
                [&request.order_id], |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?, row.get(3)?))
            ).map_err(|e| error_util::to_chinese_error(e))?;
            let now = Local::now().format("%Y-%m-%d %H:%M:%S").to_string();
            tx.execute(
                "INSERT INTO billing_records (id, party_type, party_id, party_name, order_id, order_no, amount, paid_amount, bill_type, bill_date, due_date, status, remark, created_at) 
                 VALUES (?1,'customer',?2,?3,?4,?5,?6,0.0,'应收货款',?7,'','unpaid','自动生成',?7)",
                [&Uuid::new_v4().to_string(), &customer_id, &customer_name, &request.order_id, &order_no, &total_amount.to_string(), &now]
            ).map_err(|e| error_util::to_chinese_error(e))?;
        }
    }
    
    // 取消操作：恢复库存
    if request.new_status == "cancelled" && stock_deducted {
        let order_items = get_sale_order_items_internal(&tx, &request.order_id)?;
        for item in &order_items {
            let current_stock: f64 = tx.query_row("SELECT stock FROM products WHERE id = ?1",
                [&item.product_id], |row| { let stock: f64 = row.get(0)?; Ok(stock) }
            ).map_err(|e| error_util::to_chinese_error(e))?;
            let new_stock = current_stock + item.quantity;
            tx.execute("UPDATE products SET stock = ?1 WHERE id = ?2",
                [&new_stock.to_string(), &item.product_id]
            ).map_err(|e| error_util::to_chinese_error(e))?;
        }
    }
    
    tx.execute(
        "UPDATE sale_orders SET status = ?1 WHERE id = ?2",
        [&request.new_status, &request.order_id]
    ).map_err(|e| error_util::to_chinese_error(e))?;
    
    tx.commit().map_err(|e| error_util::to_chinese_error(e))?;
    
    log_operation(&username, &real_name, "更新销售订单状态", "销售管理", &format!("订单{} 状态变更为{}", request.order_id, request.new_status));
    
    Ok("状态更新成功".to_string())
}

#[tauri::command]
pub fn delete_sale_order(order_id: String, username: String, real_name: String) -> Result<String, String> {
    if !check_permission(&username, "sales_edit") {
        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 tx = conn.transaction().map_err(|e| error_util::to_chinese_error(e))?;
    
    // 检查订单状态：只有已扣过库存的状态才需要恢复库存
    let (current_status, order_no): (String, String) = tx.query_row(
        "SELECT status, order_no FROM sale_orders WHERE id=?1", [&order_id], |row| Ok((row.get(0)?, row.get(1)?))
    ).unwrap_or_default();
    let stock_was_deducted = status_deducts_stock(&current_status);
    
    let order_items = get_sale_order_items_internal(&tx, &order_id)?;
    if stock_was_deducted {
        let now = Local::now().format("%Y-%m-%d %H:%M:%S").to_string();
        for item in &order_items {
            let current_stock: f64 = tx.query_row(
                "SELECT stock FROM products WHERE id = ?1",
                [&item.product_id],
                |row| {
                    let stock: f64 = row.get(0)?;
                    Ok(stock)
                }
            ).map_err(|e| error_util::to_chinese_error(e))?;
            let new_stock = current_stock + item.quantity;
            tx.execute("UPDATE products SET stock = ?1 WHERE id = ?2",
                [&new_stock.to_string(), &item.product_id]
            ).map_err(|e| error_util::to_chinese_error(e))?;
            // 记录库存变动
            tx.execute(
                "INSERT INTO inventory_records (id, product_id, product_name, change_type, quantity, before_stock, after_stock, remark, created_at) VALUES (?1,?2,?3,'sale_delete',?4,?5,?6,?7,?8)",
                [&Uuid::new_v4().to_string(), &item.product_id, &item.product_name,
                 &item.quantity.to_string(), &current_stock.to_string(), &new_stock.to_string(),
                 &format!("删除销售订单恢复库存: {}", order_id), &now]
            ).map_err(|e| error_util::to_chinese_error(e))?;
        }
    }
    
    tx.execute("DELETE FROM sale_order_items WHERE order_id = ?1", [&order_id])
        .map_err(|e| error_util::to_chinese_error(e))?;
    tx.execute("DELETE FROM billing_records WHERE order_id = ?1", [&order_id])
        .map_err(|e| error_util::to_chinese_error(e))?;
    tx.execute("DELETE FROM sale_orders WHERE id = ?1", [&order_id])
        .map_err(|e| error_util::to_chinese_error(e))?;
    
    tx.commit().map_err(|e| error_util::to_chinese_error(e))?;
    
    log_operation(&username, &real_name, "删除销售订单", "销售管理", &format!("删除订单{} 状态:{} 库存恢复:{}", order_no, current_status, stock_was_deducted));
    
    Ok("订单已删除".to_string())
}

#[tauri::command]
pub fn toggle_sale_invoice(order_id: String, invoiced: bool, username: String) -> Result<String, String> {
    if !check_permission(&username, "sales_edit") {
        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("系统错误：数据库未初始化")?;
    conn.execute("UPDATE sale_orders SET is_invoiced=?1 WHERE id=?2",
        [&(invoiced as i32).to_string(), &order_id]).map_err(|e| error_util::to_chinese_error(e))?;
    Ok(if invoiced { "已标记为已开票" } else { "已标记为未开票" }.to_string())
}

#[tauri::command]
pub fn get_sale_order_items(order_id: String) -> Result<Vec<SaleOrderItem>, String> {
    let conn_guard = DB_CONN.lock().map_err(|e| e.to_string())?;
    let conn = conn_guard.as_ref().ok_or("Database not initialized")?;
    get_sale_order_items_internal(conn, &order_id)
}

#[tauri::command]
pub fn update_sale_order_remark(order_id: String, remark: String, username: String, real_name: String) -> Result<String, String> {
    if !check_permission(&username, "sales_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("UPDATE sale_orders SET remark=?1 WHERE id=?2", [&remark, &order_id])
        .map_err(|e| error_util::to_chinese_error(e))?;
    log_operation(&username, &real_name, "编辑订单备注", "销售管理", &format!("订单{}备注已更新", order_id));
    Ok("备注更新成功".to_string())
}
