package com.usky.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.usky.common.core.constants.Constants;
import com.usky.common.core.util.StringUtils;
import com.usky.common.mybatis.core.AbstractCrudService;
import com.usky.common.security.utils.SecurityUtils;
import com.usky.system.domain.*;
import com.usky.system.domain.constants.UserConstants;
import com.usky.system.mapper.*;
import com.usky.system.service.ISysMenuService;
import com.usky.system.service.SysRoleMenuService;
import com.usky.system.service.SysTenantMenuService;
import com.usky.system.service.vo.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;


/**
 * 菜单 业务层处理
 *
 * @author yq
 */
@Service
public class SysMenuServiceImpl extends AbstractCrudService<SysMenuMapper, SysMenu> implements ISysMenuService {
    public static final String PREMISSION_STRING = "perms[\"{0}\"]";

    @Autowired
    private SysMenuMapper menuMapper;

    @Autowired
    private SysTenantMenuMapper tenantMenuMapper;

    @Autowired
    private SysTenantMenuService tenantMenuService;

    @Autowired
    private SysRoleMapper roleMapper;

    @Autowired
    private SysRoleMenuMapper roleMenuMapper;

    @Autowired(required = false)
    private SysRoleMenuService sysRoleMenuService;

    @Autowired
    private SysRoleMenuMapper sysRoleMenuMapper;

    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private SysPlatformMapper sysPlatformMapper;

    /**
     * 根据用户查询系统菜单列表
     *
     * @param userId 用户ID
     * @return 菜单列表
     */
    @Override
    public List<SysMenu> selectMenuList(Long userId) {
        return selectMenuList(new SysMenu(), userId);
    }

    /**
     * 查询系统菜单列表
     *
     * @param menu 菜单信息
     * @return 菜单列表
     */
    @Override
    public List<SysMenu> selectMenuList(SysMenu menu, Long userId) {
        List<SysMenu> menuList = null;
        // 管理员显示所有菜单信息
        if (SysUserVO.isAdmin(userId)) {
            menuList = menuMapper.selectMenuList(menu);
        } else {
            menu.getParams().put("userId", userId);
            menuList = menuMapper.selectMenuListByUserId(menu);
        }
        return menuList;
    }

    @Override
    public List<SysMenu> selectMenuListTwo(SysMenu menu) {
        List<SysMenu> menuList = menuMapper.selectMenuListOne(SecurityUtils.getTenantId(), menu.getMenuName());
        return menuList;
    }


    @Override
    public List<SysMenu> selectMenuListOne(Long userId) {
        List<SysMenu> menuList = menuMapper.selectMenuListByUserIdOne(userId);
        return menuList;
    }


    @Override
    public List<SysMobileMenu> selectMobileMenuListOne(Long userId) {
        List<SysMobileMenu> menuList = menuMapper.selectMobileMenuListByUserIdOne(userId);
        return menuList;
    }

    /**
     * 根据用户ID查询权限
     *
     * @param userId 用户ID
     * @return 权限列表
     */
    @Override
    public Set<String> selectMenuPermsByUserId(Long userId) {
        List<String> perms = menuMapper.selectMenuPermsByUserId(userId);
        Set<String> permsSet = new HashSet<>();
        for (String perm : perms) {
            if (StringUtils.isNotEmpty(perm)) {
                permsSet.addAll(Arrays.asList(perm.trim().split(",")));
            }
        }
        return permsSet;
    }

    /**
     * 根据租戶ID查询权限
     *
     * @param tenantId 租戶ID
     * @return 权限列表
     */
    @Override
    public Set<String> selectMenuPermsByUserIdOne(Integer tenantId) {
        List<String> perms = menuMapper.selectMenuPermsByUserIdOne(tenantId);
        Set<String> permsSet = new HashSet<>();
        for (String perm : perms) {
            if (StringUtils.isNotEmpty(perm)) {
                permsSet.addAll(Arrays.asList(perm.trim().split(",")));
            }
        }
        return permsSet;
    }


