package com.changfa.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.changfa.base.BaseController;
import com.changfa.config.shiro.CustomRealm;
import com.changfa.constants.ApiResult;
import com.changfa.enums.StatusEnum;
import com.changfa.dto.MenuDto;
import com.changfa.exception.BuzEx;
import com.changfa.service.ITMenuService;
import com.changfa.service.ITRoleMenuService;
import com.changfa.utils.CommonUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

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

/**
 * <p>
 * 角色菜单表 前端控制器
 * </p>
 *
 * @author wwz
 * @since 2022-06-24
 */
@RestController
@Api(tags = "角色菜单表")
@RequestMapping(value = "/rmenu",method = RequestMethod.POST)
public class RoleMenuController extends BaseController {

    @Autowired
    private CustomRealm customRealm;

    @Autowired
    private ITRoleMenuService roleMenuService;

    @Autowired
    private ITMenuService menuService;

    @ApiOperation(value = "角色分配权限")
    @RequestMapping("/assignPermissions")
    public ApiResult assignPermissions(@RequestParam("roleId")Integer roleId, @RequestParam("menuIds")List<Integer> menuIds){
        try{
            if(this.roleMenuService.assignPermissions(roleId,menuIds)){
                return ApiResult.success();
            }
        }catch (BuzEx buzEx){
            return ApiResult.error(buzEx.getStatusEnum());

        }catch (Exception e){
            e.printStackTrace();
            log.error(e.getMessage());
        }
        return ApiResult.error(StatusEnum.FAIL);
    }


    @ApiOperation(value = "获取菜单树")
    @RequestMapping("/getMenuTree")
    public ApiResult getMenuTree(){
        try{
            QueryWrapper wrapper = new QueryWrapper();
            wrapper.select("id as id , menu_name name,parent_key");
            List<Map<String,Object>> list = menuService.listMaps(wrapper);
            return ApiResult.success(customRealm.recursionForMenu(-1, CommonUtils.convertList(list, MenuDto.class)));
        }catch (BuzEx buzEx){
            return ApiResult.error(buzEx.getStatusEnum());

        }catch (Exception e){

        }
        return ApiResult.error(StatusEnum.FAIL);
    }



}
