package com.boman.system.service.impl;

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

import com.boman.domain.dto.AjaxResult;
import com.boman.common.redis.RedisKey;
import com.boman.common.redis.service.RedisService;
import com.boman.domain.GenTable;
import com.boman.domain.RoleEnum;
import com.boman.domain.constant.GlobalBtn;
import com.boman.domain.SysMenu;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.boman.domain.constant.UserConstants;
import com.boman.common.core.utils.SecurityUtils;
import com.boman.common.core.utils.StringUtils;
import com.boman.common.core.utils.array.ArrayUtils;
import com.boman.common.core.utils.obj.ObjectUtils;
import com.boman.domain.dto.RoleMenuDto;
import com.boman.domain.SysRole;
import com.boman.domain.SysUser;
import com.boman.system.domain.SysRoleMenu;
import com.boman.system.domain.vo.MetaVo;
import com.boman.system.domain.vo.RouterVo;
import com.boman.system.domain.vo.TreeSelect;
import com.boman.system.mapper.SysMenuMapper;
import com.boman.system.mapper.SysRoleMapper;
import com.boman.system.mapper.SysRoleMenuMapper;
import com.boman.system.service.ISysMenuService;
import org.apache.commons.lang3.BooleanUtils;

import javax.annotation.Resource;

import static com.boman.common.core.utils.obj.ObjectUtils.*;

/**
 * 菜单 业务层处理
 *
 * @author ruoyi
 */
@Service
public class SysMenuServiceImpl implements ISysMenuService {
    public static final String PREMISSION_STRING = "perms[\"{0}\"]";

    @Autowired
    private SysMenuMapper menuMapper;

    @Autowired
    private SysRoleMapper roleMapper;

    @Autowired
    private SysRoleMenuMapper roleMenuMapper;
    @Resource
    private RedisService redisService;
    @Resource
    private ISysRoleMenuService roleMenuService;

    /**
     * 根据用户查询系统菜单列表
     *
     * @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 (SysUser.isAdmin(userId)) {
            menuList = menuMapper.selectMenuList(menu);
        } else {
            menu.getParams().put("userId", userId);
            menuList = menuMapper.selectMenuListByUserId(menu);
        }
        return menuList;
    }

    @Override
    public List<SysMenu> selectMenuListAll(SysMenu menu) {
        return menuMapper.selectMenuList(menu);
    }

    /**
     * 根据用户ID查询权限
     *
     * @param id 用户ID
     * @return 权限列表
     */
    @Override
    public Set<String> selectMenuPermsById(Long id) {
        List<String> perms = menuMapper.selectMenuPermsById(id);
        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 (SecurityUtils.isAdmin(userId)) {
            menus = menuMapper.selectMenuTreeAll();
        } else {
            menus = menuMapper.selectMenuTreeByUserId(userId);
        }
        return getChildPerms(menus, 0);
    }

    /**
     * 功能描述: 根据菜单id，找到此菜单以及子菜单下所有的叶子节点
     *
     * @param menuId menuId
     * @return java.util.List<com.boman.domain.SysMenu>
     */
    @Override
    public List<SysMenu> allLeafNodeById(Long menuId) {
        List<SysMenu> tempList = Lists.newArrayListWithCapacity(16);
        SysMenu menu = selectMenuById(menuId);
        List<SysMenu> menus = menuMapper.selectMenuList(new SysMenu());
        List<SysMenu> sysMenus = recChildList(menus, menu, tempList);
        return ObjectUtils.filter(sysMenus, menu1 -> SysMenu.BUTTON.equals(menu1.getMenuType()));
    }

    private List<SysMenu> recChildList(List<SysMenu> menus, SysMenu menu, List<SysMenu> tempList) {
        int child = 0;
        // 得到子节点列表
        List<SysMenu> childList = getChildList(menus, menu);
        for (SysMenu tChild : childList) {
            if (hasChild(menus, tChild)) {
                recChildList(menus, tChild, tempList);
            } else {
                child++;
            }
        }

        if (child == childList.size() && childList.size() != 0) {
            tempList.addAll(childList);
        }

        return tempList;
    }

    private void recursionList(List<SysMenu> menus, SysMenu menu, List<SysMenu> tempList) {
        // 得到子节点列表
        List<SysMenu> childList = getChildList(menus, menu);
        if (isEmpty(childList)) {
            return;
        }

        tempList.add(menu);
        for (SysMenu tChild : childList) {
            if (hasChild(menus, tChild)) {
                recursionList(menus, tChild, tempList);
            }
        }
    }

