// 退货管理模块
use serde::{Deserialize, Serialize};
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 ReturnOrder {
    pub id: String,
    pub return_no: String,
    pub return_type: String,
    pub party_id: String,
    pub party_name: String,
    pub total_amount: f64,
    pub reason: String,
    pub status: String,
    pub created_at: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ReturnOrderItem {
    pub id: String,
    pub return_id: String,
    pub product_id: String,
    pub product_name: String,
    pub quantity: f64,
    pub price: f64,
    pub amount: f64,
    pub batch_no: String,
}

#[derive(Debug, Deserialize)]
pub struct CreateReturnRequest {
    pub return_type: String,
    pub party_id: String,
    pub party_name: String,
    pub items: Vec<ReturnItemInput>,
    pub reason: String,
}

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

#[tauri::command]
pub fn create_return_order(request: CreateReturnRequest, username: String, real_name: String) -> Result<ReturnOrder, String> {
    if !check_permission(&username, "sales_edit") && !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 id = Uuid::new_v4().to_string();
    let return_no = format!("RT{}", Uuid::new_v4().to_string()[..8].to_uppercase());
    let now = Local::now().format("%Y-%m-%d %H:%M:%S").to_string();
    let mut total = 0.0;

    for item in &request.items {
        let amount = item.quantity * item.price;
        total += amount;
        let is_sale_return = request.return_type == "销售退货";
        // 先读取当前库存（变更前）
        let before_stock: 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 is_sale_return {
            conn.execute("UPDATE products SET stock = stock + ?1 WHERE id = ?2",
                [&item.quantity.to_string(), &item.product_id]).map_err(|e| error_util::to_chinese_error(e))?;
        } else {
            if before_stock < item.quantity {
                return Err(format!("商品 '{}' 库存不足，当前库存: {:.2}, 退货数量: {:.2}",
                    item.product_name, before_stock, item.quantity));
            }
            conn.execute("UPDATE products SET stock = stock - ?1 WHERE id = ?2",
                [&item.quantity.to_string(), &item.product_id]).map_err(|e| error_util::to_chinese_error(e))?;
        }
        let after_stock: 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 (change_qty, change_type, remark) = if is_sale_return {
            (item.quantity, "sale_return", format!("销售退货: {}", return_no))
        } else {
            (-item.quantity, "purchase_return", format!("采购退货: {}", return_no))
        };
        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,?4,?5,?6,?7,?8,?9)",
            [&Uuid::new_v4().to_string(), &item.product_id, &item.product_name, change_type,
             &change_qty.to_string(), &before_stock.to_string(), &after_stock.to_string(),
             &remark, &now]
        ).map_err(|e| error_util::to_chinese_error(e))?;
    }

    conn.execute(
        "INSERT INTO return_orders (id, return_no, return_type, party_id, party_name, total_amount, reason, status, created_at) VALUES (?1,?2,?3,?4,?5,?6,?7,'completed',?8)",
        [&id, &return_no, &request.return_type, &request.party_id, &request.party_name, &total.to_string(), &request.reason, &now],
    ).map_err(|e| error_util::to_chinese_error(e))?;

    for item in &request.items {
        let amount = item.quantity * item.price;
        conn.execute(
            "INSERT INTO return_order_items (id, return_id, product_id, product_name, quantity, price, amount, batch_no) VALUES (?1,?2,?3,?4,?5,?6,?7,?8)",
            [&Uuid::new_v4().to_string(), &id, &item.product_id, &item.product_name, &item.quantity.to_string(), &item.price.to_string(), &amount.to_string(), &item.batch_no],
        ).map_err(|e| error_util::to_chinese_error(e))?;
    }

    // 自动生成应收/应付账单（销售退货减少应收，采购退货减少应付）
    let bill_type = if request.return_type == "销售退货" { "销售退货" } else { "采购退货" };
    let party_type = if request.return_type == "销售退货" { "customer" } else { "supplier" };
    conn.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,?2,?3,?4,?5,?6,?7,0.0,?8,?9,'','unpaid',?10,?11)",
        [&Uuid::new_v4().to_string(), party_type, &request.party_id, &request.party_name,
         &id, &return_no,
         &(-total).to_string(), bill_type, &now, &format!("退货单: {}", return_no), &now]
    ).map_err(|e| error_util::to_chinese_error(e))?;

    log_operation(&username, &real_name, "创建", "退货管理", &format!("创建退货单: {} 类型: {} 金额: {:.2}", return_no, request.return_type, total));

    Ok(ReturnOrder { id, return_no, return_type: request.return_type, party_id: request.party_id, party_name: request.party_name, total_amount: total, reason: request.reason, status: "completed".to_string(), created_at: now })
}