    /**
     * 根据用户ID查询菜单
     *
     * @param userId 用户名称
     * @return 菜单列表
     */
    @Override
    public List<SysMenu> selectMenuTreeByUserId(Long userId) {
        List<SysMenu> menus = null;
        if (1L == userId) {
            menus = menuMapper.selectMenuTreeAll();
        } else {
            menus = menuMapper.selectMenuTreeByUserId(userId);
        }
        return getChildPerms(menus, 0);
    }

    /**
     * 根据用户ID查询菜单
     *
     * @param userId 用户名称
     * @return 菜单列表
     */
    @Override
    public List<SysMenu> selectMenuTreeByUserId1(Long userId, Long platformId, Integer tenantId) {
        List<SysMenu> menus = null;
        if (1L == userId) {
            menus = menuMapper.selectMenuTreeAll();
        } else {
            menus = menuMapper.selectMenuTreeByUserId1(userId, platformId, tenantId);
        }
        return getChildPerms(menus, 0);
    }


    public List<SysMenu> selectMenuTreeByUserIdOne(Integer tenantId) {
        List<SysMenu> menus = menuMapper.selectMenuTreeByUserIdOne(tenantId);
        return getChildPerms(menus, 0);
    }

    public List<SysMenu> selectMenuTreeByUserIdOne1(Integer tenantId, Integer platformId) {
        List<SysMenu> menus = menuMapper.selectMenuTreeByUserIdOne1(tenantId, platformId);
        return getChildPerms(menus, 0);
    }

    @Override
    public List<SysTenantMenu> selectTenantMenuList(Integer tenantId) {
        List<SysTenantMenu> menus = tenantMenuMapper.selectTenantMenuList(tenantId);
        return menus;
    }

    /**
     * 根据角色ID查询菜单树信息
     *
     * @param roleId 角色ID
     * @return 选中菜单列表
     */
    @Override
    public List<Integer> selectMenuListByRoleId(Long roleId) {
        SysRole role = roleMapper.selectRoleById(roleId);
        return menuMapper.selectMenuListByRoleId(roleId, role.isMenuCheckStrictly());
    }

    /**
     * 构建前端路由所需要的菜单
     *
     * @param menus 菜单列表
     * @return 路由列表
     */
    @Override
    public List<RouterVo> buildMenus(List<SysMenu> menus) {
        List<RouterVo> routers = new LinkedList<RouterVo>();
        for (SysMenu menu : menus) {
            RouterVo router = new RouterVo();
            router.setHidden("1".equals(menu.getVisible()));
            router.setName(getRouteName(menu));
            router.setPath(getRouterPath(menu));
            router.setComponent(getComponent(menu));
            router.setOrderNum(menu.getOrderNum());
            router.setMeta(new MetaVo(menu.getMenuName(), menu.getMenuAliasName(), menu.getIcon(), StringUtils.equals("1", menu.getIsCache()), menu.getPath(), menu.getIsFrame(), menu.getIsNew(), menu.getRemark(),menu.getMenuMold()));
            List<SysMenu> cMenus = menu.getChildren();
            if (!cMenus.isEmpty() && cMenus.size() > 0 && UserConstants.TYPE_DIR.equals(menu.getMenuType())) {
                router.setAlwaysShow(true);
                router.setRedirect("noRedirect");
                router.setChildren(buildMenus(cMenus));
            } else if (isMenuFrame(menu)) {
                router.setMeta(null);
                List<RouterVo> childrenList = new ArrayList<RouterVo>();
                RouterVo children = new RouterVo();
                children.setPath(menu.getPath());
                children.setComponent(menu.getComponent());
                children.setName(StringUtils.capitalize(menu.getPath()));
                children.setOrderNum(menu.getOrderNum());
                children.setMeta(new MetaVo(menu.getMenuName(), menu.getMenuAliasName(), menu.getIcon(), StringUtils.equals("1", menu.getIsCache()), menu.getPath(), menu.getIsFrame(), menu.getIsNew(), menu.getRemark(),menu.getMenuMold()));
                childrenList.add(children);
                router.setChildren(childrenList);
            } else if (menu.getParentId().intValue() == 0 && isInnerLink(menu)) {
                router.setMeta(new MetaVo(menu.getMenuName(), menu.getMenuAliasName(), menu.getIcon(), menu.getIsFrame(), menu.getIsNew(), menu.getRemark(),menu.getMenuMold()));
                router.setPath("/inner");
                List<RouterVo> childrenList = new ArrayList<RouterVo>();
                RouterVo children = new RouterVo();
                String routerPath = StringUtils.replaceEach(menu.getPath(), new String[]{Constants.HTTP, Constants.HTTPS}, new String[]{"", ""});
                children.setPath(routerPath);
                children.setComponent(UserConstants.INNER_LINK);
                children.setName(StringUtils.capitalize(routerPath));
                children.setOrderNum(menu.getOrderNum());
                children.setMeta(new MetaVo(menu.getMenuName(), menu.getMenuAliasName(), menu.getIcon(), menu.getPath(), menu.getIsFrame(), menu.getIsNew(), menu.getRemark(),menu.getMenuMold()));
                childrenList.add(children);
                router.setChildren(childrenList);
            }
            routers.add(router);
        }
        return routers;
    }

