package com.haha.admin.controller;

import com.haha.admin.annotation.RequirePermission;
import com.haha.common.annotation.Log;
import com.haha.common.enums.OperationType;
import com.haha.common.vo.Result;
import com.haha.entity.DataPermission;
import com.haha.service.DataPermissionService;
import com.haha.service.RoleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * 数据权限管理控制器
 */
@Slf4j
@RestController
@RequestMapping("/permission")
public class DataPermissionController {

    @Autowired
    private DataPermissionService dataPermissionService;

    @Autowired
    private RoleService roleService;

    /**
     * 获取所有权限列表
     */
    @RequirePermission("role:read")
    @GetMapping("/list")
    public Result<List<DataPermission>> getAllPermissions() {
        return dataPermissionService.getAllPermissions();
    }

    /**
     * 获取所有权限(按模块分组)
     */
    @RequirePermission("role:read")
    @GetMapping("/list-grouped")
    public Result<List<Map<String, Object>>> getPermissionsGroupedByModule() {
        return dataPermissionService.getPermissionsTree();
    }

    /**
     * 根据模块编码获取权限列表
     */
    @RequirePermission("role:read")
    @GetMapping("/module/{moduleCode}")
    public Result<List<DataPermission>> getPermissionsByModule(@PathVariable String moduleCode) {
        return dataPermissionService.getPermissionsByModule(moduleCode);
    }

    /**
     * 根据角色ID获取权限ID列表
     */
    @RequirePermission("role:read")
    @GetMapping("/role/{roleId}")
    public Result<List<Long>> getRolePermissionIds(@PathVariable Long roleId) {
        return roleService.getRolePermissionIds(roleId);
    }

    /**
     * 更新角色权限
     */
    @RequirePermission("role:update")
    @Log(module = "权限管理", operation = OperationType.UPDATE, summary = "更新角色权限")
    @PostMapping("/role/{roleId}")
    public Result<Void> updateRolePermissions(
            @PathVariable Long roleId,
            @RequestBody List<Long> permissionIds) {
        return roleService.updateRolePermissions(roleId, permissionIds);
    }
}