    /**
     * 根据角色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.setExtraParam(getExtraParam(menu));
            router.setMeta(new MetaVo(menu.getMenuName(), menu.getIcon(), StringUtils.equals("1", menu.getIsCache())));
            if (menu.getSysTableName() != null) {
                router.setSysTableName(menu.getSysTableName());
            }
            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 (isMeunFrame(menu)) {
                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.setMeta(new MetaVo(menu.getMenuName(), menu.getIcon(), StringUtils.equals("1", menu.getIsCache())));
                children.setExtraParam(getExtraParam(menu));
                if (menu.getSysTableName() != null) {
                    children.setSysTableName(menu.getSysTableName());
                }
                childrenList.add(children);
                router.setChildren(childrenList);
            }
            routers.add(router);
        }
        return routers;
    }

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

        return returnList.isEmpty() ? menus : returnList;
    }

    /**
     * 构建前端所需要树结构
     *
     * @param menus 菜单列表
     * @return 树结构列表
     */
    @Override
    public List<SysMenu> buildMenuTreeNotAddLeafNode(List<SysMenu> menus) {
        List<SysMenu> returnList = new ArrayList<>();
        List<Long> allMenuId = map(menus, SysMenu::getId);
        for (SysMenu menu : menus) {
            // 如果是顶级节点, 遍历该父节点的所有子节点
            if (!allMenuId.contains(menu.getParentId())) {
                recursionNotAddLeafNode(menus, menu);
                returnList.add(menu);
            }
        }

        return returnList.isEmpty() ? menus : returnList;
    }


    /**
     * 功能描述: 递归调用，叶子节点不放到父类中
     *
     * @param list 所有的菜单
     * @param menu 当前菜单
     */
    private void recursionNotAddLeafNode(List<SysMenu> list, SysMenu menu) {
        // 叶子结点
        int count = 0;
        // 得到子节点列表
        List<SysMenu> childList = getChildList(list, menu);
        for (SysMenu tChild : childList) {
            if (hasChild(list, tChild)) {
                recursionNotAddLeafNode(list, tChild);
            } else {
                // 为叶子节点
                count++;
            }
        }
        if (count != childList.size()) {
            menu.setChildren(childList);
        }
    }

    /**
     * 构建前端所需要下拉树结构
     *
     * @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<TreeSelect> buildMenuTreeSelectNotAddLeafNode(List<SysMenu> menus) {
        List<SysMenu> menuTrees = buildMenuTreeNotAddLeafNode(menus);
        return menuTrees.stream().map(TreeSelect::new).collect(Collectors.toList());
    }

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

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

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

    /**
     * 新增保存菜单信息
     *
     * @param menu 菜单信息
     * @return 结果
     */
    @Override
    public AjaxResult insertMenu(SysMenu menu) {
        int i = menuMapper.insertMenu(menu);
        if (menu.getId() != null) {
            return AjaxResult.success(Integer.parseInt(menu.getId().toString()));
        }
        return i > 0 ? AjaxResult.success() : AjaxResult.error();
    }

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

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

    /**
     * 逻辑删除
     * @param id
     * @return
     */
    @Override
    public int removeMenuById(Long id) {
        return menuMapper.updateMenuById(id);
    }

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

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


    /**
     * 获取路由名称
     *
     * @param menu 菜单信息
     * @return 路由名称
     */
    public String getExtraParam(SysMenu menu) {
        return menu.getExtraParam();
    }

    /**
     * 获取路由地址
     *
     * @param menu 菜单信息
     * @return 路由地址
     */
    public String getRouterPath(SysMenu menu) {
        String routerPath = menu.getPath();
        // 非外链并且是一级目录（类型为目录）
        if (0 == menu.getParentId().intValue() && UserConstants.TYPE_DIR.equals(menu.getMenuType())
                && UserConstants.NO_FRAME.equals(menu.getIsFrame())) {
            routerPath = "/" + menu.getPath();
        }
        // 非外链并且是一级目录（类型为菜单）
        else if (isMeunFrame(menu)) {
            routerPath = "/";
        }
        return routerPath;
    }

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

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