    /**
     * 构建前端路由所需要的菜单
     * @return 路由列表
     */
    @Override
    public List<PlatformRouterVo> buildPlatformMenus() {
        List<PlatformRouterVo> platformRouterVos = new LinkedList<PlatformRouterVo>();
        Long userId = SecurityUtils.getUserId();
        Integer tenantId = SecurityUtils.getTenantId();
        String userType = SecurityUtils.getLoginUser().getSysUser().getUserType();
        if ("01".equals(userType)) {
            List<SysPlatformVo> sysPlatformVos = sysPlatformMapper.getTenantPlatformList(tenantId);
            if (CollectionUtils.isNotEmpty(sysPlatformVos)) {
                for (SysPlatformVo platformVo : sysPlatformVos) {
                    PlatformRouterVo platformRouterVo = new PlatformRouterVo();
                    platformRouterVo.setPlatformId(platformVo.getId());
                    platformRouterVo.setPlatformName(platformVo.getPlatformName());
                    platformRouterVo.setIcon(platformVo.getIcon());
                    platformRouterVo.setOrderNum(platformVo.getOrderNum());
                    platformRouterVo.setPlatformType(platformVo.getPlatformType());
                    List<SysMenu> menus1 = this.selectMenuTreeByUserIdOne1(tenantId,
                            platformVo.getId());
                    List<RouterVo> routers = new LinkedList<RouterVo>();
                    for (SysMenu menu : menus1) {
                        RouterVo router = new RouterVo();
                        router.setHidden("1".equals(menu.getVisible()));
                        router.setName(getRouteName(menu));
                        router.setPath(getRouterPath(menu));
                        router.setComponent(getComponent(menu));
                        router.setOrderNum(menu.getOrderNum());
                        router.setMeta(new MetaVo(menu.getMenuName(), menu.getMenuAliasName(), menu.getIcon(),
                                StringUtils.equals("1", menu.getIsCache()), menu.getPath(), menu.getIsFrame(),
                                menu.getIsNew(), menu.getRemark(),menu.getMenuMold()));
                        List<SysMenu> cMenus = menu.getChildren();
                        if (!cMenus.isEmpty() && UserConstants.TYPE_DIR.equals(menu.getMenuType())) {
                            router.setAlwaysShow(true);
                            router.setRedirect("noRedirect");
                            router.setChildren(buildMenus(cMenus));
                        } else if (isMenuFrame(menu)) {
                            router.setMeta(null);
                            List<RouterVo> childrenList = new ArrayList<RouterVo>();
                            RouterVo children = new RouterVo();
                            children.setPath(menu.getPath());
                            children.setComponent(menu.getComponent());
                            children.setName(StringUtils.capitalize(menu.getPath()));
                            children.setOrderNum(menu.getOrderNum());
                            children.setMeta(new MetaVo(menu.getMenuName(), menu.getMenuAliasName(), menu.getIcon(), StringUtils.equals("1", menu.getIsCache()), menu.getPath(), menu.getIsFrame(), menu.getIsNew(), menu.getRemark(),menu.getMenuMold()));
                            childrenList.add(children);
                            router.setChildren(childrenList);
                        } else if (menu.getParentId().intValue() == 0 && isInnerLink(menu)) {
                            router.setMeta(new MetaVo(menu.getMenuName(), menu.getMenuAliasName(), menu.getIcon(), menu.getIsFrame(), menu.getIsNew(), menu.getRemark(),menu.getMenuMold()));
                            router.setPath("/inner");
                            List<RouterVo> childrenList = new ArrayList<RouterVo>();
                            RouterVo children = new RouterVo();
                            String routerPath = StringUtils.replaceEach(menu.getPath(), new String[]{Constants.HTTP, Constants.HTTPS}, new String[]{"", ""});
                            children.setPath(routerPath);
                            children.setComponent(UserConstants.INNER_LINK);
                            children.setName(StringUtils.capitalize(routerPath));
                            children.setOrderNum(menu.getOrderNum());
                            children.setMeta(new MetaVo(menu.getMenuName(), menu.getMenuAliasName(), menu.getIcon(), menu.getPath(), menu.getIsFrame(), menu.getIsNew(), menu.getRemark(),menu.getMenuMold()));
                            childrenList.add(children);
                            router.setChildren(childrenList);
                        }
                        routers.add(router);
                    }
                    platformRouterVo.setRouterVos(routers);
                    platformRouterVos.add(platformRouterVo);
                }
            }
        } else {
            LambdaQueryWrapper<SysUserRole> queryWrapper = Wrappers.lambdaQuery();
            queryWrapper.eq(SysUserRole::getUserId, userId)
                    .eq(SysUserRole::getTenantId, tenantId);
            List<SysUserRole> userRoleList = sysUserRoleMapper.selectList(queryWrapper);
            if (CollectionUtils.isNotEmpty(userRoleList)) {
                List<SysPlatformVo> sysPlatformVos = userRoleList.stream()
                        .map(userRole -> sysPlatformMapper.getRolePlatformList(tenantId, Math.toIntExact(userRole.getRoleId())))
                        .flatMap(Collection::stream)
                        .distinct()
                        .collect(Collectors.toList());
                if (CollectionUtils.isNotEmpty(sysPlatformVos)) {
                    for (SysPlatformVo platformVo : sysPlatformVos) {
                        PlatformRouterVo platformRouterVo = new PlatformRouterVo();
                        platformRouterVo.setPlatformId(platformVo.getId());
                        platformRouterVo.setPlatformName(platformVo.getPlatformName());
                        platformRouterVo.setIcon(platformVo.getIcon());
                        platformRouterVo.setOrderNum(platformVo.getOrderNum());
                        platformRouterVo.setPlatformType(platformVo.getPlatformType());
                        List<SysMenu> menus1 = this.selectMenuTreeByUserId1(userId,
                                platformVo.getId().longValue(), tenantId);
                        List<RouterVo> routers = new LinkedList<RouterVo>();
                        for (SysMenu menu : menus1) {
                            RouterVo router = new RouterVo();
                            router.setHidden("1".equals(menu.getVisible()));
                            router.setName(getRouteName(menu));
                            router.setPath(getRouterPath(menu));
                            router.setComponent(getComponent(menu));
                            router.setOrderNum(menu.getOrderNum());
                            router.setMeta(new MetaVo(menu.getMenuName(), menu.getMenuAliasName(), menu.getIcon(), StringUtils.equals("1", menu.getIsCache()), menu.getPath(), menu.getIsFrame(), menu.getIsNew(), menu.getRemark(),menu.getMenuMold()));
                            List<SysMenu> cMenus = menu.getChildren();
                            if (!cMenus.isEmpty() && cMenus.size() > 0 && UserConstants.TYPE_DIR.equals(menu.getMenuType())) {
                                router.setAlwaysShow(true);
                                router.setRedirect("noRedirect");
                                router.setChildren(buildMenus(cMenus));
                            } else if (isMenuFrame(menu)) {
                                router.setMeta(null);
                                List<RouterVo> childrenList = new ArrayList<RouterVo>();
                                RouterVo children = new RouterVo();
                                children.setPath(menu.getPath());
                                children.setComponent(menu.getComponent());
                                children.setName(StringUtils.capitalize(menu.getPath()));
                                children.setOrderNum(menu.getOrderNum());
                                children.setMeta(new MetaVo(menu.getMenuName(), menu.getMenuAliasName(), menu.getIcon(), StringUtils.equals("1", menu.getIsCache()), menu.getPath(), menu.getIsFrame(), menu.getIsNew(), menu.getRemark(),menu.getMenuMold()));
                                childrenList.add(children);
                                router.setChildren(childrenList);
                            } else if (menu.getParentId().intValue() == 0 && isInnerLink(menu)) {
                                router.setMeta(new MetaVo(menu.getMenuName(), menu.getMenuAliasName(), menu.getIcon(), menu.getIsFrame(), menu.getIsNew(), menu.getRemark(),menu.getMenuMold()));
                                router.setPath("/inner");
                                List<RouterVo> childrenList = new ArrayList<RouterVo>();
                                RouterVo children = new RouterVo();
                                String routerPath = StringUtils.replaceEach(menu.getPath(), new String[]{Constants.HTTP, Constants.HTTPS}, new String[]{"", ""});
                                children.setPath(routerPath);
                                children.setComponent(UserConstants.INNER_LINK);
                                children.setName(StringUtils.capitalize(routerPath));
                                children.setOrderNum(menu.getOrderNum());
                                children.setMeta(new MetaVo(menu.getMenuName(), menu.getMenuAliasName(), menu.getIcon(), menu.getPath(), menu.getIsFrame(), menu.getIsNew(), menu.getRemark(),menu.getMenuMold()));
                                childrenList.add(children);
                                router.setChildren(childrenList);
                            }
                            routers.add(router);
                        }
                        platformRouterVo.setRouterVos(routers);
                        platformRouterVos.add(platformRouterVo);
                    }
                }
            }
        }
        return platformRouterVos;
    }

