package com.ym.mec.auth.web.controller;

import com.ym.mec.auth.api.dto.MenuQueryInfo;
import com.ym.mec.auth.api.entity.SysMenu;
import com.ym.mec.auth.service.SysMenuService;
import com.ym.mec.common.controller.BaseController;
import com.ym.mec.common.security.AuthUser;
import com.ym.mec.common.security.SecurityUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import java.util.Date;

@RestController()
@RequestMapping("menu")
@Api(tags = "菜单服务")
public class MenuController extends BaseController {

    @Autowired
    private SysMenuService sysMenuService;

    @ApiOperation("新增菜单")
    @PutMapping(value = "/add",consumes = MediaType.APPLICATION_JSON_VALUE)
    public Object getMenu(@RequestBody SysMenu sysMenu) {
        SysMenu menuByPermission = sysMenuService.findMenuByPermission(sysMenu.getPermission());
        if(menuByPermission != null){
            return failed("权限标识不能重复");
        }
        return succeed(sysMenuService.insert(sysMenu));
    }

    @ApiOperation("根据菜单id删除菜单")
    @DeleteMapping("/del/{id}")
    public Object delMenu(@ApiParam(value = "菜单编号", required = true) @PathVariable("id") Integer id) {
        sysMenuService.recursiveDel(id);
        return succeed();
    }

    @ApiOperation("根据菜单id修改菜单")
    @PutMapping(value = "/update",consumes = MediaType.APPLICATION_JSON_VALUE)
    public Object updateMenu(@RequestBody SysMenu sysMenu) {
        SysMenu menuByPermission = sysMenuService.findMenuByPermission(sysMenu.getPermission());
        if(menuByPermission != null && !menuByPermission.getId().equals(sysMenu.getId())){
            return failed("权限标识不能重复");
        }
        Date date = new Date();
        sysMenu.setUpdateTime(date);
        return succeed(sysMenuService.update(sysMenu));
    }

    @ApiOperation("根据菜单id查询菜单")
    @GetMapping(value = "/{id}",consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
    public Object getMenu(@ApiParam(value = "菜单编号", required = true) @PathVariable("id") Integer id) {
        return succeed(sysMenuService.get(id));
    }

    @ApiOperation("查询用户可访问菜单树状结构")
    @GetMapping(value = "/findByUser")
    public Object findByUser(@RequestBody(required = false) MenuQueryInfo menuQueryInfo) {
        AuthUser user = SecurityUtils.getUser();
        if(user != null){
            if(menuQueryInfo == null){
                menuQueryInfo = new MenuQueryInfo();
            }

            menuQueryInfo.setUserId(user.getUserId());
            return succeed(sysMenuService.findByUser(menuQueryInfo));
        }
        return failed();
    }



}
