/*
 * Author: wangjian
 * 生成controller
 */
package com.tofly.base.controller;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tofly.base.entity.BaseSys;
import com.tofly.base.entity.Menu;
import com.tofly.base.entity.RoleMenu;
import com.tofly.base.service.BaseSysService;
import com.tofly.base.service.MenuService;
import com.tofly.base.service.RoleMenuService;
import com.tofly.base.vo.SystemMenuVO;
import com.tofly.common.core.entity.ResultRespone;
import com.tofly.common.core.util.StringUtil;
import com.tofly.common.log.annotation.ToFlyAppLog;
import io.swagger.annotations.*;
import lombok.AllArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.baomidou.mybatisplus.core.toolkit.Wrappers.update;

/**
 * 菜单表
 *
 * @author admin
 * @date Thu Oct 10 00:00:00 CST 2019
 */
@RestController
@AllArgsConstructor
@RequestMapping("/menu")
@Api(tags="菜单管理")
public class MenuController {

    private final  MenuService menuService;

    private final RoleMenuService roleMenuService;

    private final BaseSysService systemService;
    /**
    * 分页查询
    * @param page 分页对象
    * @param menu 菜单表
    * @return
    */
    @GetMapping("/page" )
    @ApiOperation(value = "分页查询")
    public ResultRespone getMenuPage(Page page, @ModelAttribute Menu menu) {
      return ResultRespone.success(menuService.page(page, Wrappers.query(menu)));
    }

    /**
     * 菜单列表
     * @param menu 菜单表
     * @return
     */
    @GetMapping("/list" )
    @ApiOperation(tags = {"用户管理","菜单管理","角色管理"},value = "菜单列表")
    public ResultRespone getMenuPage(@ModelAttribute Menu menu) {
        return ResultRespone.success(menuService.list(Wrappers.query(menu)));
    }


    /**
     * 通过id查询菜单表
     * @param id id
     * @return ResultRespone
     */
    @GetMapping("/{id}" )
    @ApiOperation(value = "通过ID查询")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "ID", required = true, dataType = "Long")
    })
    public ResultRespone getById(@PathVariable("id" ) Long id) {
      return ResultRespone.success(menuService.getById(id));
    }

    /**
     * 新增菜单表
     * @param menu 菜单表
     * @return ResultRespone
     */
    @ToFlyAppLog(title="新增菜单表" )
    @ApiOperation(value = "新增菜单表")
    @PostMapping
    public ResultRespone save(@RequestBody Menu menu) {
      return ResultRespone.success(menuService.save(menu));
    }

    /**
     * 修改菜单表
     * @param menu 菜单表
     * @return ResultRespone
     */
    @ToFlyAppLog(title="修改菜单表" )
    @ApiOperation(value = "修改菜单表")
    @PutMapping
    public ResultRespone updateById(@RequestBody Menu menu) {
      return ResultRespone.success(menuService.updateById(menu));
    }

    /**
     * 通过id删除菜单表
     * @param id id
     * @return ResultRespone
     */
    @ToFlyAppLog(title="通过id删除菜单表" )
    @ApiOperation(value = "通过ID删除菜单表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "ID", required = true, dataType = "Long")
    })
    @DeleteMapping("/{id}" )
    public ResultRespone removeById(@PathVariable Long id) {
        //非传统意义删除，修改禁用标志
        Menu menu=new Menu();
        menu.setId(id);
        menu.setStatusFlag("0");

        return ResultRespone.success(update(menu));
        //return ResultRespone.success(menuService.removeById(id));
    }

    /**
     * 通过id删除菜单
     * @param ids id数组
     * @return ResultRespone
     */
    @ToFlyAppLog(title="通过id删除菜单" )
    @ApiOperation(value = "通过ID删除菜单")
    @DeleteMapping("/removeByIds" )
    public ResultRespone removeByIds(@ApiParam(value = "通过ID拼接的字符串,以逗号隔开.如,'1,2,3,4,5,6,7",name = "ids",required = true) String ids) {
        String[] idss=ids.split(",");
        List<Long> list=new ArrayList();
        boolean flag=true;
        StringBuffer sb=new StringBuffer();
        for(String id:idss){

            List<RoleMenu> roleMenuList = roleMenuService.list(Wrappers.<RoleMenu>lambdaQuery()
                    .eq(RoleMenu::getMenuId, Long.valueOf(id)));
            if(roleMenuList.size()>0){
                flag=false;
                sb.append("id:").append(id).append(",该菜单在角色里还存在").append(roleMenuList.size())
                        .append("条数据;");
            }

            list.add(Long.valueOf(id));
        }
        if(flag){

            //return ResultRespone.success(menuService.removeByIds(list));
            String msg=menuService.removeMenuByIds(list);
            return StringUtil.isEmpty(msg)?ResultRespone.success(true):
                    ResultRespone.failed(msg);
        }else {
            return ResultRespone.failed("还存在角色正在使用该菜单，不能删除："+sb.toString());
        }
    }

    @ToFlyAppLog(title="通过文件批量新增菜单" )
    @ApiOperation(value = "通过文件批量新增菜单")
    @PostMapping("/batchMenu" )
    public ResultRespone uploadBatchMenu(MultipartFile file){
        return ResultRespone.success(menuService.uploadBatchMenu(file));
    }

    /**
     * 树形结构
     *
     * @param
     * @return
     */
    @GetMapping("/getTreeMenu")
    @ApiOperation(tags = { "树形菜单列表"}, value = "树形菜单列表")
    public ResultRespone getTreeMenu() {
        List<SystemMenuVO> vos = new ArrayList<>();
        List<BaseSys> systems = systemService.list(Wrappers.<BaseSys>lambdaQuery().orderByAsc(BaseSys::getCreateTime));
        List<Menu> list = menuService.queryAllMenu();
        Map<Long,List<Menu>> menuList = list.stream().collect(Collectors.groupingBy(Menu::getSysId));
        for (BaseSys s: systems){
            SystemMenuVO systemMenuVO = new SystemMenuVO();
            BeanUtils.copyProperties(s,systemMenuVO);
            systemMenuVO.setLabel(s.getSysname());
            systemMenuVO.setChildrens(menuList.get(s.getId()));
            vos.add(systemMenuVO);
        }
        return ResultRespone.success(vos);
    }

    /**
     * 通过用户动态的获取权限对应的菜单
     *
     * @param
     * @return
     */
    @GetMapping("/getTreeMenuByUser")
    @ApiOperation(tags = { "通过用户动态的获取权限对应的菜单"}, value = "通过用户动态的获取权限对应的菜单")
    public ResultRespone getTreeMenuByUser(Long id) {
        List<SystemMenuVO> vos = new ArrayList<>();
        //获取系统菜单
        List<BaseSys> systems = systemService.list(Wrappers.<BaseSys>lambdaQuery().orderByAsc(BaseSys::getCreateTime));
        List<Menu> list = menuService.getTreeMenuByUser(id);
//        List<Menu> list = menuService.getTreeMenuByUserNew(id);
        Map<Long,List<Menu>> menuList = list.stream().collect(Collectors.groupingBy(Menu::getSysId));
        for (BaseSys s: systems){
                SystemMenuVO systemMenuVO = new SystemMenuVO();
                BeanUtils.copyProperties(s, systemMenuVO);
                systemMenuVO.setLabel(s.getSysname());
            if (!CollectionUtils.isEmpty(menuList.get(s.getId()))){
                systemMenuVO.setChildrens(menuList.get(s.getId()));
                vos.add(systemMenuVO);
            }
        }
        return ResultRespone.success(vos);
    }

}
