package com.yunfeiyun.agmp.pts.service.impl;

import com.yunfeiyun.agmp.pts.domain.PtsLink;
import com.yunfeiyun.agmp.pts.domain.resvo.PtsLinkVo;
import com.yunfeiyun.agmp.pts.mapper.PtsLinkMapper;
import com.yunfeiyun.agmp.pts.service.IPtsMenuService;
import com.yunfeiyun.agmp.common.config.SystemConfig;
import com.yunfeiyun.agmp.common.constant.Constants;
import com.yunfeiyun.agmp.common.constant.ResConstants;
import com.yunfeiyun.agmp.common.constant.UserConstants;
import com.yunfeiyun.agmp.common.core.domain.TreeSelect;
import com.yunfeiyun.agmp.common.core.domain.entity.SysMenu;
import com.yunfeiyun.agmp.common.core.domain.entity.SysRole;
import com.yunfeiyun.agmp.common.core.domain.entity.SysUser;
import com.yunfeiyun.agmp.common.core.domain.model.IBaseMenu;
import com.yunfeiyun.agmp.common.core.domain.vo.MetaVo;
import com.yunfeiyun.agmp.common.core.domain.vo.RouterVo;
import com.yunfeiyun.agmp.common.framework.manager.ResManager;
import com.yunfeiyun.agmp.common.utils.StringUtils;
import com.yunfeiyun.agmp.common.web.system.domain.SysRes;
import com.yunfeiyun.agmp.common.web.system.mapper.SysMenuMapper;
import com.yunfeiyun.agmp.common.web.system.mapper.SysRoleMapper;
import com.yunfeiyun.agmp.common.web.system.mapper.SysRoleMenuMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class PtsMenuServiceImpl implements IPtsMenuService {

    @Autowired
    private SysMenuMapper menuMapper;

    @Autowired
    private SysRoleMapper roleMapper;

    @Autowired
    private SysRoleMenuMapper roleMenuMapper;

    @Autowired
    private PtsLinkMapper ptsLinkMapper;

    @Autowired
    private ResManager resManager;

    private String[] homeMenuIds = {"025504d3-df06-f61e-8ce7-91586ac9020b","839b4032-c831-a4d8-9543-44469ebc05ac"};
    private String[] sysMenuIds = {"19eb5a63-9cb8-8b5e-e3a8-afefd31b62cb"};
    /**
     * 根据用户查询系统菜单列表
     *
     * @param userId 用户ID
     * @return 菜单列表
     */
    @Override
    public List<IBaseMenu> selectMenuList(String userId)
    {
        return selectMenuList(new SysMenu(), userId);
    }

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

    /**
     * 根据用户ID查询权限
     *
     * @param userId 用户ID
     * @return 权限列表
     */
    @Override
    public Set<String> selectMenuPermsByUserId(String 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 roleId 角色ID
     * @return 权限列表
     */
    @Override
    public Set<String> selectMenuPermsByRoleId(String roleId)
    {
        List<String> perms = menuMapper.selectMenuPermsByRoleId(roleId);
        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<IBaseMenu> selectMenuTreeByUserId(String userId)
    {
        List<IBaseMenu> menus = null;
        menus = menuMapper.selectMenuTreeByUserId(userId);
        return getChildPerms(menus, SystemConfig.getTopMenuparentid());
    }

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

    /**
     * 构建前端路由所需要的菜单
     *
     * @param menus 菜单列表
     * @return 路由列表
     */
    @Override
    public List<RouterVo> buildMenus(List<IBaseMenu> menus)
    {
        List<RouterVo> routers = new LinkedList<RouterVo>();
        for (IBaseMenu menu : menus)
        {
            RouterVo router = new RouterVo();
            router.setHidden("1".equals(menu.getMenuVisiblestatus()));
            router.setName(getRouteName(menu));
            router.setPath(getRouterPath(menu));
            router.setComponent(getComponent(menu));
            router.setQuery(menu.getMenuQuery());
            router.setMenuId(menu.getMenuId() );
            router.setMeta(new MetaVo(menu.getMenuName(), menu.getMenuIcon(), StringUtils.equals("1", "1"), menu.getMenuPath()));
            List<IBaseMenu> 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.getMenuPath());
                children.setComponent(menu.getMenuComponent());
                children.setName(StringUtils.capitalize(menu.getMenuPath()));
                children.setMenuId(menu.getMenuId() );
                children.setMeta(new MetaVo(menu.getMenuName(), menu.getMenuIcon(), StringUtils.equals("1", "1"), menu.getMenuPath()));
                children.setQuery(menu.getMenuQuery());
                childrenList.add(children);
                router.setChildren(childrenList);
            }
            else if (menu.getMenuParentid().equalsIgnoreCase(SystemConfig.getTopMenuparentid()) && isInnerLink(menu))
            {
                router.setMeta(new MetaVo(menu.getMenuName(), menu.getMenuIcon()));
                router.setPath("/");
                List<RouterVo> childrenList = new ArrayList<RouterVo>();
                RouterVo children = new RouterVo();
                String routerPath = innerLinkReplaceEach(menu.getMenuPath());
                children.setPath(routerPath);
                children.setComponent(UserConstants.INNER_LINK);
                children.setName(StringUtils.capitalize(routerPath));
                children.setMenuId(menu.getMenuId() );
                children.setMeta(new MetaVo(menu.getMenuName(), menu.getMenuIcon(), menu.getMenuPath()));
                childrenList.add(children);
                router.setChildren(childrenList);
            }
            routers.add(router);
        }
        return routers;
    }

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

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

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

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

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

    /**
     * 新增保存菜单信息
     *
     * @param menu 菜单信息
     * @return 结果
     */
    @Override
    public int insertMenu(IBaseMenu menu)
    {
        if(StringUtils.isNull(menu.getMenuId()))  menu.setMenuId(menu.getId());
        if(menu.getMenuLevelcode() == null || "0".equals(menu.getMenuParentid())){
            menu.setMenuLevelcode(menu.getMenuParentid());
        }else{
            menu.setMenuLevelcode(menu.getMenuLevelcode() + "," + menu.getMenuParentid());
        }
        return menuMapper.insertMenu(menu);
    }

    /**
     * 修改保存菜单信息
     *
     * @param menu 菜单信息
     * @return 结果
     */
    @Override
    public int updateMenu(IBaseMenu menu)
    {
        IBaseMenu newParentMenu = menuMapper.selectMenuById(menu.getMenuParentid());
        if (StringUtils.isNotNull(newParentMenu) )
        {
            String newAncestors = newParentMenu.getMenuLevelcode() + "," + newParentMenu.getMenuId();
            if( newParentMenu.getMenuLevelcode() == null || "0".equals(newParentMenu.getMenuParentid() )){
                newAncestors = "0";
            }
            menu.setMenuLevelcode(newAncestors);
        }
        return menuMapper.updateMenu(menu);
    }

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

    /**
     * 校验菜单名称是否唯一
     *
     * @param menu 菜单信息
     * @return 结果
     */
    @Override
    public boolean checkMenuNameUnique(IBaseMenu menu)
    {
        String menuId = StringUtils.isNull(menu.getMenuId()) ? "-1" : menu.getMenuId();
        IBaseMenu info = menuMapper.checkMenuNameUnique(menu.getMenuName(), menu.getMenuParentid());
        if (StringUtils.isNotNull(info) && !info.getMenuId().equalsIgnoreCase(menuId.toString()))
        {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

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

    /**
     * 获取路由地址
     *
     * @param menu 菜单信息
     * @return 路由地址
     */
    public String getRouterPath(IBaseMenu menu)
    {
        String routerPath = menu.getMenuPath();
        // 内链打开外网方式
        if (menu.getMenuParentid().equalsIgnoreCase(SystemConfig.getTopMenuparentid()) && isInnerLink(menu))
        {
            routerPath = innerLinkReplaceEach(routerPath);
        }
        // 非外链并且是一级目录（类型为目录）
        if (SystemConfig.getTopMenuparentid().equalsIgnoreCase(menu.getMenuParentid()) && UserConstants.TYPE_DIR.equals(menu.getMenuType())
                && UserConstants.NO_FRAME.equals(menu.getMenuOpentype()))
        {
            routerPath = "/" + menu.getMenuPath();
        }
        // 非外链并且是一级目录（类型为菜单）
        else if (isMenuFrame(menu))
        {
            routerPath = "/";
        }
        return routerPath;
    }

    /**
     * 获取组件信息
     *
     * @param menu 菜单信息
     * @return 组件信息
     */
    public String getComponent(IBaseMenu menu)
    {
        String component = UserConstants.LAYOUT;
        if (StringUtils.isNotEmpty(menu.getMenuComponent()) && !isMenuFrame(menu))
        {
            component = menu.getMenuComponent();
        }
        else if (StringUtils.isEmpty(menu.getMenuComponent()) && !menu.getMenuParentid().equalsIgnoreCase(SystemConfig.getTopMenuparentid()) && isInnerLink(menu))
        {
            component = UserConstants.INNER_LINK;
        }
        else if (StringUtils.isEmpty(menu.getMenuComponent()) && isParentView(menu))
        {
            component = UserConstants.PARENT_VIEW;
        }
        return component;
    }

    /**
     * 是否为菜单内部跳转
     *
     * @param menu 菜单信息
     * @return 结果
     */
    public boolean isMenuFrame(IBaseMenu menu)
    {
        return menu.getMenuParentid().equalsIgnoreCase(SystemConfig.getTopMenuparentid()) && UserConstants.TYPE_MENU.equals(menu.getMenuType())
                && menu.getMenuOpentype().equals(UserConstants.NO_FRAME);
    }

    /**
     * 是否为内链组件
     *
     * @param menu 菜单信息
     * @return 结果
     */
    public boolean isInnerLink(IBaseMenu menu)
    {
        return menu.getMenuOpentype() !=null && menu.getMenuOpentype().equals(UserConstants.NO_FRAME) && StringUtils.ishttp(menu.getMenuPath());
    }

    /**
     * 是否为parent_view组件
     *
     * @param menu 菜单信息
     * @return 结果
     */
    public boolean isParentView(IBaseMenu menu)
    {
        return menu.getMenuParentid() !=null && !menu.getMenuParentid().equalsIgnoreCase(SystemConfig.getTopMenuparentid())  && UserConstants.TYPE_DIR.equals(menu.getMenuType());
    }

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

        }
        return returnList;
    }

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

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

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

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

    /**
     * 构建前端路由所需要的菜单
     *
     * @param routersVo 路由列表
     * @return 路由列表
     */
    @Override
    public PtsLinkVo buildConsoleMenus(List<RouterVo> routersVo){
        PtsLinkVo ptsLinkVo = new PtsLinkVo();
        List<PtsLink> ptsLink = ptsLinkMapper.selectPtsLinkList(null);
        List<PtsLinkVo.LinkSys> links = new LinkedList<PtsLinkVo.LinkSys>();
        List<PtsLink> ptsLinkNew = null;
        for(RouterVo router : routersVo){
            List<RouterVo> cRouters = router.getChildren();
            if (StringUtils.isNotEmpty(cRouters))
            {
                for(RouterVo cRouter : cRouters){
                    ptsLinkNew = ptsLink.stream().filter(v -> v.getLinkId().equals(cRouter.getMenuId())).collect(Collectors.toList());
                    if(ptsLinkNew != null && ptsLinkNew.size() >0 ){
                        List<SysRes> resList = resManager.queryRes(ptsLinkNew.get(0).getLinkId() ,  ResConstants.BizType.SYSLINK.getKey());
                        String menuIcon = resList !=null && resList.size() > 0 ? resList.get(0).getResUrl() : "";
                        PtsLinkVo.LinkSys vo = new PtsLinkVo.LinkSys();
                        vo.setLinkSeq(ptsLinkNew.get(0).getLinkSeq().toString());
                        vo.setLinkName(ptsLinkNew.get(0).getLinkName() );
                        vo.setLinkPath(ptsLinkNew.get(0).getLinkPath() );
                        vo.setLinkId(ptsLinkNew.get(0).getLinkId());
                        vo.setLinkIcon(menuIcon);
                        links.add(vo);
                    }
                }
            }

        }
        ptsLinkVo.setLinkSys(links);
        return ptsLinkVo;
    }


}
