package com.haha.admin.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.haha.admin.annotation.RequirePermission;
import com.haha.service.RoleService;
import com.haha.common.annotation.Log;
import com.haha.common.enums.OperationType;
import com.haha.common.vo.Result;
import com.haha.entity.Role;
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("/role")
public class RoleController {
    
    @Autowired
    private RoleService roleService;
    
    /**
     * 分页查询角色列表
     */
    @RequirePermission("role:read")
    @PostMapping
    public Result<Map<String, Object>> list(@RequestBody Map<String, Object> params) {
        int page = Integer.parseInt(params.getOrDefault("page", 1).toString());
        int pageSize = Integer.parseInt(params.getOrDefault("pageSize", 10).toString());
        String name = (String) params.get("name");
        String code = (String) params.get("code");
        
        Result<IPage<Role>> result = roleService.getRoleList(page, pageSize, name, code);
        
        // 转换为前端需要的格式
        if (result.getCode() == 200 && result.getData() != null) {
            IPage<Role> pageData = result.getData();
            Map<String, Object> data = Map.of(
                "list", pageData.getRecords(),
                "total", pageData.getTotal(),
                "pageSize", pageData.getSize(),
                "currentPage", pageData.getCurrent()
            );
            return Result.success("查询成功", data);
        }
        return Result.error(result.getCode(), "查询失败");
    }
    
    /**
     * 获取所有角色(不分页)
     */
    @RequirePermission("role:read")
    @GetMapping("/list-all-role")
    public Result<List<Role>> listAll() {
        return roleService.getAllRoles();
    }
    
    /**
     * 添加角色
     */
    @RequirePermission("role:create")
    @Log(module = "角色管理", operation = OperationType.INSERT, summary = "添加角色")
    @PostMapping("/add")
    public Result<Void> add(@RequestBody Role role) {
        return roleService.addRole(role);
    }
    
    /**
     * 更新角色
     */
    @RequirePermission("role:update")
    @Log(module = "角色管理", operation = OperationType.UPDATE, summary = "更新角色")
    @PostMapping("/update")
    public Result<Void> update(@RequestBody Role role) {
        return roleService.updateRole(role);
    }
    
    /**
     * 删除角色
     */
    @RequirePermission("role:delete")
    @Log(module = "角色管理", operation = OperationType.DELETE, summary = "删除角色")
    @DeleteMapping("/{id}")
    public Result<Void> delete(@PathVariable Long id) {
        return roleService.deleteRole(id);
    }
}
