package com.aiotagro.cattletrade.business.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import com.aiotagro.cattletrade.business.entity.SysUserMenu;
import com.aiotagro.cattletrade.business.mapper.SysUserMenuMapper;
import com.aiotagro.common.core.web.domain.AjaxResult;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.*;

/**
 * 用户菜单权限管理控制器
 *
 * @author System
 * @date 2025-01-27
 */
@Slf4j
@RestController
@RequestMapping("/sysUserMenu")
public class SysUserMenuController {

    @Resource
    private SysUserMenuMapper sysUserMenuMapper;

    /**
     * 获取用户已分配的菜单ID列表
     */
    @SaCheckPermission("permission:operation:list")
    @GetMapping("/userMenuIds")
    public AjaxResult getUserMenuIds(@RequestParam Integer userId) {
        log.info("=== 获取用户菜单权限ID列表 ===");
        log.info("userId: {}", userId);
        
        if (userId == null) {
            log.error("用户ID不能为空");
            return AjaxResult.error("用户ID不能为空");
        }
        
        try {
            List<Integer> menuIds = sysUserMenuMapper.selectMenuIdsByUserId(userId);
            log.info("=== 用户 {} 已分配权限ID列表: {}", userId, menuIds);
            return AjaxResult.success(menuIds);
        } catch (Exception e) {
            log.error("获取用户菜单权限失败", e);
            return AjaxResult.error("获取用户菜单权限失败");
        }
    }

    /**
     * 为用户分配菜单权限
     */
    @SaCheckPermission("permission:operation:assign")
    @PostMapping("/assignUserMenus")
    public AjaxResult assignUserMenus(@RequestBody Map<String, Object> params) {
        Integer userId = (Integer) params.get("userId");
        @SuppressWarnings("unchecked")
        List<Integer> menuIds = (List<Integer>) params.get("menuIds");
        
        log.info("=== 分配用户菜单权限 ===");
        log.info("userId: {}", userId);
        log.info("menuIds: {}", menuIds);
        
        if (userId == null) {
            log.error("用户ID不能为空");
            return AjaxResult.error("用户ID不能为空");
        }
        
        try {
            // 删除原有权限
            int deletedCount = sysUserMenuMapper.delete(
                new LambdaQueryWrapper<SysUserMenu>()
                    .eq(SysUserMenu::getUserId, userId)
            );
            log.info("=== 删除用户 {} 原有权限记录数: {}", userId, deletedCount);
            
            // 添加新权限
            if (menuIds != null && !menuIds.isEmpty()) {
                for (Integer menuId : menuIds) {
                    SysUserMenu userMenu = new SysUserMenu();
                    userMenu.setUserId(userId);
                    userMenu.setMenuId(menuId);
                    userMenu.setCreateTime(new Date());
                    int insertResult = sysUserMenuMapper.insert(userMenu);
                    log.info("=== 插入用户权限记录 userId: {}, menuId: {}, 结果: {}", userId, menuId, insertResult);
                }
                log.info("=== 成功为用户 {} 分配 {} 个权限", userId, menuIds.size());
            } else {
                log.info("=== 没有要分配的权限，清空用户 {} 所有权限", userId);
            }
            
            return AjaxResult.success("分配成功");
        } catch (Exception e) {
            log.error("分配用户菜单权限失败", e);
            return AjaxResult.error("分配用户菜单权限失败");
        }
    }

    /**
     * 清空用户专属权限（恢复使用角色权限）
     */
    @SaCheckPermission("permission:operation:assign")
    @DeleteMapping("/clearUserMenus")
    public AjaxResult clearUserMenus(@RequestParam Integer userId) {
        log.info("=== 清空用户专属权限 ===");
        log.info("userId: {}", userId);
        
        if (userId == null) {
            log.error("用户ID不能为空");
            return AjaxResult.error("用户ID不能为空");
        }
        
        try {
            // 删除用户所有专属权限
            int deletedCount = sysUserMenuMapper.delete(
                new LambdaQueryWrapper<SysUserMenu>()
                    .eq(SysUserMenu::getUserId, userId)
            );
            log.info("=== 清空用户 {} 专属权限，删除记录数: {}", userId, deletedCount);
            
            return AjaxResult.success("清空成功，用户将使用角色权限");
        } catch (Exception e) {
            log.error("清空用户专属权限失败", e);
            return AjaxResult.error("清空用户专属权限失败");
        }
    }

    /**
     * 检查用户是否有专属权限
     */
    @SaCheckPermission("permission:operation:list")
    @GetMapping("/hasUserPermissions")
    public AjaxResult hasUserPermissions(@RequestParam Integer userId) {
        log.info("=== 检查用户是否有专属权限 ===");
        log.info("userId: {}", userId);
        
        if (userId == null) {
            log.error("用户ID不能为空");
            return AjaxResult.error("用户ID不能为空");
        }
        
        try {
            List<Integer> menuIds = sysUserMenuMapper.selectMenuIdsByUserId(userId);
            boolean hasUserPermissions = menuIds != null && !menuIds.isEmpty();
            
            Map<String, Object> result = new HashMap<>();
            result.put("hasUserPermissions", hasUserPermissions);
            result.put("permissionCount", menuIds != null ? menuIds.size() : 0);
            result.put("permissionSource", hasUserPermissions ? "用户专属权限" : "角色权限");
            
            log.info("=== 用户 {} 权限状态: {}", userId, result);
            return AjaxResult.success(result);
        } catch (Exception e) {
            log.error("检查用户权限状态失败", e);
            return AjaxResult.error("检查用户权限状态失败");
        }
    }
}