#[tauri::command]
pub fn get_return_orders(return_type: String) -> Result<Vec<ReturnOrder>, 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 sql = if return_type.is_empty() { "SELECT * FROM return_orders ORDER BY created_at DESC".to_string() } else { format!("SELECT * FROM return_orders WHERE return_type='{}' ORDER BY created_at DESC", return_type) };
    let mut stmt = conn.prepare(&sql).map_err(|e| error_util::to_chinese_error(e))?;
    let rows = stmt.query_map([], |row| {
        Ok(ReturnOrder { id: row.get(0)?, return_no: row.get(1)?, return_type: row.get(2)?, party_id: row.get::<_, Option<String>>(3)?.unwrap_or_default(), party_name: row.get::<_, Option<String>>(4)?.unwrap_or_default(), total_amount: row.get::<_, Option<f64>>(5)?.unwrap_or(0.0), reason: row.get::<_, Option<String>>(6)?.unwrap_or_default(), status: row.get(7)?, created_at: row.get(8)? })
    }).map_err(|e| error_util::to_chinese_error(e))?;
    rows.collect::<Result<Vec<_>, _>>().map_err(|e| error_util::to_chinese_error(e))
}
#[tauri::command]
pub fn get_return_order_items(return_id: String) -> Result<Vec<ReturnOrderItem>, 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 mut stmt = conn.prepare(
        "SELECT id, return_id, product_id, product_name, quantity, price, amount, batch_no FROM return_order_items WHERE return_id=?1"
    ).map_err(|e| error_util::to_chinese_error(e))?;
    let rows = stmt.query_map([&return_id], |row| {
        Ok(ReturnOrderItem {
            id: row.get(0)?,
            return_id: row.get(1)?,
            product_id: row.get(2)?,
            product_name: row.get(3)?,
            quantity: row.get(4)?,
            price: row.get(5)?,
            amount: row.get(6)?,
            batch_no: row.get::<_, Option<String>>(7)?.unwrap_or_default(),
        })
    }).map_err(|e| error_util::to_chinese_error(e))?;
    rows.collect::<Result<Vec<_>, _>>().map_err(|e| error_util::to_chinese_error(e))
}

#[tauri::command]
pub fn delete_return_order(return_id: String, username: String, real_name: String) -> Result<String, String> {
    if !check_permission(&username, "sales_edit") && !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 return_type: String = conn.query_row(
        "SELECT return_type FROM return_orders WHERE id=?1", [&return_id], |row| row.get(0)
    ).unwrap_or_default();
    let is_sale_return = return_type == "销售退货";

    // 获取退货单明细
    let mut stmt = conn.prepare(
        "SELECT product_id, product_name, quantity FROM return_order_items WHERE return_id=?1"
    ).map_err(|e| error_util::to_chinese_error(e))?;
    let items: Vec<(String, String, f64)> = stmt.query_map([&return_id], |row| {
        Ok((row.get(0)?, row.get(1)?, row.get(2)?))
    }).map_err(|e| error_util::to_chinese_error(e))?
    .filter_map(|r| r.ok()).collect();

    let now = Local::now().format("%Y-%m-%d %H:%M:%S").to_string();
    for (product_id, product_name, quantity) in &items {
        let before_stock: 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 is_sale_return {
            // 销售退货创建时增加了库存，删除时扣回
            conn.execute(
                "UPDATE products SET stock = stock - ?1 WHERE id = ?2",
                [&quantity.to_string(), product_id]
            ).map_err(|e| error_util::to_chinese_error(e))?;
        } else {
            // 采购退货创建时减少了库存，删除时恢复
            conn.execute(
                "UPDATE products SET stock = stock + ?1 WHERE id = ?2",
                [&quantity.to_string(), product_id]
            ).map_err(|e| error_util::to_chinese_error(e))?;
        }
        let after_stock: 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 (change_qty, change_type) = if is_sale_return {
            (-quantity, "return_delete")
        } else {
            (*quantity, "return_delete")
        };
        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,?4,?5,?6,?7,?8,?9)",
            [&Uuid::new_v4().to_string(), product_id, product_name, change_type,
             &change_qty.to_string(), &before_stock.to_string(), &after_stock.to_string(),
             &format!("删除退货单恢复库存: {}", return_id), &now]
        ).map_err(|e| error_util::to_chinese_error(e))?;
    }

    let return_no: String = conn.query_row("SELECT return_no FROM return_orders WHERE id=?1", [&return_id], |row| row.get(0)).unwrap_or_default();
    conn.execute("DELETE FROM return_order_items WHERE return_id=?1", [&return_id]).map_err(|e| error_util::to_chinese_error(e))?;
    conn.execute("DELETE FROM billing_records WHERE order_id=?1", [&return_id]).map_err(|e| error_util::to_chinese_error(e))?;
    conn.execute("DELETE FROM return_orders WHERE id=?1", [&return_id]).map_err(|e| error_util::to_chinese_error(e))?;
    log_operation(&username, &real_name, "删除", "退货管理", &format!("删除退货单: {} 类型:{} 库存已恢复", return_no, return_type));
    Ok("删除成功".to_string())
}