package com.chushang.system.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chushang.common.core.constant.Constants;
import com.chushang.common.core.constant.UserConstants;
import com.chushang.common.core.util.StringUtils;
import com.chushang.security.utils.SecurityUtils;
import com.chushang.system.entity.dto.ListMenuDTO;
import com.chushang.system.entity.enums.MenuTypeEnum;
import com.chushang.system.entity.po.SysMenu;
import com.chushang.system.entity.po.SysRole;
import com.chushang.system.entity.po.SysUser;
import com.chushang.system.entity.vo.MetaVo;
import com.chushang.system.entity.vo.RouterVo;
import com.chushang.system.entity.vo.TreeSelect;
import com.chushang.system.mapper.SysMenuMapper;
import com.chushang.system.service.ISysMenuService;
import com.chushang.system.service.ISysRoleMenuService;
import com.chushang.system.service.ISysRoleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author author
 * @since 2022-08-18
 */
@Slf4j
@Service
public class SysMenuServiceImpl extends ServiceImpl<SysMenuMapper, SysMenu> implements ISysMenuService {

    @Autowired
    ISysRoleService roleService;
    @Autowired
    ISysRoleMenuService roleMenuService;

    @Override
    public Set<String> selectMenuPermsByUserId(Long userId) {
        Set<String> perms = baseMapper.selectMenuPermsByUserId(userId);
        Set<String> permsSet = new HashSet<>();
        if (CollectionUtil.isNotEmpty(perms)){
            perms.stream().filter(StringUtils::isNotEmpty)
                    .forEach(p->permsSet.addAll(Set.of(p.trim().split(","))));
        }
        return permsSet;
    }

    @Override
    public List<SysMenu> selectMenuList(ListMenuDTO menu, Long userId) {
        List<SysMenu> menuList;
        if (SecurityUtils.isAdmin())
        {
            menuList = baseMapper.selectMenuList(menu);
        }
        else
        {
            menu.getSqlParam().put("userId", userId);
            menuList = baseMapper.selectMenuListByUserId(menu);
        }
        return menuList;
    }

    @Override
    public List<TreeSelect> buildMenuTreeSelect(List<SysMenu> menus) {
        List<SysMenu> menuTrees = buildMenuTree(menus);
        return menuTrees.stream().map(TreeSelect::new).collect(Collectors.toList());
    }

    @Override
    public List<Long> selectMenuListByRoleId(Long roleId) {
        SysRole sysRole = roleService.selectRoleById(roleId);
        return baseMapper.selectMenuListByRoleId(roleId, sysRole.isMenuCheckStrictly());
    }

    @Override
    public boolean checkMenuExistRole(Long menuId) {
        return roleMenuService.checkMenuExistRole(menuId);
    }

    @Override
    public List<SysMenu> selectMenuTreeByUserId(SysUser sysUser) {
        List<SysMenu> menus;
        if (sysUser.isAdmin())
        {
            menus = baseMapper.selectMenuTreeAll();
        }
        else
        {
            menus = baseMapper.selectMenuTreeByUserId(sysUser.getUserId());
        }
        return getChildPerms(menus, 0);
    }

