// ============ 客户管理模块 ============
use crate::models::*;
use crate::database::DB_CONN;
use crate::operation_logs::log_operation;
use crate::error_util;
use crate::permissions::check_permission;
use serde::{Deserialize};
use uuid::Uuid;
use chrono::Local;

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

#[tauri::command]
pub fn add_customer(request: AddCustomerRequest, username: String, real_name: String) -> Result<Customer, String> {
    if !check_permission(&username, "customers_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 customers (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(Customer {
        id,
        name: request.name,
        contact: request.contact,
        phone: request.phone,
        address: request.address,
        balance: 0.0,
        created_at: now,
    })
}

#[tauri::command]
pub fn get_customers(username: String) -> Result<Vec<Customer>, String> {
    if !check_permission(&username, "customers_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 c.id, c.name, c.contact, c.phone, c.address, COALESCE((SELECT SUM(b.amount - b.paid_amount) FROM billing_records b WHERE b.party_id=c.id AND b.party_type='customer' AND b.status!='paid'), 0.0) as balance, c.created_at FROM customers c ORDER BY c.created_at DESC").map_err(|e| error_util::to_chinese_error(e))?;
    let customers = stmt.query_map([], |row| {
        Ok(Customer {
            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))?;
    
    customers.collect::<Result<Vec<_>, _>>().map_err(|e| error_util::to_chinese_error(e))
}

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

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

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

#[tauri::command]
pub fn update_customer(request: UpdateCustomerRequest, username: String, real_name: String) -> Result<String, String> {
    if !check_permission(&username, "customers_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 customers 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())
}