    /**
     * 构建前端所需要树结构
     *
     * @param menus 菜单列表
     * @return 树结构列表
     */
    @Override
    public List<SysMenu> buildMenuTree(List<SysMenu> menus) {
        List<SysMenu> returnList = new ArrayList<SysMenu>();
        List<Long> tempList = new ArrayList<Long>();
        for (SysMenu dept : menus) {
            tempList.add(dept.getMenuId());
        }
        for (Iterator<SysMenu> iterator = menus.iterator(); iterator.hasNext(); ) {
            SysMenu menu = (SysMenu) iterator.next();
            // 如果是顶级节点, 遍历该父节点的所有子节点
            if (!tempList.contains(menu.getParentId())) {
                recursionFn(menus, menu);
                returnList.add(menu);
            }
        }
        if (returnList.isEmpty()) {
            returnList = menus;
        }
        return returnList;
    }

    /**
     * 构建移动端前端所需要树结构
     *
     * @param menus 菜单列表
     * @return 树结构列表
     */
    @Override
    public List<SysMobileMenu> buildMobileMenuTree(List<SysMobileMenu> menus) {
        List<SysMobileMenu> returnList = new ArrayList<SysMobileMenu>();
        List<Long> tempList = new ArrayList<Long>();
        for (SysMobileMenu dept : menus) {
            tempList.add(dept.getMenuId());
        }
        for (Iterator<SysMobileMenu> iterator = menus.iterator(); iterator.hasNext(); ) {
            SysMobileMenu menu = (SysMobileMenu) iterator.next();
            // 如果是顶级节点, 遍历该父节点的所有子节点
            if (!tempList.contains(menu.getParentId())) {
                recursionMobileFn(menus, menu);
                returnList.add(menu);
            }
        }
        if (returnList.isEmpty()) {
            returnList = menus;
        }
        return returnList;
    }

