// ============ 用户认证模块 ============
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::{Serialize, Deserialize};
use serde_json::json;
use uuid::Uuid;
use chrono::Local;

#[derive(Debug, Serialize, Deserialize)]
pub struct AccountInfo {
    pub username: String,
    pub real_name: String,
    pub role: String,
}

#[tauri::command]
pub fn get_accounts() -> Result<Vec<AccountInfo>, 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 username, real_name, role FROM users ORDER BY username"
    ).map_err(|e| error_util::to_chinese_error(e))?;
    
    let accounts = stmt.query_map([], |row| {
        Ok(AccountInfo {
            username: row.get(0)?,
            real_name: row.get(1)?,
            role: row.get(2)?,
        })
    }).map_err(|e| error_util::to_chinese_error(e))?;
    
    accounts.collect::<Result<Vec<_>, _>>().map_err(|e| error_util::to_chinese_error(e))
}


/// Load granted permission keys for a role
fn load_role_permissions(conn: &rusqlite::Connection, role_name: &str) -> Vec<String> {
    let mut stmt = match conn.prepare(
        "SELECT permission_key FROM role_permissions WHERE role_name=?1 AND is_granted=1"
    ) {
        Ok(s) => s,
        Err(_) => return vec![],
    };
    let rows = stmt.query_map([role_name], |row| row.get::<_, String>(0));
    match rows {
        Ok(iter) => iter.filter_map(|r| r.ok()).collect(),
        Err(_) => vec![],
    }
}

#[tauri::command]
pub fn login(request: LoginRequest) -> Result<LoginResponse, 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 id, username, password, real_name, role, created_at FROM users WHERE username = ?1"
    ).map_err(|e| error_util::to_chinese_error(e))?;
    
    let mut rows = stmt.query([&request.username]).map_err(|e| error_util::to_chinese_error(e))?;
    
    if let Some(row) = rows.next().map_err(|e| error_util::to_chinese_error(e))? {
        let db_password: String = row.get(2).map_err(|e| error_util::to_chinese_error(e))?;
        
        if db_password == request.password {
            let role_str: String = row.get(4).map_err(|e| error_util::to_chinese_error(e))?;
            let role = if role_str == "admin" {
                UserRole::Admin
            } else {
                UserRole::Employee
            };
            
            // Load user permissions from role_permissions table
            let role_name = if role_str == "admin" { "admin".to_string() } else { role_str.clone() };
            let perms = load_role_permissions(conn, &role_name);

            Ok(LoginResponse {
                success: true,
                message: "登录成功".to_string(),
                user: Some(User {
                    id: row.get(0).map_err(|e| error_util::to_chinese_error(e))?,
                    username: row.get(1).map_err(|e| error_util::to_chinese_error(e))?,
                    password: "".to_string(),
                    real_name: row.get(3).map_err(|e| error_util::to_chinese_error(e))?,
                    role,
                    permissions: perms,
                    created_at: row.get(5).map_err(|e| error_util::to_chinese_error(e))?,
                }),
            })
        } else {
            Ok(LoginResponse {
                success: false,
                message: "密码错误".to_string(),
                user: None,
            })
        }
    } else {
        Ok(LoginResponse {
            success: false,
            message: "用户名不存在".to_string(),
            user: None,
        })
    }
}

#[tauri::command]
pub fn get_users(username: String) -> Result<Vec<serde_json::Value>, String> {
    if !check_permission(&username, "users_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 id, username, password, real_name, role, created_at FROM users ORDER BY created_at DESC"
    ).map_err(|e| error_util::to_chinese_error(e))?;
    
    let user_iter = stmt.query_map([], |row| {
        Ok(json!({
            "id": row.get::<_, String>(0)?,
            "username": row.get::<_, String>(1)?,
            "password": "",
            "real_name": row.get::<_, String>(3)?,
            "role": row.get::<_, String>(4)?,
            "created_at": row.get::<_, String>(5)?,
        }))
    }).map_err(|e| error_util::to_chinese_error(e))?;
    
    let mut users = Vec::new();
    for user in user_iter {
        users.push(user.map_err(|e| error_util::to_chinese_error(e))?);
    }
    
    Ok(users)
}

