// 采购管理模块
use serde::Deserialize;
use rusqlite::Connection;
use crate::models::*;
use crate::database::DB_CONN;
use crate::sales::UpdateOrderStatusRequest;
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, "received" | "invoiced" | "paid" | "completed")
}

#[derive(Debug, Deserialize)]
pub struct CreatePurchaseOrderRequest {
    pub supplier_id: String,
    pub supplier_name: String,
    pub items: Vec<PurchaseOrderItemInput>,
    pub remark: String,
    pub status: Option<String>,
}

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

#[tauri::command]
pub fn create_purchase_order(request: CreatePurchaseOrderRequest, username: String, real_name: String) -> Result<PurchaseOrder, String> {
    if !check_permission(&username, "purchases_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!("PO{}", 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());
    let is_completed = status_deducts_stock(&status);
    
    tx.execute(
        "INSERT INTO purchase_orders (id, order_no, supplier_id, supplier_name, total_amount, status, remark, created_at) 
         VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)",
        [&id, &order_no, &request.supplier_id, &request.supplier_name, &total_amount.to_string(), &status, &request.remark, &now]
    ).map_err(|e| error_util::to_chinese_error(e))?;
    
    for item in &request.items {
        tx.execute(
            "INSERT INTO purchase_order_items (id, order_id, product_id, product_name, quantity, price, amount, batch_no, expiry_date) 
             VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9)",
            [&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(),
             &item.batch_no, &item.expiry_date]
        ).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;
            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, 'purchase', ?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,'supplier',?2,?3,?4,?5,?6,0.0,'应付货款',?7,'','unpaid','自动生成',?7)",
                [&Uuid::new_v4().to_string(), &request.supplier_id, &request.supplier_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.supplier_name, total_amount));
    
    Ok(PurchaseOrder {
        id,
        order_no,
        supplier_id: request.supplier_id,
        supplier_name: request.supplier_name,
        total_amount,
        status,
        remark: request.remark,
        created_at: now,
        is_invoiced: false,
    })
}

#[tauri::command]
pub fn get_purchase_orders(username: String) -> Result<Vec<PurchaseOrder>, String> {
    if !check_permission(&username, "purchases_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 purchase_orders ORDER BY created_at DESC").map_err(|e| e.to_string())?;
    let orders = stmt.query_map([], |row| {
        Ok(PurchaseOrder {
            id: row.get(0)?,
            order_no: row.get(1)?,
            supplier_id: row.get(2)?,
            supplier_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_purchase_order_items_internal(conn: &Connection, order_id: &str) -> Result<Vec<PurchaseOrderItem>, String> {
    let mut stmt = conn.prepare("SELECT poi.id, poi.order_id, poi.product_id, poi.product_name, COALESCE(p.code,'') as product_code, COALESCE(p.model,'') as product_model, poi.quantity, poi.price, poi.amount, poi.batch_no, poi.expiry_date FROM purchase_order_items poi LEFT JOIN products p ON poi.product_id = p.id WHERE poi.order_id = ?1")
        .map_err(|e| e.to_string())?;
    let items = stmt.query_map([order_id], |row| {
        Ok(PurchaseOrderItem {
            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(),
            expiry_date: row.get::<_, Option<String>>(10)?.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_purchase_order_status(request: UpdateOrderStatusRequest, username: String, real_name: String) -> Result<String, String> {
    if !check_permission(&username, "purchases_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 purchase_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 purchase_orders WHERE id=?1", [&request.order_id], |row| row.get(0)
        ).unwrap_or_default();
        let order_items = get_purchase_order_items_internal(&tx, &request.order_id)?;
        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) }
            ).unwrap_or(0.0);
            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,'purchase',?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 request.new_status == "cancelled" && stock_deducted {
        let order_no: String = tx.query_row(
            "SELECT order_no FROM purchase_orders WHERE id=?1", [&request.order_id], |row| row.get(0)
        ).unwrap_or_default();
        let order_items = get_purchase_order_items_internal(&tx, &request.order_id)?;
        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) }
            ).unwrap_or(0.0);
            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,'purchase_cancel',?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))?;
        }
    }

    // 生成应付账单
    let billing_statuses = ["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 purchase_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 (supplier_id, supplier_name, total_amount, order_no): (String, String, f64, String) = tx.query_row(
                "SELECT supplier_id, supplier_name, total_amount, order_no FROM purchase_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,'supplier',?2,?3,?4,?5,?6,0.0,'应付货款',?7,'','unpaid','自动生成',?7)",
                [&Uuid::new_v4().to_string(), &supplier_id, &supplier_name,
                 &request.order_id, &order_no, &total_amount.to_string(), &now]
            ).map_err(|e| error_util::to_chinese_error(e))?;
        }
    }

    tx.execute("UPDATE purchase_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_purchase_order(order_id: String, username: String, real_name: String) -> Result<String, String> {
    if !check_permission(&username, "purchases_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 purchase_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_purchase_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)
                }
            ).unwrap_or(0.0);
            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,'purchase_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 purchase_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 purchase_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_purchase_invoice(order_id: String, invoiced: bool, username: String) -> Result<String, String> {
    if !check_permission(&username, "purchases_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 purchase_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_purchase_order_items(order_id: String) -> Result<Vec<PurchaseOrderItem>, 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_purchase_order_items_internal(conn, &order_id)
}

#[tauri::command]
pub fn update_purchase_order_remark(order_id: String, remark: String, username: String, real_name: String) -> Result<String, String> {
    if !check_permission(&username, "purchases_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 purchase_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())
}
