package org.dromara.system.controller.system;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.hutool.core.lang.tree.Tree;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.constraints.NotNull;
import lombok.RequiredArgsConstructor;
import org.dromara.common.core.domain.R;
import org.dromara.common.core.validate.AddGroup;
import org.dromara.common.idempotent.annotation.RepeatSubmit;
import org.dromara.common.log.annotation.Log;
import org.dromara.common.log.enums.BusinessType;
import org.dromara.common.satoken.utils.LoginHelper;
import org.dromara.common.web.core.BaseController;
import org.dromara.system.domain.bo.SysRolePermissionBo;
import org.dromara.system.domain.vo.SysMenuVo;
import org.dromara.system.service.ISysMenuService;
import org.dromara.system.service.ISysRolePermissionService;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 角色和菜单关联
 *
 * @author shihongwei
 * @date 2025-12-24
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/system/rolePermission")
@Tag(name = "角色和菜单关联", description = "角色和菜单关联管理")
public class SysRolePermissionController extends BaseController {

    private final ISysRolePermissionService sysRolePermissionService;
    private final ISysMenuService menuService;

    /**
     * 获取角色和菜单关联详细信息
     *
     * @param roleId 主键
     */
    @SaCheckPermission("system:role:query")
    @GetMapping("/{roleId}")
    @Operation(summary = "获取角色和菜单关联详细信息")
    public R<MenuTreeSelectVo> getInfo(@NotNull(message = "主键不能为空")
                                       @Parameter(name = "roleId", description = "主键", required = true, example = "1")
                                       @PathVariable Long roleId) {
        List<SysMenuVo> menus = menuService.selectMenuList(LoginHelper.getUserId());
        MenuTreeSelectVo selectVo = new MenuTreeSelectVo(
                sysRolePermissionService.selectMenuIdsByRoleId(roleId),
                menuService.buildMenuTreeSelect(menus));
        return R.ok(selectVo);
    }

    /**
     * 新增角色和菜单关联
     */
    @SaCheckPermission("system:role:add")
    @Log(title = "角色和菜单关联", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @RequestMapping(method = {RequestMethod.POST, RequestMethod.PUT})
    @Operation(summary = "新增角色和菜单关联")
    public R<Void> add(@Validated(AddGroup.class) @RequestBody SysRolePermissionBo bo) {
        return toAjax(sysRolePermissionService.insertByBo(bo));
    }

    /**
     * 角色菜单列表树信息
     *
     * @param checkedKeys 选中菜单列表
     * @param menus       菜单下拉树结构列表
     */
    public record MenuTreeSelectVo(List<Long> checkedKeys, List<Tree<Long>> menus) {
    }

}