    /**
     * 构建前端所需要下拉树结构
     *
     * @param menus 菜单列表
     * @return 下拉树结构列表
     */
    @Override
    public List<TreeSelect> buildMenuTreeSelect(List<SysMenu> menus) {
        List<SysMenu> menuTrees = buildMenuTree(menus);
        return menuTrees.stream().map(TreeSelect::new).collect(Collectors.toList());
    }

    /**
     * 构建移动端前端所需要下拉树结构
     *
     * @param menus 菜单列表
     * @return 下拉树结构列表
     */
    @Override
    public List<TreeMobileSelect> buildMobileMenuTreeSelect(List<SysMobileMenu> menus) {
        List<SysMobileMenu> menuTrees = buildMobileMenuTree(menus);
        return menuTrees.stream().map(TreeMobileSelect::new).collect(Collectors.toList());
    }

    /**
     * 根据菜单ID查询信息
     *
     * @param menuId 菜单ID
     * @return 菜单信息
     */
    @Override
    public SysMenu selectMenuById(Long menuId) {
        return menuMapper.selectMenuById(menuId);
    }

    /**
     * 是否存在菜单子节点
     *
     * @param menuId 菜单ID
     * @return 结果
     */
    @Override
    public boolean hasChildByMenuId(Long menuId) {
        int result = menuMapper.hasChildByMenuId(menuId);
        return result > 0 ? true : false;
    }

