package com.ruoyi.brewery.service.impl;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;

import com.ruoyi.bar.service.impl.WyBarUserServiceImpl;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.domain.TreeSelect;
import com.ruoyi.common.core.domain.entity.*;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.vo.MetaVo;
import com.ruoyi.system.domain.vo.RouterVo;
import org.springframework.stereotype.Service;
import com.ruoyi.brewery.mapper.WyBreweryMenuMapper;
import com.ruoyi.brewery.service.IWyBreweryMenuService;

import javax.annotation.Resource;

/**
 * 品牌方菜单权限Service业务层处理
 *
 * @author ruoyi
 * @date 2024-12-22
 */
@Service
public class WyBreweryMenuServiceImpl implements IWyBreweryMenuService {
    @Resource
    private WyBreweryMenuMapper wyBreweryMenuMapper;
    @Resource
    private WyBreweryUserServiceImpl userService;
    /**
     * 查询品牌方菜单权限
     *
     * @param menuId 品牌方菜单权限主键
     * @return 品牌方菜单权限
     */
    @Override
    public WyBreweryMenu selectWyBreweryMenuByMenuId(Long menuId) {
        return wyBreweryMenuMapper.selectWyBreweryMenuByMenuId(menuId);
    }

    /**
     * 查询品牌方菜单权限列表
     *
     * @param wyBreweryMenu 品牌方菜单权限
     * @return 品牌方菜单权限
     */
    @Override
    public List<WyBreweryMenu> selectWyBreweryMenuList(WyBreweryMenu wyBreweryMenu) {
        return wyBreweryMenuMapper.selectWyBreweryMenuList(wyBreweryMenu);
    }

    /**
     * 新增品牌方菜单权限
     *
     * @param wyBreweryMenu 品牌方菜单权限
     * @return 结果
     */
    @Override
    public int insertWyBreweryMenu(WyBreweryMenu wyBreweryMenu) {
        wyBreweryMenu.setCreateTime(DateUtils.getNowDate());
        return wyBreweryMenuMapper.insertWyBreweryMenu(wyBreweryMenu);
    }

    /**
     * 修改品牌方菜单权限
     *
     * @param wyBreweryMenu 品牌方菜单权限
     * @return 结果
     */
    @Override
    public int updateWyBreweryMenu(WyBreweryMenu wyBreweryMenu) {
        wyBreweryMenu.setUpdateTime(DateUtils.getNowDate());
        return wyBreweryMenuMapper.updateWyBreweryMenu(wyBreweryMenu);
    }

    /**
     * 批量删除品牌方菜单权限
     *
     * @param menuIds 需要删除的品牌方菜单权限主键
     * @return 结果
     */
    @Override
    public int deleteWyBreweryMenuByMenuIds(Long[] menuIds) {
        return wyBreweryMenuMapper.deleteWyBreweryMenuByMenuIds(menuIds);
    }

    /**
     * 删除品牌方菜单权限信息
     *
     * @param menuId 品牌方菜单权限主键
     * @return 结果
     */
    @Override
    public int deleteWyBreweryMenuByMenuId(Long menuId) {
        return wyBreweryMenuMapper.deleteWyBreweryMenuByMenuId(menuId);
    }

    /**
     * 根据用户ID查询菜单
     *
     * @param userId 用户名称
     * @return 菜单列表
     */
    @Override
    public List<WyBreweryMenu> selectMenuTreeByUserId(Long userId) {
        final WyBreweryUser wyBreweryUser = userService.selectWyBreweryUserByUserId(userId);
        List<WyBreweryMenu> menus = null;
        if (wyBreweryUser.isAdmin()) {
            menus = wyBreweryMenuMapper.selectMenuTreeAll();
        } else {
            menus = wyBreweryMenuMapper.selectMenuTreeByUserId(userId);
        }
        return getChildPerms(menus, 0);
    }

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

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

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

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

    /**
     * 构建前端路由所需要的菜单
     *
     * @param menus 菜单列表
     * @return 路由列表
     */
    @Override
    public List<RouterVo> buildMenus(List<WyBreweryMenu> menus) {
        List<RouterVo> routers = new LinkedList<RouterVo>();
        for (WyBreweryMenu 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.setQuery(menu.getQuery());
            router.setMeta(new MetaVo(menu.getMenuName(), menu.getIcon(), StringUtils.equals("1", menu.getIsCache()), menu.getPath()));
            List<WyBreweryMenu> cMenus = menu.getChildren();
            if (StringUtils.isNotEmpty(cMenus) && 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(getRouteName(menu.getRouteName(), menu.getPath()));
                children.setMeta(new MetaVo(menu.getMenuName(), menu.getIcon(), StringUtils.equals("1", menu.getIsCache()), menu.getPath()));
                children.setQuery(menu.getQuery());
                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>();
                RouterVo children = new RouterVo();
                String routerPath = innerLinkReplaceEach(menu.getPath());
                children.setPath(routerPath);
                children.setComponent(UserConstants.INNER_LINK);
                children.setName(getRouteName(menu.getRouteName(), routerPath));
                children.setMeta(new MetaVo(menu.getMenuName(), menu.getIcon(), menu.getPath()));
                childrenList.add(children);
                router.setChildren(childrenList);
            }
            routers.add(router);
        }
        return routers;
    }

    /**
     * 构建前端所需要树结构
     *
     * @param menus 菜单列表
     * @return 树结构列表
     */
    @Override
    public List<WyBreweryMenu> buildMenuTree(List<WyBreweryMenu> menus) {
        List<WyBreweryMenu> returnList = new ArrayList<WyBreweryMenu>();
        List<Long> tempList = menus.stream().map(WyBreweryMenu::getMenuId).collect(Collectors.toList());
        for (Iterator<WyBreweryMenu> iterator = menus.iterator(); iterator.hasNext(); ) {
            WyBreweryMenu menu = (WyBreweryMenu) 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<TreeSelect> buildMenuTreeSelect(List<WyBreweryMenu> menus) {
        List<WyBreweryMenu> menuTrees = buildMenuTree(menus);
        return menuTrees.stream().map(TreeSelect::new).collect(Collectors.toList());
    }

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

    /**
     * 获取路由名称，如没有配置路由名称则取路由地址
     *
     * @param name 路由名称
     * @param path 路由地址
     * @return 路由名称（驼峰格式）
     */
    public String getRouteName(String name, String path) {
        String routerName = StringUtils.isNotEmpty(name) ? name : path;
        return StringUtils.capitalize(routerName);
    }

    /**
     * 获取路由地址
     *
     * @param menu 菜单信息
     * @return 路由地址
     */
    public String getRouterPath(WyBreweryMenu menu) {
        String routerPath = menu.getPath();
        // 内链打开外网方式
        if (menu.getParentId().intValue() != 0 && isInnerLink(menu)) {
            routerPath = innerLinkReplaceEach(routerPath);
        }
        // 非外链并且是一级目录（类型为目录）
        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(WyBreweryMenu 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(WyBreweryMenu menu) {
        return menu.getParentId().intValue() == 0 && UserConstants.TYPE_MENU.equals(menu.getMenuType())
                && menu.getIsFrame().equals(UserConstants.NO_FRAME);
    }

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

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

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