// 角色权限管理模块
use crate::database::DB_CONN;
use serde::{Deserialize, Serialize};
use uuid::Uuid;
use chrono::Local;

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RolePermission {
    pub id: String,
    pub role_name: String,
    pub permission_key: String,
    pub permission_name: String,
    pub is_granted: bool,
    pub updated_at: String,
}

#[derive(Debug, Deserialize)]
pub struct SetPermissionRequest {
    pub role_name: String,
    pub permission_key: String,
    pub is_granted: bool,
}

/// 获取角色权限列表（如果是新角色，自动创建默认权限）
#[tauri::command]
pub fn get_role_permissions(role_name: String) -> Result<Vec<RolePermission>, String> {
    // 先检查是否需要初始化该角色的默认权限
    {
        let conn_guard = DB_CONN.lock().map_err(|e| format!("系统错误：数据库访问失败 - {}", e))?;
        let conn = conn_guard.as_ref().ok_or("系统错误：数据库未初始化")?;
        let count: i64 = conn.query_row(
            "SELECT COUNT(*) FROM role_permissions WHERE role_name=?1",
            [&role_name], |row| row.get(0)
        ).unwrap_or(0);
        if count > 0 {
            // 已有权限，直接查询返回
            let mut stmt = conn.prepare(
                "SELECT id, role_name, permission_key, permission_name, is_granted, updated_at FROM role_permissions WHERE role_name=?1 ORDER BY permission_key"
            ).map_err(|e| format!("查询权限失败：{}", e))?;
            let perms = stmt.query_map([&role_name], |row| {
                Ok(RolePermission {
                    id: row.get(0)?,
                    role_name: row.get(1)?,
                    permission_key: row.get(2)?,
                    permission_name: row.get(3)?,
                    is_granted: row.get::<_, i32>(4)? != 0,
                    updated_at: row.get::<_, Option<String>>(5)?.unwrap_or_default(),
                })
            }).map_err(|e| format!("查询权限失败：{}", e))?;
            let mut result = Vec::new();
            for p in perms {
                result.push(p.map_err(|e| format!("读取权限失败：{}", e))?);
            }
            // Check for missing permissions (from upgrades) and add them
            let all_perms = vec![
                ("商品管理", "products_view"), ("商品管理", "products_edit"), ("商品管理", "products_delete"),
                ("客户管理", "customers_view"), ("客户管理", "customers_edit"),
                ("供应商管理", "suppliers_view"), ("供应商管理", "suppliers_edit"),
                ("销售管理", "sales_view"), ("销售管理", "sales_create"), ("销售管理", "sales_edit"),
                ("采购管理", "purchases_view"), ("采购管理", "purchases_create"), ("采购管理", "purchases_edit"),
                ("库存管理", "inventory_view"), ("库存管理", "inventory_ops"), ("库存管理", "inventory_batch"), ("库存管理", "inventory_view_cost"),
                ("仓库管理", "warehouses_view"), ("仓库管理", "warehouses_edit"),
                ("应收应付", "billing_view"), ("应收应付", "billing_edit"),
                ("打印管理", "print_view"), ("打印管理", "print_edit"),
                ("系统管理", "users_view"), ("系统管理", "users_edit"), ("系统管理", "logs_view"), ("系统管理", "permissions_edit"),
                ("系统管理", "data_import"), ("系统管理", "data_export"),
            ];
            let now2 = Local::now().format("%Y-%m-%d %H:%M:%S").to_string();
            for (module, key) in &all_perms {
                let exists: i64 = conn.query_row(
                    "SELECT COUNT(*) FROM role_permissions WHERE role_name=?1 AND permission_key=?2",
                    rusqlite::params![&role_name, *key], |row| row.get(0)
                ).unwrap_or(0);
                if exists == 0 {
                    let granted = match *key {
                        "products_delete" | "sales_edit" | "purchases_edit"
                        | "users_view" | "users_edit" | "logs_view" | "permissions_edit" | "inventory_view_cost" => "0",
                        _ => "1",
                    };
                    let _ = conn.execute(
                        "INSERT INTO role_permissions (id, role_name, permission_key, permission_name, is_granted, updated_at) VALUES (?1,?2,?3,?4,?5,?6)",
                        rusqlite::params![Uuid::new_v4().to_string(), &role_name, key, module, granted, &now2],
                    );
                }
            }
            return Ok(result);
        }
    } // conn_guard 在这里释放

    // 新角色，插入默认权限
    let mut guard = DB_CONN.lock().map_err(|e| format!("系统错误：数据库访问失败 - {}", e))?;
    let conn = guard.as_mut().ok_or("系统错误：数据库未初始化")?;
    let now = Local::now().format("%Y-%m-%d %H:%M:%S").to_string();
    let all_permissions = vec![
        ("商品管理", "products_view"), ("商品管理", "products_edit"), ("商品管理", "products_delete"),
        ("客户管理", "customers_view"), ("客户管理", "customers_edit"),
        ("供应商管理", "suppliers_view"), ("供应商管理", "suppliers_edit"),
        ("销售管理", "sales_view"), ("销售管理", "sales_create"), ("销售管理", "sales_edit"),
        ("采购管理", "purchases_view"), ("采购管理", "purchases_create"), ("采购管理", "purchases_edit"),
        ("库存管理", "inventory_view"), ("库存管理", "inventory_ops"), ("库存管理", "inventory_batch"), ("库存管理", "inventory_view_cost"),
        ("仓库管理", "warehouses_view"), ("仓库管理", "warehouses_edit"),
        ("应收应付", "billing_view"), ("应收应付", "billing_edit"),
        ("打印管理", "print_view"), ("打印管理", "print_edit"),
        ("系统管理", "users_view"), ("系统管理", "users_edit"), ("系统管理", "logs_view"), ("系统管理", "permissions_edit"),
    ];
    for (module, key) in &all_permissions {
        let granted = match *key {
            "products_delete" | "sales_edit" | "purchases_edit"
            | "users_view" | "users_edit" | "logs_view" | "permissions_edit" | "inventory_view_cost" => "0",
            _ => "1",
        };
        let _ = conn.execute(
            "INSERT INTO role_permissions (id, role_name, permission_key, permission_name, is_granted, updated_at) VALUES (?1,?2,?3,?4,?5,?6)",
            rusqlite::params![Uuid::new_v4().to_string(), &role_name, key, module, granted, &now],
        );
    }
    drop(guard);

    // 返回刚插入的默认权限
    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, role_name, permission_key, permission_name, is_granted, updated_at FROM role_permissions WHERE role_name=?1 ORDER BY permission_key"
    ).map_err(|e| format!("查询权限失败：{}", e))?;
    let perms = stmt.query_map([&role_name], |row| {
        Ok(RolePermission {
            id: row.get(0)?,
            role_name: row.get(1)?,
            permission_key: row.get(2)?,
            permission_name: row.get(3)?,
            is_granted: row.get::<_, i32>(4)? != 0,
            updated_at: row.get::<_, Option<String>>(5)?.unwrap_or_default(),
        })
    }).map_err(|e| format!("查询权限失败：{}", e))?;
    let mut result = Vec::new();
    for p in perms {
        result.push(p.map_err(|e| format!("读取权限失败：{}", e))?);
    }
    Ok(result)
}