    /**
     * 查询菜单使用数量
     *
     * @param menuId 菜单ID
     * @return 结果
     */
    @Override
    public boolean checkMenuExistRole(Long menuId) {
        int result = roleMenuMapper.checkMenuExistRole(menuId);
        return result > 0 ? true : false;
    }

    /**
     * 新增保存菜单信息
     *
     * @param menu 菜单信息
     * @return 结果
     */
    @Override
    public int insertMenu(SysMenu menu) {
        return menuMapper.insertMenu(menu);
    }

    /**
     * 修改保存菜单信息
     *
     * @param menu 菜单信息
     * @return 结果
     */
    @Override
    public int updateMenu(SysMenu menu) {
        return menuMapper.updateMenu(menu);
    }

    @Override
    public void updateTenantMenu(SysTenantMenu tenantMenu) {
        UpdateWrapper<SysTenantMenu> updateWrapper = Wrappers.update();
        updateWrapper.set("menu_alias_name", tenantMenu.getMenuAliasName())
                .eq("tenant_id", tenantMenu.getTenantId())
                .eq("menu_id", tenantMenu.getMenuId());
        tenantMenuService.update(updateWrapper);


        LambdaQueryWrapper<SysUser> queryWrapper1 = Wrappers.lambdaQuery();
        queryWrapper1.select(SysUser::getUserId)
                .eq(SysUser::getStatus, 0)
                .eq(SysUser::getDelFlag, 0)
                .eq(SysUser::getTenantId, SecurityUtils.getTenantId());
        List<SysUser> list = sysUserMapper.selectList(queryWrapper1);
        List<Long> userIdList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(list)) {
            for (int i = 0; i < list.size(); i++) {
                userIdList.add(list.get(i).getUserId());
            }
        }