    @Override
    public List<RouterVo> buildMenus(List<SysMenu> menus) {
        List<RouterVo> routers = new LinkedList<>();
        for (SysMenu menu : menus)
        {
            RouterVo router = new RouterVo();
            // visible 为1 代表显示路由
            router.setHidden(!menu.getVisible());
            router.setName(getRouteName(menu));
            router.setPath(getRouterPath(menu));
            router.setComponent(getComponent(menu));
            router.setQuery(menu.getQuery());
            router.setMeta(new MetaVo(menu.getMenuName(), menu.getIcon(), !menu.getCache(), menu.getPath()));
            List<SysMenu> cMenus = menu.getChildren();
            if (!cMenus.isEmpty() && MenuTypeEnum.CATALOG.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 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(), !menu.getCache(), menu.getPath()));
                children.setQuery(menu.getQuery());
                childrenList.add(children);
                router.setChildren(childrenList);
            }
            // 是否为内链组件
            else if (menu.getParentId() == 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 Set<String> selectMenuPermsByRoleId(Long roleId) {
        return baseMapper.selectMenuPermsByRoleId(roleId);
    }

    public String getRouteName(SysMenu menu)
    {
        String routerName = StringUtils.capitalize(menu.getPath());
        // 非外链并且是一级目录（类型为目录） // 此处当为 false
        if (isMenuFrame(menu))
        {
            routerName = StringUtils.EMPTY;
        }
        return routerName;
    }

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

    /**
     * 获取路由地址
     *
     * @param menu 菜单信息
     * @return 路由地址
     */
    public String getRouterPath(SysMenu menu)
    {
        String routerPath = menu.getPath();
        // 内链打开外网方式
        if (menu.getParentId() != 0 && isInnerLink(menu))
        {
            routerPath = innerLinkReplaceEach(routerPath);
        }
        // 非外链并且是一级目录（类型为目录）
        if (0 == menu.getParentId() && MenuTypeEnum.CATALOG.equals(menu.getMenuType())
                && menu.getFrame())
        {
            routerPath = "/" + menu.getPath();
        }
        // 非外链并且是一级目录（类型为菜单）
        else if (isMenuFrame(menu))
        {
            routerPath = "/";
        }
        return routerPath;
    }

    public static void main(String[] args) {
        SysMenuServiceImpl sysMenuService = new SysMenuServiceImpl();
        SysMenu menu = new SysMenu();
        menu.setParentId(0);
        menu.setMenuName("系统管理");
        menu.setPath("system");
        menu.setMenuType(MenuTypeEnum.CATALOG);
        menu.setFrame(true);
        menu.setCache(true);
        menu.setVisible(true);
        menu.setStatus(true);
        String routerPath = sysMenuService.getRouterPath(menu);
        System.out.println(routerPath);
    }

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

    /**
     * 获取组件信息
     *
     * @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() != 0 && isInnerLink(menu))
        {
            component = UserConstants.INNER_LINK;
        }
        else if (StringUtils.isEmpty(menu.getComponent()) && isParentView(menu))
        {
            component = UserConstants.PARENT_VIEW;
        }
        return component;
    }

    /**
     * 是否为parent_view组件
     *
     * @param menu 菜单信息
     * @return 结果
     */
    public boolean isParentView(SysMenu menu)
    {
        return menu.getParentId() != 0 && MenuTypeEnum.CATALOG.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<>();
        for (SysMenu menu : list) {
            // 一、根据传入的某个父节点ID,遍历该父节点的所有子节点
            if (menu.getParentId() == parentId) {
                recursionFn(list, menu);
                returnList.add(menu);
            }
        }
        return returnList;
    }

    /**
     * 构建前端树
     */
    private List<SysMenu> buildMenuTree(List<SysMenu> menus) {
        List<SysMenu> returnList = new ArrayList<>();

        List<Long> tempList = menus.stream().map(SysMenu::getMenuId).toList();
        for (SysMenu menu : menus) {
            // 如果是顶级节点, 遍历该父节点的所有子节点
            if (!tempList.contains(menu.getParentId())) {
                recursionFn(menus, menu);
                returnList.add(menu);
            }
        }
        if (returnList.isEmpty())
        {
            returnList = menus;
        }
        return returnList;
    }
    /**
     * 递归列表
     */
    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);
            }
        }
    }
    /**
     * 得到子节点列表
     */
    private List<SysMenu> getChildList(List<SysMenu> list, SysMenu t)
    {
        List<SysMenu> cList = new ArrayList<>();
        for (SysMenu n : list) {
            if (Objects.equals(n.getParentId(), t.getMenuId())) {
                cList.add(n);
            }
        }
        return cList;
    }

    private boolean hasChild(List<SysMenu> list, SysMenu t)
    {
        return !getChildList(list, t).isEmpty();
    }

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

}