    /**
     * 是否为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 (SysMenu menu : list) {
            // 一、根据传入的某个父节点ID,遍历该父节点的所有子节点
            if (menu.getParentId() == parentId) {
                recursionFn(list, menu);
                returnList.add(menu);
            }
        }
        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);
            }
        }
    }

    /**
     * 功能描述: 获取menu下所有的子节点
     *
     * @param allMenus 所有的
     * @param menu     父节点
     * @return java.util.List<com.boman.domain.SysMenu>
     */
    @Override
    public List<SysMenu> getChildList(List<SysMenu> allMenus, SysMenu menu) {
        List<SysMenu> tlist = new ArrayList<SysMenu>();
        Iterator<SysMenu> it = allMenus.iterator();
        while (it.hasNext()) {
            SysMenu n = (SysMenu) it.next();
            if (n.getParentId().longValue() == menu.getId().longValue()) {
                tlist.add(n);
            }
        }
        return tlist;
    }

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

    @Override
    public Map<String, Object> listMenus(Long roleId, Long menuId) {
        SysMenu menu = selectMenuById(menuId);
        requireNonNull(menu, "当前菜单不存在，id = " + menuId);
        List<SysMenu> allMenu = menuMapper.selectMenuList(new SysMenu());
        List<SysMenu> tempList = Lists.newArrayListWithCapacity(16);
        recursionList(allMenu, menu, tempList);
        // 把父亲去掉
        if (tempList.size() > 1) {
            tempList.remove(0);
        }

        Map<String, Object> result = Maps.newHashMapWithExpectedSize(2);
        List<Map<String, String>> all = RoleEnum.all();
        result.put("heads", all);
        if (isEmpty(tempList)) {
            result.put("sysMenus", tempList);
            return result;
        }

        // 找到当前menuId对应的所有的叶子结点
        List<SysMenu> leafNodes = allLeafNodeById(menuId);
        List<Long> menuIdList = map(leafNodes, SysMenu::getId);
        List<String> allBtnList = RoleEnum.roles();
        List<SysRoleMenu> roleMenuList = roleMenuService.listByRoleIdMenuIdList(roleId, menuIdList);
        if (isEmpty(roleMenuList)) {
            initWhenRoleMenuIsEmpty(menuId, menu);
            result.put("sysMenus", Collections.singletonList(menu));
            return result;
        }

        List<Long> roleMenuIdList = map(roleMenuList, SysRoleMenu::getMenuId);

        for (SysMenu sysMenu : tempList) {
            List<Map<String, Object>> containsHead = RoleEnum.initData();
            List<SysMenu> childList = getChildList(allMenu, sysMenu);
            if (isEmpty(childList)) {
                continue;
            }

            List<String> btnList = getBtnFromMenu(roleMenuIdList, childList);

            String tableName = childList.get(0).getSysTableName();
            GenTable genTable = redisService.getCacheObject(RedisKey.TABLE_INFO + tableName);
            if (isEmpty(genTable)) {
                continue;
            }

            List<String> menuRoleList = ArrayUtils.split(genTable.getMenuRole(), "");

            for (String allBtn : allBtnList) {
                boolean one = btnList.contains(allBtn);
                boolean another = menuRoleList.contains(allBtn);
                if (BooleanUtils.isTrue(one) && BooleanUtils.isTrue(another)) {
                    switchBtn(containsHead, allBtn, true);
                }

                if (BooleanUtils.isFalse(one) && BooleanUtils.isTrue(another)) {
                    switchBtn(containsHead, allBtn, false);
                }

                if (BooleanUtils.isFalse(one) && BooleanUtils.isFalse(another)) {
                    switchBtn(containsHead, allBtn, "0");
                }
            }

            sysMenu.setContainsHead(containsHead);
        }

        result.put("sysMenus", tempList);
        return result;
    }

    private void initWhenRoleMenuIsEmpty(Long menuId, SysMenu menu) {
        String menuTableName = menu.getSysTableName();
        GenTable menuGenTable = redisService.getCacheObject(RedisKey.TABLE_INFO + menuTableName);
        if (isEmpty(menuGenTable)) {
            requireNonNull(menuGenTable, "当前菜单对应的表不存在，menuId = " + menuId + ", tableName = " + menuTableName);
        }

        List<String> menuRoleList = ArrayUtils.split(menuGenTable.getMenuRole(), "");
        menu.setContainsHead(RoleEnum.initDataByBtnList(menuRoleList));
    }

