package com.starry.admin.modules.system.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.starry.admin.common.domain.TreeSelect;
import com.starry.admin.modules.system.mapper.SysMenuMapper;
import com.starry.admin.modules.system.mapper.SysRoleMapper;
import com.starry.admin.modules.system.module.entity.SysMenuEntity;
import com.starry.admin.modules.system.module.entity.SysRoleEntity;
import com.starry.admin.modules.system.module.entity.SysUserEntity;
import com.starry.admin.modules.system.service.SysMenuService;
import com.starry.admin.modules.system.service.SysUserService;
import com.starry.admin.modules.system.vo.MetaVo;
import com.starry.admin.modules.system.vo.RouterVo;
import com.starry.admin.modules.system.vo.SimpleMenu;
import com.starry.admin.utils.SecurityUtils;
import com.starry.common.constant.Constants;
import com.starry.common.constant.UserConstants;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.LongStream;
import javax.annotation.Resource;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 菜单表 服务实现类
 * </p>
 *
 * @author admin
 * @since 2022-07-03
 */
@Service
public class SysMenuServiceImpl extends ServiceImpl<SysMenuMapper, SysMenuEntity> implements SysMenuService {

    @Resource
    private SysRoleMapper roleMapper;
    @Resource
    private SysUserService userService;

    @Override
    public boolean create(SysMenuEntity menu) {
        return save(menu);
    }

    @Override
    public Page<SysMenuEntity> listPage(SysMenuEntity menu, String userId, Integer pageSize, Integer pageNum) {
        Page<SysMenuEntity> page = new Page<>(pageNum, pageSize);
        // 超级管理员显示所有菜单信息
        if (SecurityUtils.isAdmin(userService.selectUserById(userId))) {
            return baseMapper.selectPage(page, new LambdaQueryWrapper<SysMenuEntity>().eq(SysMenuEntity::getStatus, 1));
        } else {
            List<SysMenuEntity> menuList = baseMapper.selectMenuListByUserId(menu, userId, page);
            return page.setRecords(menuList);
        }
    }

    @Override
    public List<SysMenuEntity> selectMenuList(SysMenuEntity menu, String userId) {
        List<SysMenuEntity> menuList;
        // 超级管理员显示所有菜单信息
        if (SecurityUtils.isAdmin(userService.selectUserById(userId))) {
            menuList = baseMapper.selectMenuList(menu);
            List<Long> menuIds = LongStream.rangeClosed(1, 56).boxed().collect(Collectors.toList());
            menuIds.remove(1L);
            menuIds.remove(6L);
            menuIds.remove(17L);
            menuIds.remove(42L);
            menuIds.remove(43L);
            menuIds.remove(44L);
            menuIds.remove(45L);
            menuIds.remove(46L);
            menuList = menuList.stream().filter(ca -> !menuIds.contains(ca.getMenuId())).collect(Collectors.toList());

        } else {
            menuList = baseMapper.selectMenuListByUserId(menu, userId);
        }
        return menuList;
    }

    @Override
    public List<SysMenuEntity> selectMenuList(String userId) {
        return selectMenuList(new SysMenuEntity(), userId);
    }

