// 供应商管理模块
use serde::Deserialize;
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;

#[derive(Debug, Deserialize)]
pub struct AddSupplierRequest {
    pub name: String,
    pub contact: String,
    pub phone: String,
    pub address: String,
}

#[derive(Debug, Deserialize)]
pub struct UpdateSupplierRequest {
    pub id: String,
    pub name: String,
    pub contact: String,
    pub phone: String,
    pub address: String,
}

#[tauri::command]
pub fn add_supplier(request: AddSupplierRequest, username: String, real_name: String) -> Result<Supplier, String> {
    if !check_permission(&username, "suppliers_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 now = Local::now().format("%Y-%m-%d %H:%M:%S").to_string();
    
    conn.execute(
        "INSERT INTO suppliers (id, name, contact, phone, address, balance, created_at) 
         VALUES (?1, ?2, ?3, ?4, ?5, 0.0, ?6)",
        [&id, &request.name, &request.contact, &request.phone, &request.address, &now]
    ).map_err(|e| error_util::to_chinese_error(e))?;
    
    log_operation(&username, &real_name, "添加供应商", "供应商管理", &format!("供应商'{}'", request.name));
    
    Ok(Supplier {
        id,
        name: request.name,
        contact: request.contact,
        phone: request.phone,
        address: request.address,
        balance: 0.0,
        created_at: now,
    })
}

#[tauri::command]
pub fn get_suppliers(username: String) -> Result<Vec<Supplier>, String> {
    if !check_permission(&username, "suppliers_view") {
        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("系统错误：数据库未初始化")?;
    
    let mut stmt = conn.prepare("SELECT * FROM suppliers ORDER BY created_at DESC").map_err(|e| error_util::to_chinese_error(e))?;
    let suppliers = stmt.query_map([], |row| {
        Ok(Supplier {
            id: row.get(0)?,
            name: row.get(1)?,
            contact: row.get::<_, Option<String>>(2)?.unwrap_or_default(),
            phone: row.get::<_, Option<String>>(3)?.unwrap_or_default(),
            address: row.get::<_, Option<String>>(4)?.unwrap_or_default(),
            balance: row.get(5)?,
            created_at: row.get(6)?,
        })
    }).map_err(|e| error_util::to_chinese_error(e))?;
    
    suppliers.collect::<Result<Vec<_>, _>>().map_err(|e| error_util::to_chinese_error(e))
}

#[tauri::command]
pub fn update_supplier(request: UpdateSupplierRequest, username: String, real_name: String) -> Result<String, String> {
    if !check_permission(&username, "suppliers_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 suppliers SET name=?1, contact=?2, phone=?3, address=?4 WHERE id=?5",
        [&request.name, &request.contact, &request.phone, &request.address, &request.id]
    ).map_err(|e| error_util::to_chinese_error(e))?;
    
    log_operation(&username, &real_name, "编辑供应商", "供应商管理", &format!("供应商'{}'", request.name));
    
    Ok("更新成功".to_string())
}

#[tauri::command]
pub fn delete_supplier(supplier_id: String, username: String, real_name: String) -> Result<(), String> {
    if !check_permission(&username, "suppliers_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 name: String = conn.query_row("SELECT name FROM suppliers WHERE id=?1", [&supplier_id], |row| row.get(0)).unwrap_or_default();
    conn.execute("DELETE FROM suppliers WHERE id = ?1", [&supplier_id]).map_err(|e| error_util::to_chinese_error(e))?;

    log_operation(&username, &real_name, "删除供应商", "供应商管理", &format!("删除供应商'{}'", name));
    
    Ok(())
}