#[tauri::command]
pub fn add_user(request: AddUserRequest, username: String, real_name: String) -> Result<User, String> {
    if !check_permission(&username, "users_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 mut stmt = conn.prepare(
        "SELECT COUNT(*) FROM users WHERE username = ?1"
    ).map_err(|e| error_util::to_chinese_error(e))?;
    
    let count: i64 = stmt.query_row([&request.username], |row| row.get(0))
        .map_err(|e| error_util::to_chinese_error(e))?;
    
    if count > 0 {
        return Err("用户名已存在".to_string());
    }
    
    let id = Uuid::new_v4().to_string();
    let now = Local::now().format("%Y-%m-%d %H:%M:%S").to_string();
    // 直接使用传入的角色名称，支持自定义角色
    let role_str = if request.role == "admin" { "admin" } else { &request.role };
    
    conn.execute(
        "INSERT INTO users (id, username, password, real_name, role, created_at) VALUES (?1, ?2, ?3, ?4, ?5, ?6)",
        [&id, &request.username, &request.password, &request.real_name, role_str, &now]
    ).map_err(|e| error_util::to_chinese_error(e))?;
    
    let role = if role_str == "admin" {
        UserRole::Admin
    } else {
        UserRole::Employee
    };
    
    log_operation(&username, &real_name, "添加", "用户管理", &format!("添加用户: {} ({})", request.username, request.real_name));
    
    Ok(User {
        id,
        username: request.username,
        password: "".to_string(),
        real_name: request.real_name,
        role,
        permissions: vec![],
        created_at: now,
    })
}

#[tauri::command]
pub fn delete_user(user_id: String, username: String, real_name: String) -> Result<(), String> {
    if !check_permission(&username, "users_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 mut stmt = conn.prepare(
        "SELECT username FROM users WHERE id = ?1"
    ).map_err(|e| error_util::to_chinese_error(e))?;
    
    let deleted_username = stmt.query_row([&user_id], |row| row.get::<_, String>(0)).map_err(|e| error_util::to_chinese_error(e))?;
    if deleted_username == "admin" {
        return Err("不能删除默认管理员账户".to_string());
    }
    
    conn.execute(
        "DELETE FROM users WHERE id = ?1",
        [&user_id]
    ).map_err(|e| error_util::to_chinese_error(e))?;
    
    log_operation(&username, &real_name, "删除", "用户管理", &format!("删除用户: {}", deleted_username));
    
    Ok(())
}

#[tauri::command]
pub fn change_password(user_id: String, old_password: String, new_password: String, username: String, real_name: String) -> Result<(), 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 mut stmt = conn.prepare(
        "SELECT password FROM users WHERE id = ?1"
    ).map_err(|e| error_util::to_chinese_error(e))?;
    
    let db_password: String = stmt.query_row([&user_id], |row| row.get(0))
        .map_err(|e| error_util::to_chinese_error(e))?;
    
    if db_password != old_password {
        return Err("原密码错误".to_string());
    }
    
    conn.execute(
        "UPDATE users SET password = ?1 WHERE id = ?2",
        [&new_password, &user_id]
    ).map_err(|e| error_util::to_chinese_error(e))?;
    
    log_operation(&username, &real_name, "修改", "用户管理", "修改密码");
    
    Ok(())
}

/// 管理员重置指定用户密码（无需原密码）
#[tauri::command]
pub fn admin_reset_password(target_user_id: String, new_password: String, username: String, real_name: String) -> Result<(), String> {
    if !check_permission(&username, "users_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 users SET password = ?1 WHERE id = ?2",
        [&new_password, &target_user_id]
    ).map_err(|e| error_util::to_chinese_error(e))?;
    
    // 获取目标用户名用于日志
    let target_name: String = conn.query_row(
        "SELECT username FROM users WHERE id=?1",
        [&target_user_id], |row| row.get(0)
    ).unwrap_or_default();
    
    log_operation(&username, &real_name, "重置密码", "用户管理", &format!("重置用户 '{}' 的密码", target_name));
    
    Ok(())
}
