// 系统配置模块 - 支持双单位开关、通用配置项
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 SystemConfig {
    pub id: String,
    pub config_key: String,
    pub config_value: String,
    pub description: String,
    pub updated_at: String,
}

/// 获取系统配置值
pub fn get_config(key: &str) -> String {
    let conn_guard = DB_CONN.lock().map_err(|e| e.to_string());
    if let Ok(guard) = conn_guard {
        if let Some(conn) = guard.as_ref() {
            if let Ok(val) = conn.query_row(
                "SELECT config_value FROM system_config WHERE config_key=?1",
                [key],
                |row| row.get::<_, String>(0)
            ) {
                return val;
            }
        }
    }
    String::new()
}

#[derive(Debug, Deserialize)]
pub struct SetConfigRequest {
    pub config_key: String,
    pub config_value: String,
    pub description: Option<String>,
}

#[tauri::command]
pub fn get_system_config(config_key: String) -> Result<String, String> {
    let conn_guard = DB_CONN.lock().map_err(|e| format!("系统错误：数据库访问失败 - {}", e))?;
    let conn = conn_guard.as_ref().ok_or("系统错误：数据库未初始化")?;
    
    let val: String = conn.query_row(
        "SELECT config_value FROM system_config WHERE config_key=?1",
        [&config_key],
        |row| row.get(0)
    ).unwrap_or_default();
    
    Ok(val)
}

#[tauri::command]
pub fn set_system_config(request: SetConfigRequest, username: String) -> Result<String, String> {
    // 打印相关配置允许所有用户设置，其他需要管理员权限
    if !request.config_key.starts_with("default_print_") && !check_permission(&username, "permissions_edit") {
        return Err("权限不足：没有设置系统配置的权限".to_string());
    }
    let mut conn_guard = DB_CONN.lock().map_err(|e| format!("系统错误：数据库访问失败 - {}", e))?;
    let conn = conn_guard.as_mut().ok_or("系统错误：数据库未初始化")?;
    let now = Local::now().format("%Y-%m-%d %H:%M:%S").to_string();
    let desc = request.description.unwrap_or_default();
    
    let exists: i64 = conn.query_row(
        "SELECT COUNT(*) FROM system_config WHERE config_key=?1",
        [&request.config_key],
        |row| row.get(0)
    ).unwrap_or(0);
    
    if exists > 0 {
        conn.execute(
            "UPDATE system_config SET config_value=?1, description=?2, updated_at=?3 WHERE config_key=?4",
            [&request.config_value, &desc, &now, &request.config_key]
        ).map_err(|e| format!("保存配置失败：{}", e))?;
    } else {
        conn.execute(
            "INSERT INTO system_config (id, config_key, config_value, description, updated_at) VALUES (?1,?2,?3,?4,?5)",
            [&Uuid::new_v4().to_string(), &request.config_key, &request.config_value, &desc, &now]
        ).map_err(|e| format!("保存配置失败：{}", e))?;
    }
    
    Ok("配置保存成功".to_string())
}

#[tauri::command]
pub fn get_all_system_configs() -> Result<Vec<SystemConfig>, String> {
    let conn_guard = DB_CONN.lock().map_err(|e| format!("系统错误：数据库访问失败 - {}", e))?;
    let conn = conn_guard.as_ref().ok_or("系统错误：数据库未初始化")?;
    
    let mut stmt = conn.prepare("SELECT id, config_key, config_value, description, updated_at FROM system_config ORDER BY config_key")
        .map_err(|e| format!("查询配置失败：{}", e))?;
    
    let configs = stmt.query_map([], |row| {
        Ok(SystemConfig {
            id: row.get(0)?,
            config_key: row.get(1)?,
            config_value: row.get(2)?,
            description: row.get::<_, Option<String>>(3)?.unwrap_or_default(),
            updated_at: row.get::<_, Option<String>>(4)?.unwrap_or_default(),
        })
    }).map_err(|e| format!("查询配置失败：{}", e))?;
    
    let mut result = Vec::new();
    for c in configs {
        result.push(c.map_err(|e| format!("读取配置失败：{}", e))?);
    }
    Ok(result)
}