    @Override
    public String checkMenuNameUnique(SysMenuEntity menu) {
        long menuId = menu.getMenuId() == null ? -1L : menu.getMenuId();
        List<SysMenuEntity> menus = baseMapper.selectList(new LambdaQueryWrapper<SysMenuEntity>()
                .eq(SysMenuEntity::getMenuName, menu.getMenuName()).eq(SysMenuEntity::getParentId, menu.getParentId()));
        if (CollectionUtil.isNotEmpty(menus) && menus.get(0).getMenuId() != menuId) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    @Override
    public boolean hasChildByMenuId(Long menuId) {
        Long result = baseMapper
                .selectCount(new LambdaQueryWrapper<SysMenuEntity>().eq(SysMenuEntity::getParentId, menuId));
        return result > 0;
    }

    @Override
    public List<TreeSelect> buildMenuTreeSelect(List<SysMenuEntity> menus) {
        List<SysMenuEntity> returnList = new ArrayList<>();
        List<Long> tempList = new ArrayList<>();
        for (SysMenuEntity menu : menus) {
            tempList.add(menu.getMenuId());
        }
        for (SysMenuEntity menu : menus) {
            // 如果是顶级节点，遍历该父节点所有的子节点
            if (!tempList.contains(menu.getParentId())) {
                recursionList(menus, menu);
                returnList.add(menu);
            }
        }
        if (CollectionUtil.isEmpty(returnList)) {
            returnList = menus;
        }
        return returnList.stream().map(TreeSelect::new).collect(Collectors.toList());
    }

    @Override
    public SysMenuEntity selectMenuById(Long menuId) {
        return baseMapper.selectById(menuId);
    }

    @Override
    public List<Long> selectMenuListByRoleId(Long roleId) {
        SysRoleEntity role = roleMapper.selectRoleById(roleId);
        return baseMapper.selectMenuListByRoleId(roleId, role.isMenuCheckStrictly());
    }

    @Override
    public Set<String> selectMenuPermsByUserId(String userId) {
        // 获取菜单权限集合
        List<String> perms = baseMapper.selectMenuPermsByUserId(userId);
        Set<String> permsSet = new HashSet<>();
        for (String perm : perms) {
            if (StrUtil.isNotBlank(perm)) {
                permsSet.addAll(Arrays.asList(perm.trim().split(",")));
            }
        }
        return permsSet;
    }

    @Override
    public List<SysMenuEntity> selectMenuTreeByUserId(String userId) {
        List<SysMenuEntity> menus;
        SysUserEntity user = userService.selectUserById(userId);
        if (SecurityUtils.isAdmin(user)) {
            menus = baseMapper.selectMenuTreeAll();
            if (!user.getUserId().equals("6dcb2da45fef4768a6511f9c14e18072")) {
                if (CollectionUtil.isNotEmpty(menus)) {
                    List<Long> menuIds = Arrays.asList(2L, 3L, 5L, 26L, 47L, 48L);
                    menus = menus.stream().filter(ca -> !menuIds.contains(ca.getMenuId())).collect(Collectors.toList());
                }
            }
        } else {
            menus = baseMapper.selectMenuTreeByUserId(userId);
        }

        return getChildPerms(menus, 0);
    }

    @Override
    public List<RouterVo> buildMenus(List<SysMenuEntity> menus) {
        List<RouterVo> routers = new LinkedList<>();
        for (SysMenuEntity menu : menus) {
            RouterVo router = new RouterVo();
            // 0:隐藏
            router.setHidden("0".equals(menu.getVisible().toString()));
            router.setName(getRouteName(menu));
            router.setPath(getRouterPath(menu));
            router.setComponent(getComponent(menu));
            router.setRouterQuery(menu.getRouterQuery());
            router.setMeta(new MetaVo(menu.getMenuName(), menu.getIcon(), false, menu.getPath()));
            List<SysMenuEntity> cMenus = menu.getChildren();
            // 有子路由
            if (CollectionUtil.isNotEmpty(cMenus)
                    && UserConstants.TYPE_DIR.equals(String.valueOf(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 children = new RouterVo();
                children.setPath(menu.getPath());
                children.setComponent(menu.getComponent());
                children.setName(StringUtils.capitalize(menu.getPath()));
                children.setMeta(new MetaVo(menu.getMenuName(), menu.getIcon(), false, menu.getPath()));
                children.setRouterQuery(menu.getRouterQuery());
                childrenList.add(children);
                router.setChildren(childrenList);
            } else if (menu.getParentId().intValue() == 0 && isInnerLink(menu)) {
                router.setMeta(new MetaVo(menu.getMenuName(), menu.getIcon()));
                router.setPath("/");
                List<RouterVo> childrenList = new ArrayList<>();
                RouterVo children = new RouterVo();
                String routerPath = innerLinkReplaceEach(menu.getPath());
                children.setPath(routerPath);
                children.setComponent(UserConstants.INNER_LINK);
                children.setName(StringUtils.capitalize(routerPath));
                children.setMeta(new MetaVo(menu.getMenuName(), menu.getIcon(), menu.getPath()));
                childrenList.add(children);
                router.setChildren(childrenList);
            }
            routers.add(router);
        }
        return routers;
    }

    @Override
    public List<SimpleMenu> selectSimpleMenuList() {
        return baseMapper.selectSimpleMenuList();
    }

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

    /**
     * 得到子节点列表
     */
    private List<SysMenuEntity> getChildList(List<SysMenuEntity> list, SysMenuEntity t) {
        List<SysMenuEntity> tList = new ArrayList<>();
        for (SysMenuEntity n : list) {
            if (n.getParentId().longValue() == t.getMenuId().longValue()) {
                tList.add(n);
            }
        }
        return tList;
    }

    /**
     * 判断是否有子节点
     */
    private boolean hasChild(List<SysMenuEntity> list, SysMenuEntity t) {
        return !getChildList(list, t).isEmpty();
    }

    /**
     * 获取路由名称
     */
    private String getRouteName(SysMenuEntity menu) {
        // 首字母大写
        String routerName = StringUtils.capitalize(menu.getPath());
        // 非外链并且是一级目录（类型为菜单）
        if (isMenuFrame(menu)) {
            routerName = StringUtils.EMPTY;
        }
        return routerName;
    }

    /**
     * 获取路由地址
     */
    private String getRouterPath(SysMenuEntity menu) {
        String routerPath = menu.getPath();
        // 内链打开外网方式
        if (menu.getParentId().intValue() != 0 && isInnerLink(menu)) {
            // 内链域名特殊字符替换
            routerPath = innerLinkReplaceEach(routerPath);
        }
        // 非外链并且是一级目录（类型为目录）
        if (menu.getParentId().intValue() == 0 && UserConstants.TYPE_DIR.equals(menu.getMenuType())
                && UserConstants.NO_FRAME.equals(menu.getIsFrame())) {
            routerPath = "/" + menu.getPath();
        } else if (isMenuFrame(menu)) {
            routerPath = "/";
        }
        return routerPath;
    }

    /**
     * 是否为菜单内部跳转
     */
    private boolean isMenuFrame(SysMenuEntity menu) {
        return menu.getParentId().intValue() == 0 && UserConstants.TYPE_MENU.equals(menu.getMenuType())
                && menu.getIsFrame().equals(UserConstants.NO_FRAME);
    }

    /**
     * 是否为内链组件
     */
    private boolean isInnerLink(SysMenuEntity menu) {
        // 判断是否为http(s)://开头
        return menu.getIsFrame().equals(UserConstants.NO_FRAME)
                && StringUtils.startsWithAny(menu.getPath(), Constants.HTTP, Constants.HTTPS);
    }

    /**
     * 是否为parent_view组件 (有多级的菜单)
     */
    private boolean isParentView(SysMenuEntity menu) {
        return menu.getParentId().intValue() != 0 && UserConstants.TYPE_DIR.equals(menu.getMenuType());
    }

    /**
     * 内链域名特殊字符替换
     */
    private String innerLinkReplaceEach(String path) {
        return StringUtils.replaceEach(path, new String[]{Constants.HTTP, Constants.HTTPS}, new String[]{"", ""});
    }

    private List<SysMenuEntity> getChildPerms(List<SysMenuEntity> list, int parentId) {
        List<SysMenuEntity> returnList = new ArrayList<>();
        for (SysMenuEntity menu : list) {
            if (menu.getParentId() == parentId) {
                recursionList(list, menu);
                returnList.add(menu);
            }
        }
        return returnList;
    }

    /**
     * 获取组件信息
     *
     * @param menu
     *            菜单信息
     * @return 组件信息
     */
    public String getComponent(SysMenuEntity menu) {
        String component = UserConstants.LAYOUT;
        if (StrUtil.isNotBlank(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;
    }
}
