package com.atguigu.ssyx.acl.controller;

import com.atguigu.ssyx.acl.service.PermissionService;
import com.atguigu.ssyx.common.result.Result;
import com.atguigu.ssyx.model.acl.Permission;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * ClassName: PermissionController
 * Package: com.atguigu.ssyx.acl.controller
 * 菜单服务
 *
 * @author yovinchen
 * @Create 2023/9/14 14:03
 */
@RestController
@RequestMapping("/admin/acl/permission")
@Api(tags = "菜单服务")

public class PermissionController {

    @Autowired
    private PermissionService permissionService;

    @ApiOperation(value = "获取菜单")
    @GetMapping
    public Result index() {
        try {
            List<Permission> list = permissionService.queryAllMenu();
            return StringUtils.isNotEmpty(list.toString()) ? Result.ok(list) : Result.fail(list);
        } catch (Exception e) {
            throw new RuntimeException("获取菜单异常", e);
        }
    }

    @ApiOperation(value = "新增菜单")
    @PostMapping("save")
    public Result save(@RequestBody Permission permission) {
        try {
            boolean result = permissionService.save(permission);
            return result ? Result.ok(null) : Result.fail(null);
        } catch (Exception e) {
            throw new RuntimeException("新增菜单异常", e);
        }
    }

    @ApiOperation(value = "修改菜单")
    @PutMapping("update")
    public Result updateById(@RequestBody Permission permission) {
        try {
            boolean result = permissionService.updateById(permission);
            return result ? Result.ok(null) : Result.fail(null);
        } catch (Exception e) {
            throw new RuntimeException("修改菜单异常", e);
        }
    }

    @ApiOperation(value = "递归删除菜单")
    @DeleteMapping("remove/{id}")
    public Result remove(@PathVariable Long id) {
        try {
            boolean result = permissionService.removeChildById(id);
            return result ? Result.ok(null) : Result.fail(null);
        } catch (Exception e) {
            throw new RuntimeException("递归删除菜单异常", e);
        }
    }
}