    /**
     * 功能描述: roleMenuIdList包含childList中的id的全部取出来
     *
     * @param roleMenuIdList roleMenuIdList
     * @param childList      childList
     * @return java.util.List<java.lang.String>
     */
    private List<String> getBtnFromMenu(List<Long> roleMenuIdList, List<SysMenu> childList) {
        List<String> btnList = Lists.newArrayList();
        for (SysMenu childMenu : childList) {
            if (roleMenuIdList.contains(childMenu.getId())) {
                String perms = childMenu.getPerms();
                if (isEmpty(perms)) {
                    throw new IllegalArgumentException("[" + childMenu.getMenuName() + "]菜单未配置权限标识");
                }

                String btn = RoleMenuDto.getBtnFromPerms(perms);
                btnList.add(btn);
            }
        }
        return btnList;
    }

    /**
     * 功能描述: 根据roleId查找的叶子结点去匹配所对应的菜单树
     *
     * @param roleId roleId
     * @return java.lang.String
     */
    @Override
    public List<SysMenu> listTreeByRoleId(Long roleId) {
        List<SysMenu> roleMenus = menuMapper.listTreeByRoleId(roleId);

        SysMenu con = new SysMenu();
        // 0 为可用的
        con.setStatus("0");
        List<SysMenu> allMenus = selectMenuListAll(con);

        List<Long> roleMenuIdList = map(roleMenus, SysMenu::getId);
        List<SysMenu> parentMenus = Lists.newArrayListWithCapacity(16);

        // 把roleMenus对应的所有的爹parentMenus找到
        recGetParent(allMenus, roleMenus, parentMenus);

        // 递归，把孩子放进父亲的怀抱
        for (SysMenu parentMenu : parentMenus) {
            recursionFn(parentMenus, parentMenu);
        }

        // 把不在roleMenus中的去除掉
        return filter(parentMenus, menu -> isNotEmpty(menu.getChildren()));
    }

    /**
     * 功能描述: 找到sonMenus对应的所有的父类，结果存放于result中
     *
     * @param allMenus allMenus
     * @param result   没有按照规则排序只是把父类全部存放于result中
     */
    @Override
    public void recGetParent(List<SysMenu> allMenus, List<SysMenu> targetMenus, List<SysMenu> result) {
        for (SysMenu sonMenu : targetMenus) {
            for (SysMenu parentMenu : allMenus) {
                if (sonMenu.getParentId().equals(parentMenu.getId())) {
                    if (isNotEmpty(result)) {
                        List<Long> idList = map(result, SysMenu::getId);
                        if (!idList.contains(parentMenu.getId())) {
                            result.add(parentMenu);
                        }
                    } else {
                        result.add(parentMenu);
                    }

                    // 顶级目录
                    if (parentMenu.getId() != 1) {
                        List<SysMenu> list = Collections.singletonList(parentMenu);
                        recGetParent(allMenus, list, result);
                        break;
                    }
                }
            }
        }
    }

    private void recBuildTree(List<SysMenu> roleMenus, SysMenu parent) {
        List<SysMenu> childList = getChildList(roleMenus, parent);

        parent.setChildren(childList);
        for (SysMenu tChild : childList) {
            if (hasChild(roleMenus, tChild)) {
                recursionFn(roleMenus, tChild);
            }
        }
    }

    /**
     * 根据用户ID查询按钮
     *
     * @param userId 用户ID
     * @return 菜单列表
     */
    @Override
    public List<SysMenu> listBtnByUserId(Long userId) {
        if (SysUser.isAdmin(userId)) {
            return menuMapper.listAllBtn();
        }

        return menuMapper.listBtnByUserId(userId);
    }

    private void switchBtn(List<Map<String, Object>> containsHead, String btn, Object value) {
        Map<String, Object> jsonObject = new HashMap<>(2);
        jsonObject.put("name", btn);
        jsonObject.put("type", value);
        switch (btn) {
            case GlobalBtn.A:
                containsHead.set(0, jsonObject);
                break;
            case GlobalBtn.M:
                containsHead.set(1, jsonObject);
                break;
            case GlobalBtn.D:
                containsHead.set(2, jsonObject);
                break;
            case GlobalBtn.Q:
                containsHead.set(3, jsonObject);
                break;
            case GlobalBtn.S:
                containsHead.set(4, jsonObject);
                break;
            case GlobalBtn.U:
                containsHead.set(5, jsonObject);
                break;
            case GlobalBtn.I:
                containsHead.set(6, jsonObject);
                break;
            case GlobalBtn.E:
                containsHead.set(7, jsonObject);
                break;
            default:
                break;
        }
    }

}
