// 仓库管理模块
use serde::Deserialize;
use crate::models::*;
use crate::database::DB_CONN;
use crate::permissions::check_permission;
use uuid::Uuid;
use chrono::Local;

#[derive(Debug, Deserialize)]
pub struct AddWarehouseRequest {
    pub name: String,
    pub code: String,
    pub address: Option<String>,
    pub contact: Option<String>,
    pub phone: Option<String>,
    pub description: Option<String>,
    pub is_default: bool,
}

#[tauri::command]
pub fn add_warehouse(request: AddWarehouseRequest, username: String) -> Result<Warehouse, String> {
    if !check_permission(&username, "warehouses_edit") {
        return Err("权限不足：没有新增仓库的权限".to_string());
    }
    let mut conn_guard = DB_CONN.lock().map_err(|e| e.to_string())?;
    let conn = conn_guard.as_mut().ok_or("Database not initialized")?;
    
    // 检查编码是否重复
    let exists: i64 = conn.query_row(
        "SELECT COUNT(*) FROM warehouses WHERE code = ?1",
        [&request.code],
        |row| row.get(0)
    ).map_err(|e| e.to_string())?;
    
    if exists > 0 {
        return Err(format!("仓库编码 '{}' 已存在", request.code));
    }
    
    let id = Uuid::new_v4().to_string();
    let now = Local::now().format("%Y-%m-%d %H:%M:%S").to_string();
    
    // 如果设置为默认仓库，取消其他仓库的默认状态
    if request.is_default {
        conn.execute(
            "UPDATE warehouses SET is_default = 0",
            []
        ).map_err(|e| e.to_string())?;
    }
    
    conn.execute(
        "INSERT INTO warehouses (id, name, code, address, contact, phone, description, is_default, created_at) 
         VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9)",
        [&id, &request.name, &request.code, &request.address.clone().unwrap_or_default(), &request.contact.clone().unwrap_or_default(), &request.phone.clone().unwrap_or_default(), &request.description.clone().unwrap_or_default(), &(request.is_default as i32).to_string(), &now]
    ).map_err(|e| e.to_string())?;
    
    Ok(Warehouse {
        id,
        name: request.name,
        code: request.code,
        address: request.address.unwrap_or_default(),
        contact: request.contact.unwrap_or_default(),
        phone: request.phone.unwrap_or_default(),
        description: request.description.unwrap_or_default(),
        is_default: request.is_default,
        created_at: now,
    })
}

#[tauri::command]
pub fn get_warehouses() -> Result<Vec<Warehouse>, 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 warehouses ORDER BY created_at DESC").map_err(|e| e.to_string())?;
    let warehouses = stmt.query_map([], |row| {
        Ok(Warehouse {
            id: row.get(0)?,
            name: row.get(1)?,
            code: row.get(2)?,
            address: row.get(3)?,
            contact: row.get(4)?,
            phone: row.get(5)?,
            description: row.get(6)?,
            is_default: row.get::<_, i32>(7)? != 0,
            created_at: row.get(8)?,
        })
    }).map_err(|e| e.to_string())?;
    
    warehouses.collect::<Result<Vec<_>, _>>().map_err(|e| e.to_string())
}

#[tauri::command]
pub fn update_warehouse(request: Warehouse, username: String) -> Result<String, String> {
    if !check_permission(&username, "warehouses_edit") {
        return Err("权限不足：没有编辑仓库的权限".to_string());
    }
    let mut conn_guard = DB_CONN.lock().map_err(|e| e.to_string())?;
    let conn = conn_guard.as_mut().ok_or("Database not initialized")?;
    
    // 如果设置为默认仓库，取消其他仓库的默认状态
    if request.is_default {
        conn.execute(
            "UPDATE warehouses SET is_default = 0 WHERE id != ?1",
            [&request.id]
        ).map_err(|e| e.to_string())?;
    }
    
    conn.execute(
        "UPDATE warehouses SET name = ?1, code = ?2, address = ?3, contact = ?4, phone = ?5, description = ?6, is_default = ?7 WHERE id = ?8",
        [&request.name, &request.code, &request.address, &request.contact, &request.phone, &request.description, &(request.is_default as i32).to_string(), &request.id]
    ).map_err(|e| e.to_string())?;
    
    Ok("更新成功".to_string())
}

#[tauri::command]
pub fn delete_warehouse(warehouse_id: String, username: String) -> Result<String, String> {
    if !check_permission(&username, "warehouses_edit") {
        return Err("权限不足：没有删除仓库的权限".to_string());
    }
    let mut conn_guard = DB_CONN.lock().map_err(|e| e.to_string())?;
    let conn = conn_guard.as_mut().ok_or("Database not initialized")?;
    
    // 检查是否有库位关联
    let location_count: i64 = conn.query_row(
        "SELECT COUNT(*) FROM locations WHERE warehouse_id = ?1",
        [&warehouse_id],
        |row| row.get(0)
    ).map_err(|e| e.to_string())?;
    
    if location_count > 0 {
        return Err("该仓库下存在库位，无法删除".to_string());
    }
    
    conn.execute("DELETE FROM warehouses WHERE id = ?1", [&warehouse_id])
        .map_err(|e| e.to_string())?;
    
    Ok("删除成功".to_string())
}