        if (userIdList.size() > 0) {
            LambdaQueryWrapper<SysUserRole> queryWrapper = Wrappers.lambdaQuery();
            queryWrapper.in(SysUserRole::getUserId, userIdList);
            List<SysUserRole> userRoleList = sysUserRoleMapper.selectList(queryWrapper);
            List<Long> roleIdList = new ArrayList<>();
            if (userRoleList.size() > 0) {
                for (int i = 0; i < userRoleList.size(); i++) {
                    if (roleIdList.contains(userRoleList.get(i).getRoleId())) {

                    } else {
                        roleIdList.add(userRoleList.get(i).getRoleId());
                    }
                }
            }

            if (roleIdList.size() > 0) {
                UpdateWrapper<SysRoleMenu> updateWrapper1 = Wrappers.update();
                updateWrapper1.set("menu_alias_name", tenantMenu.getMenuAliasName())
                        .in("role_id", roleIdList)
                        .eq("menu_id", tenantMenu.getMenuId());
                sysRoleMenuMapper.update(null, updateWrapper1);
            }

        }

    }

    /**
     * 删除菜单管理信息
     *
     * @param menuId 菜单ID
     * @return 结果
     */
    @Override
    public int deleteMenuById(Long menuId) {
        return menuMapper.deleteMenuById(menuId);
    }

    /**
     * 校验菜单名称是否唯一
     *
     * @param menu 菜单信息
     * @return 结果
     */
    @Override
    public String checkMenuNameUnique(SysMenu menu) {
        Long menuId = Objects.isNull(menu.getMenuId()) ? -1L : menu.getMenuId();
        SysMenu info = menuMapper.checkMenuNameUnique(menu.getMenuName(), menu.getParentId());
        if (Objects.nonNull(info) && info.getMenuId().longValue() != menuId.longValue()) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    @Override
    public String checkMenuPathUnique(SysMenu menu) {
        // 按钮等场景 path 常为空，不做重复校验
        if (StringUtils.isEmpty(menu.getPath())) {
            return UserConstants.UNIQUE;
        }
        Long menuId = Objects.isNull(menu.getMenuId()) ? -1L : menu.getMenuId();
        SysMenu info = menuMapper.checkMenuPathUnique(menu.getPath(), menu.getParentId());
        if (Objects.nonNull(info) && info.getMenuId().longValue() != menuId.longValue()) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 获取路由名称
     *
     * @param menu 菜单信息
     * @return 路由名称
     */
    public String getRouteName(SysMenu menu) {
        String routerName = StringUtils.capitalize(menu.getPath());
        // 非外链并且是一级目录（类型为目录）
        if (isMenuFrame(menu)) {
            routerName = StringUtils.EMPTY;
        }
        return routerName;
    }

    /**
     * 获取路由地址
     *
     * @param menu 菜单信息
     * @return 路由地址
     */
    public String getRouterPath(SysMenu menu) {
        String routerPath = menu.getPath();
        // 内链打开外网方式
        if (menu.getParentId().intValue() != 0 && isInnerLink(menu)) {
            routerPath = StringUtils.replaceEach(routerPath, new String[]{Constants.HTTP, Constants.HTTPS}, new String[]{"", ""});
        }
        // 非外链并且是一级目录（类型为目录）
        if (0 == menu.getParentId().intValue() && UserConstants.TYPE_DIR.equals(menu.getMenuType())
                && UserConstants.NO_FRAME.equals(menu.getIsFrame())) {
            routerPath = "/" + menu.getPath();
        }
        // 非外链并且是一级目录（类型为菜单）
        else if (isMenuFrame(menu)) {
            routerPath = "/";
        }
        return routerPath;
    }

    /**
     * 获取组件信息
     *
     * @param menu 菜单信息
     * @return 组件信息
     */
    public String getComponent(SysMenu menu) {
        String component = UserConstants.LAYOUT;
        if (StringUtils.isNotEmpty(menu.getComponent()) && !isMenuFrame(menu)) {
            component = menu.getComponent();
        } else if (StringUtils.isEmpty(menu.getComponent()) && menu.getParentId().intValue() != 0 && isInnerLink(menu)) {
            component = UserConstants.INNER_LINK;
        } else if (StringUtils.isEmpty(menu.getComponent()) && isParentView(menu)) {
            component = UserConstants.PARENT_VIEW;
        }
        return component;
    }

    /**
     * 是否为菜单内部跳转
     *
     * @param menu 菜单信息
     * @return 结果
     */
    public boolean isMenuFrame(SysMenu menu) {
        return menu.getParentId().intValue() == 0 && UserConstants.TYPE_MENU.equals(menu.getMenuType())
                && menu.getIsFrame().equals(UserConstants.NO_FRAME);
    }

    /**
     * 是否为内链组件
     *
     * @param menu 菜单信息
     * @return 结果
     */
    public boolean isInnerLink(SysMenu menu) {
        return menu.getIsFrame().equals(UserConstants.NO_FRAME) && StringUtils.startsWithAny(menu.getPath(), Constants.HTTP, Constants.HTTPS);
    }

    /**
     * 是否为parent_view组件
     *
     * @param menu 菜单信息
     * @return 结果
     */
    public boolean isParentView(SysMenu menu) {
        return menu.getParentId().intValue() != 0 && UserConstants.TYPE_DIR.equals(menu.getMenuType());
    }

    /**
     * 根据父节点的ID获取所有子节点
     *
     * @param list 分类表
     * @param parentId 传入的父节点ID
     * @return String
     */
    public List<SysMenu> getChildPerms(List<SysMenu> list, int parentId) {
        List<SysMenu> returnList = new ArrayList<SysMenu>();
        for (Iterator<SysMenu> iterator = list.iterator(); iterator.hasNext(); ) {
            SysMenu t = (SysMenu) iterator.next();
            // 一、根据传入的某个父节点ID,遍历该父节点的所有子节点
            if (t.getParentId() == parentId) {
                recursionFn(list, t);
                returnList.add(t);
            }
        }
        return returnList;
    }

    /**
     * 递归列表
     *
     * @param list
     * @param t
     */
    private void recursionFn(List<SysMenu> list, SysMenu t) {
        // 得到子节点列表
        List<SysMenu> childList = getChildList(list, t);
        t.setChildren(childList);
        for (SysMenu tChild : childList) {
            if (hasChild(list, tChild)) {
                recursionFn(list, tChild);
            }
        }
    }

    /**
     * 移动端递归列表
     *
     * @param list
     * @param t
     */
    private void recursionMobileFn(List<SysMobileMenu> list, SysMobileMenu t) {
        // 得到子节点列表
        List<SysMobileMenu> childList = getChildMobileList(list, t);
        t.setChildren(childList);
        for (SysMobileMenu tChild : childList) {
            if (hasMobileChild(list, tChild)) {
                recursionMobileFn(list, tChild);
            }
        }
    }

    /**
     * 得到子节点列表
     */
    private List<SysMenu> getChildList(List<SysMenu> list, SysMenu t) {
        List<SysMenu> tlist = new ArrayList<SysMenu>();
        Iterator<SysMenu> it = list.iterator();
        while (it.hasNext()) {
            SysMenu n = (SysMenu) it.next();
            if (n.getParentId().longValue() == t.getMenuId().longValue()) {
                tlist.add(n);
            }
        }
        return tlist;
    }

    /**
     * 得到移动端子节点列表
     */
    private List<SysMobileMenu> getChildMobileList(List<SysMobileMenu> list, SysMobileMenu t) {
        List<SysMobileMenu> tlist = new ArrayList<SysMobileMenu>();
        Iterator<SysMobileMenu> it = list.iterator();
        while (it.hasNext()) {
            SysMobileMenu n = (SysMobileMenu) it.next();
            if (n.getParentId().longValue() == t.getMenuId()) {
                tlist.add(n);
            }
        }
        return tlist;
    }

    /**
     * 判断是否有子节点
     */
    private boolean hasChild(List<SysMenu> list, SysMenu t) {
        return getChildList(list, t).size() > 0 ? true : false;
    }

    /**
     * 判断移动端是否有子节点
     */
    private boolean hasMobileChild(List<SysMobileMenu> list, SysMobileMenu t) {
        return getChildMobileList(list, t).size() > 0 ? true : false;
    }

    @Override
    public List<TenantPlatformMenuVo> selectRolePlatformMenu() {
        List<TenantPlatformMenuVo> list1 = new ArrayList<>();
        List<SysPlatformVo> list = sysPlatformMapper.getTenantPlatformList(SecurityUtils.getTenantId());
        if (CollectionUtils.isNotEmpty(list)) {
            for (int i = 0; i < list.size(); i++) {
                TenantPlatformMenuVo tenantPlatformMenuVo = new TenantPlatformMenuVo();
                tenantPlatformMenuVo.setId(list.get(i).getId());
                tenantPlatformMenuVo.setLabel(list.get(i).getPlatformName());
                List<SysMenu> menus = baseMapper.getTenantPlatformMenuList(SecurityUtils.getTenantId(), list.get(i).getId());
                tenantPlatformMenuVo.setChildren(this.buildMenuTreeSelect(menus));
                list1.add(tenantPlatformMenuVo);
            }
        }
        return list1;
    }
}
