package com.storlead.system.controller;

import cn.hutool.core.util.StrUtil;
import com.storlead.framework.common.result.Result;
import com.storlead.framework.common.util.PingyinUtil;
import com.storlead.framework.util.LoginUserUtil;
import com.storlead.system.pojo.entity.MenuEntity;
import com.storlead.system.pojo.vo.MetaVo;
import com.storlead.system.pojo.vo.RouterVo;
import com.storlead.system.pojo.vo.UserMenuVO;
import com.storlead.system.service.IMenuService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import javax.annotation.Resource;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

/**
 * @program: sp-sales-platform
 * @description:
 * @author: chenkq
 * @create: 2024-04-09 10:02
 */

@Api(tags = "平台中心 - 系统: 权限菜单")
@Log4j2
@RestController
@RequestMapping("/sys/permission")
public class PermissionResApiController {

    @Resource
    private IMenuService menuService;
    private static final String PARENT_VIEW = "ParentView";
    private static final String LAYOUT = "Layout";

    @ApiOperation("获取用户拥有的全部菜单,权限")
    @PostMapping("getUserAccessResource")
    public Result getUserMenuList() {
        try {
            Map<String,Object> map = new HashMap();
            Long currentUserId = LoginUserUtil.getCurrentUserId();
            List<MenuEntity> userMenuList = menuService.getUserMenuList(currentUserId,Arrays.asList(0),Arrays.asList(1,2));
            List<UserMenuVO> menuls = new ArrayList();

            userMenuList.forEach(menu -> {
                UserMenuVO menuVo = new UserMenuVO();
                BeanUtils.copyProperties(menu,menuVo);
                menuls.add(menuVo);
            });
            if (!CollectionUtils.isEmpty(menuls)) {
                menuls.forEach(e -> {
                    if (StrUtil.isNotBlank(e.getMenuName())) {
                        String pyIcon = PingyinUtil.getLowFullSpell(e.getMenuName());
                        e.setIcon(pyIcon);
                    }
                });
            }
            List<UserMenuVO>  menuRes = createTreeMenus(Long.valueOf(0),menuls);
            List<RouterVo> treeRouter = new ArrayList<>();
            menuToRouter(menuRes, null, treeRouter);
            map.put("routerVo",treeRouter);
            return Result.result(map);
        }catch (Exception e) {
            e.printStackTrace();
            return Result.error("获取菜单信息错误:"+e.getMessage());
        }
    }


    @ApiOperation("获取用户拥有的全部菜单,权限")
    @PostMapping("getUserAccessResourceTest")
    public Result getUserMenuListTest() {
        try {
            Map<String,Object> map = new HashMap();

            List<MenuEntity> userMenuList = menuService.getAllMenuCreateTree();
            List<UserMenuVO> menuls = new ArrayList();
//            List<MenuEntity> menuBtnls = new ArrayList();
//            List<MenuEntity> quickMenuls = new ArrayList();
//            List<Long> qmIds = quickMenuService.listByMap(Map.of("user_id",currentUserId)).stream().map(QuickMenuEntity::getMenuId).collect(Collectors.toList());

            userMenuList.forEach(menu -> {
                UserMenuVO menuVo = new UserMenuVO();
                BeanUtils.copyProperties(menu,menuVo);
                menuls.add(menuVo);
            });
            if (!CollectionUtils.isEmpty(menuls)) {
                menuls.forEach(e -> {
                    if (StrUtil.isNotBlank(e.getMenuName())) {
                        String pyIcon = PingyinUtil.getLowFullSpell(e.getMenuName());
                        e.setIcon(pyIcon);
                    }
                });
            }
            List<UserMenuVO>  menuRes = createTreeMenus(Long.valueOf(0),menuls);
            return Result.result(menuRes);
        }catch (Exception e) {
            e.printStackTrace();
            return Result.error("获取菜单信息错误:"+e.getMessage());
        }
    }
    /**
     * 是否为parent_view组件
     */

    private void menuToRouter(List<UserMenuVO> menus, RouterVo parent,  List<RouterVo> treeRouter){

        for (UserMenuVO menu : menus) {
            RouterVo routerVo = new RouterVo() ;
            MetaVo metaVo = new MetaVo(menu.getMenuName(), menu.getIcon(), menu.getIsCache() == 0 ? true : false, menu.getId());
            if(menu.getPid() != 0L && menu.getMenuType() == 1 && StringUtils.isBlank(menu.getComponent()) ) {
                routerVo.setComponent(PARENT_VIEW);
                routerVo.setAlwaysShow(true);
            } else if((menu.getPid() == null || menu.getPid() == 0L) && menu.getMenuType() == 1 && StringUtils.isBlank(menu.getComponent()) ){
                routerVo.setComponent(LAYOUT);
                routerVo.setAlwaysShow(true);
            } else {
                routerVo.setComponent(menu.getComponent());
            }

            routerVo.setHidden(menu.getVisible());
            routerVo.setMeta(metaVo);
            routerVo.setTitle(menu.getMenuName());
            routerVo.setName(menu.getRouterName());
            routerVo.setPath(menu.getPath());
            if(parent != null) {
                parent.getChildren().add(routerVo);
            } else {
                routerVo.setAlwaysShow(true);
                treeRouter.add(routerVo);
            }
            if(menu.getChildren()!=null && menu.getChildren().size() > 0) {
                List<RouterVo> treeRouterChild = new ArrayList<>();
                routerVo.setChildren(treeRouterChild);
                menuToRouter(menu.getChildren(), routerVo, treeRouterChild);
            }
        }
    }
    /**
     * 递归生成菜单树
     */
    private List<UserMenuVO> createTreeMenus(Long pid, List<UserMenuVO> menus) {
        List<UserMenuVO> treeMenu = new ArrayList<>();
        for (UserMenuVO menu : menus) {
            if (pid.equals(menu.getPid())) {
                treeMenu.add(menu);
                List<UserMenuVO> childs =  createTreeMenus(menu.getId(), menus);
                if (childs != null && childs.size() > 0) {
                    menu.setChildren(childs);
                }
            }
        }
        return treeMenu;
    }
}