/// 设置角色权限
#[tauri::command]
pub fn set_role_permission(request: SetPermissionRequest, username: String) -> Result<String, String> {
    if !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 exists: i64 = conn.query_row(
        "SELECT COUNT(*) FROM role_permissions WHERE role_name=?1 AND permission_key=?2",
        [&request.role_name, &request.permission_key],
        |row| row.get(0)
    ).unwrap_or(0);
    
    let granted_str = if request.is_granted { "1".to_string() } else { "0".to_string() };
    if exists > 0 {
        conn.execute(
            "UPDATE role_permissions SET is_granted=?1, updated_at=?2 WHERE role_name=?3 AND permission_key=?4",
            [&granted_str, &now, &request.role_name, &request.permission_key]
        ).map_err(|e| format!("设置权限失败：{}", e))?;
    } else {
        conn.execute(
            "INSERT INTO role_permissions (id, role_name, permission_key, permission_name, is_granted, updated_at) VALUES (?1,?2,?3,?4,?5,?6)",
            [&Uuid::new_v4().to_string(), &request.role_name, &request.permission_key, &String::new(), &granted_str, &now]
        ).map_err(|e| format!("设置权限失败：{}", e))?;
    }
    
    Ok("权限设置成功".to_string())
}

/// 初始化默认权限（由 init_db 调用，不自己加锁）
pub fn init_default_permissions(conn: &rusqlite::Connection) -> Result<(), String> {
    let count: i64 = conn.query_row(
        "SELECT COUNT(*) FROM role_permissions", [], |row| row.get(0)
    ).unwrap_or(0);
    
    if count == 0 {
        let now = Local::now().format("%Y-%m-%d %H:%M:%S").to_string();
        let all_permissions = vec![
            ("商品管理", "products_view", "查看商品"),
            ("商品管理", "products_edit", "新增/编辑商品"),
            ("商品管理", "products_delete", "删除商品"),
            ("客户管理", "customers_view", "查看客户"),
            ("客户管理", "customers_edit", "新增/编辑客户"),
            ("供应商管理", "suppliers_view", "查看供应商"),
            ("供应商管理", "suppliers_edit", "新增/编辑供应商"),
            ("销售管理", "sales_view", "查看销售订单"),
            ("销售管理", "sales_create", "创建销售订单"),
            ("销售管理", "sales_edit", "编辑/取消/删除销售订单"),
            ("采购管理", "purchases_view", "查看采购订单"),
            ("采购管理", "purchases_create", "创建采购订单"),
            ("采购管理", "purchases_edit", "编辑/取消/删除采购订单"),
            ("库存管理", "inventory_view", "查看库存"),
            ("库存管理", "inventory_ops", "入库/出库/盘点"),
            ("库存管理", "inventory_batch", "批量出入库"),
            ("库存管理", "inventory_view_cost", "查看成本价"),
            ("仓库管理", "warehouses_view", "查看仓库"),
            ("仓库管理", "warehouses_edit", "新增/编辑仓库库位"),
            ("应收应付", "billing_view", "查看应收应付"),
            ("应收应付", "billing_edit", "新增/编辑应收应付"),
            ("打印管理", "print_view", "查看打印模板"),
            ("打印管理", "print_edit", "新增/编辑打印模板"),
            ("系统管理", "users_view", "查看用户"),
            ("系统管理", "users_edit", "新增/编辑用户"),
            ("系统管理", "logs_view", "查看操作日志"),
            ("系统管理", "permissions_edit", "管理权限"),
            ("系统管理", "data_import", "Excel导入"),
            ("系统管理", "data_export", "Excel导出"),
        ];
        
        for (module_name, key, _name) in &all_permissions {
            let key_str = key.to_string();
            let module_str = module_name.to_string();
            // admin has all permissions
            let _ = conn.execute(
                "INSERT INTO role_permissions (id, role_name, permission_key, permission_name, is_granted, updated_at) VALUES (?1,'admin',?2,?3,1,?4)",
                [&Uuid::new_v4().to_string(), &key_str, &module_str, &now]
            );
            // employee has limited permissions
            let employee_granted: i32 = match *key {
                "products_delete" => 0,
                "sales_edit" => 0,
                "purchases_edit" => 0,
                "users_view" | "users_edit" | "logs_view" | "permissions_edit" | "data_import" | "data_export" => 0,
                _ => 1,
            };
            let _ = conn.execute(
                "INSERT INTO role_permissions (id, role_name, permission_key, permission_name, is_granted, updated_at) VALUES (?1,'employee',?2,?3,?4,?5)",
                [&Uuid::new_v4().to_string(), &key_str, &module_str, &employee_granted.to_string(), &now]
            );
        }
    }
    Ok(())
}

/// 检查用户是否拥有权限（内部调用）
pub fn check_permission(username: &str, permission_key: &str) -> bool {
    let conn_guard = DB_CONN.lock();
    if let Ok(guard) = conn_guard {
        if let Some(conn) = guard.as_ref() {
            // Get user's role
            if let Ok(role_str) = conn.query_row::<String, _, _>(
                "SELECT role FROM users WHERE username=?1",
                [username],
                |row| row.get(0)
            ) {
                if let Ok(granted) = conn.query_row::<i64, _, _>(
                    "SELECT is_granted FROM role_permissions WHERE role_name=?1 AND permission_key=?2",
                    [&role_str, permission_key],
                    |row| row.get(0)
                ) {
                    return granted != 0;
                }
            }
        }
    }
    false
}
