// 操作日志模块 - 记录所有系统操作
use rusqlite::Connection;
use crate::database::DB_CONN;
use crate::permissions::check_permission;
use serde::{Deserialize, Serialize};
use uuid::Uuid;
use chrono::Local;

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct OperationLog {
    pub id: String,
    pub username: String,
    pub real_name: String,
    pub action: String,
    pub module: String,
    pub detail: String,
    pub created_at: String,
}

#[derive(Debug, Deserialize)]
pub struct AddLogRequest {
    pub username: String,
    pub real_name: String,
    pub action: String,
    pub module: String,
    pub detail: String,
}

/// 记录操作日志（内部调用 - 使用独立连接避免死锁）
pub fn log_operation(username: &str, real_name: &str, action: &str, module: &str, detail: &str) {
    // 使用独立的数据库连接，避免与调用方持有的 DB_CONN 锁发生死锁
    if let Ok(conn) = Connection::open("inventory.db") {
        let id = Uuid::new_v4().to_string();
        let now = Local::now().format("%Y-%m-%d %H:%M:%S").to_string();
        let _ = conn.execute(
            "INSERT INTO operation_logs (id, username, real_name, action, module, detail, created_at) VALUES (?1,?2,?3,?4,?5,?6,?7)",
            [&id, username, real_name, action, module, detail, &now]
        );
    }
}

#[tauri::command]
pub fn add_operation_log(request: AddLogRequest) -> Result<String, String> {
    let conn_guard = DB_CONN.lock().map_err(|e| format!("系统错误：数据库访问失败 - {}", e))?;
    let conn = conn_guard.as_ref().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 operation_logs (id, username, real_name, action, module, detail, created_at) VALUES (?1,?2,?3,?4,?5,?6,?7)",
        [&id, &request.username, &request.real_name, &request.action, &request.module, &request.detail, &now]
    ).map_err(|e| format!("记录日志失败：{}", e))?;
    
    Ok("日志记录成功".to_string())
}

#[tauri::command]
pub fn get_operation_logs(limit: Option<i64>, module: Option<String>, username: String) -> Result<Vec<OperationLog>, String> {
    if !check_permission(&username, "logs_view") {
        return Err("权限不足：没有查看操作日志的权限".to_string());
    }
    let conn_guard = DB_CONN.lock().map_err(|e| format!("系统错误：数据库访问失败 - {}", e))?;
    let conn = conn_guard.as_ref().ok_or("系统错误：数据库未初始化")?;
    
    let limit_val = limit.unwrap_or(100);
    let sql = if let Some(ref mod_name) = module {
        format!("SELECT id, username, real_name, action, module, detail, created_at FROM operation_logs WHERE module='{}' ORDER BY created_at DESC LIMIT {}", mod_name, limit_val)
    } else {
        format!("SELECT id, username, real_name, action, module, detail, created_at FROM operation_logs ORDER BY created_at DESC LIMIT {}", limit_val)
    };
    
    let mut stmt = conn.prepare(&sql).map_err(|e| format!("查询日志失败：{}", e))?;
    let logs = stmt.query_map([], |row| {
        Ok(OperationLog {
            id: row.get(0)?,
            username: row.get(1)?,
            real_name: row.get(2)?,
            action: row.get(3)?,
            module: row.get(4)?,
            detail: row.get::<_, Option<String>>(5)?.unwrap_or_default(),
            created_at: row.get::<_, Option<String>>(6)?.unwrap_or_default(),
        })
    }).map_err(|e| format!("查询日志失败：{}", e))?;
    
    let mut result = Vec::new();
    for l in logs {
        result.push(l.map_err(|e| format!("读取日志失败：{}", e))?);
    }
    Ok(result)
}

#[tauri::command]
pub fn clear_operation_logs(username: String) -> Result<String, String> {
    if !check_permission(&username, "logs_view") {
        return Err("权限不足：没有清除操作日志的权限".to_string());
    }
    let conn_guard = DB_CONN.lock().map_err(|e| format!("系统错误：数据库访问失败 - {}", e))?;
    let conn = conn_guard.as_ref().ok_or("系统错误：数据库未初始化")?;
    
    conn.execute("DELETE FROM operation_logs", [])
        .map_err(|e| format!("清除日志失败：{}", e))?;
    
    Ok("日志已清除".to_string())
}
