package com.fs.company.service.impl;

import com.fs.common.constant.UserConstants;
import com.fs.common.core.domain.entity.SysMenu;
import com.fs.common.utils.DateUtils;
import com.fs.common.utils.StringUtils;
import com.fs.company.domain.CompanyMenu;
import com.fs.company.domain.CompanyMenuTreeSelect;
import com.fs.company.domain.CompanyRole;
import com.fs.company.domain.CompanyUser;
import com.fs.company.mapper.CompanyMenuMapper;
import com.fs.company.mapper.CompanyRoleMapper;
import com.fs.company.mapper.CompanyRoleMenuMapper;
import com.fs.company.service.ICompanyMenuService;
import com.fs.system.vo.MetaVO;
import com.fs.system.vo.RouterVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

/**
 * 菜单权限Service业务层处理
 *
 * @author fs
 * @date 2021-05-25
 */
@Service
public class CompanyMenuServiceImpl implements ICompanyMenuService
{
    @Autowired
    private CompanyMenuMapper companyMenuMapper;
    @Autowired
    private CompanyRoleMapper roleMapper;
    @Autowired
    private CompanyRoleMenuMapper roleMenuMapper;
    /**
     * 查询菜单权限
     *
     * @param menuId 菜单权限ID
     * @return 菜单权限
     */
    @Override
    public CompanyMenu selectCompanyMenuById(Long menuId)
    {
        return companyMenuMapper.selectCompanyMenuById(menuId);
    }

    /**
     * 查询菜单权限列表
     *
     * @param companyMenu 菜单权限
     * @return 菜单权限
     */
    @Override
    public List<CompanyMenu> selectCompanyMenuList(CompanyMenu companyMenu)
    {
        return companyMenuMapper.selectCompanyMenuList(companyMenu);
    }

    /**
     * 新增菜单权限
     *
     * @param companyMenu 菜单权限
     * @return 结果
     */
    @Override
    public int insertCompanyMenu(CompanyMenu companyMenu)
    {
        companyMenu.setCreateTime(DateUtils.getNowDate());
        return companyMenuMapper.insertCompanyMenu(companyMenu);
    }

    /**
     * 修改菜单权限
     *
     * @param companyMenu 菜单权限
     * @return 结果
     */
    @Override
    public int updateCompanyMenu(CompanyMenu companyMenu)
    {
        companyMenu.setUpdateTime(DateUtils.getNowDate());
        return companyMenuMapper.updateCompanyMenu(companyMenu);
    }

    /**
     * 批量删除菜单权限
     *
     * @param menuIds 需要删除的菜单权限ID
     * @return 结果
     */
    @Override
    public int deleteCompanyMenuByIds(Long[] menuIds)
    {
        return companyMenuMapper.deleteCompanyMenuByIds(menuIds);
    }

    /**
     * 删除菜单权限信息
     *
     * @param menuId 菜单权限ID
     * @return 结果
     */
    @Override
    public int deleteCompanyMenuById(Long menuId)
    {
        return companyMenuMapper.deleteCompanyMenuById(menuId);
    }

    @Override
    public List<CompanyMenu> selectMenuTreeByUserId(Long userId, boolean isAdmin) {
        List<CompanyMenu> menus = null;
        if (isAdmin)
        {
            menus = companyMenuMapper.selectMenuTreeAll();
        }
        else
        {
            menus = companyMenuMapper.selectMenuTreeByUserId(userId);
        }
        return getChildPerms(menus, 0);
    }

    @Override
    public List<CompanyMenu> selectMenuTreeByCompany(Long userId, boolean isAdmin) {
        List<CompanyMenu> menus = null;
        if (isAdmin)
        {
            menus = companyMenuMapper.selectMenuTreeAllByCompany();
        }
        else
        {
            menus = companyMenuMapper.selectMenuTreeByCompanyUserId(userId);
        }
        return getChildPerms(menus, 0);
    }

    @Override
    public List<CompanyMenu> buildMenuTree(List<CompanyMenu> menus)
    {
        List<CompanyMenu> returnList = new ArrayList<CompanyMenu>();
        List<Long> tempList = new ArrayList<Long>();
        for (CompanyMenu dept : menus)
        {
            tempList.add(dept.getMenuId());
        }
        for (Iterator<CompanyMenu> iterator = menus.iterator(); iterator.hasNext();)
        {
            CompanyMenu menu = (CompanyMenu) iterator.next();
            // 如果是顶级节点, 遍历该父节点的所有子节点
            if (!tempList.contains(menu.getParentId()))
            {
                recursionFn(menus, menu);
                returnList.add(menu);
            }
        }
        if (returnList.isEmpty())
        {
            returnList = menus;
        }
        return returnList;
    }

    @Override
    public List<Integer> selectMenuListByRoleId(Long roleId) {
        CompanyRole role = roleMapper.selectCompanyRoleById(roleId);
        return companyMenuMapper.selectMenuListByRoleId(roleId, role.getMenuCheckStrictly());
    }

    @Override
    public boolean checkMenuExistRole(Long menuId) {
        int result = roleMenuMapper.checkMenuExistRole(menuId);
        return result > 0 ? true : false;
    }

    @Override
    public boolean hasChildByMenuId(Long menuId) {
        int result = companyMenuMapper.hasChildByMenuId(menuId);
        return result > 0 ? true : false;
    }



    @Override
    public List<RouterVO> buildMenus(List<CompanyMenu> menus) {

        List<RouterVO> routers = new LinkedList<RouterVO>();
        for (CompanyMenu menu : menus)
        {
            RouterVO router = new RouterVO();
            router.setIsFrame(menu.getIsFrame());
            router.setHidden("1".equals(menu.getVisible()));
            router.setName(getRouteName(menu));
            router.setPath(getRouterPath(menu));
            router.setComponent(getComponent(menu));
            router.setMeta(new MetaVO(menu.getMenuName(), menu.getIcon(), StringUtils.equals("1", menu.getIsCache().toString())));
            List<CompanyMenu> cMenus = menu.getChildren();
            if (!cMenus.isEmpty() && cMenus.size() > 0 && UserConstants.TYPE_DIR.equals(menu.getMenuType()))
            {
                router.setAlwaysShow(true);
                router.setRedirect("noRedirect");
                router.setChildren(buildMenus(cMenus));
            }
            else if (isMenuFrame(menu))
            {
                List<RouterVO> childrenList = new ArrayList<RouterVO>();
                RouterVO children = new RouterVO();
                children.setIsFrame(menu.getIsFrame());
                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().toString())));
                childrenList.add(children);
                router.setChildren(childrenList);
            }
            routers.add(router);
        }
        return routers;
    }

    @Override
    public Collection<? extends String> selectMenuPermsByUserId(Long userId) {
        List<String> perms = companyMenuMapper.selectMenuPermsByUserId(userId);
        Set<String> permsSet = new HashSet<>();
        for (String perm : perms)
        {
            if (StringUtils.isNotEmpty(perm))
            {
                permsSet.addAll(Arrays.asList(perm.trim().split(",")));
            }
        }
        return permsSet;
    }

    @Override
    public List<CompanyMenu> selectMenuList(CompanyMenu menu, Long userId, String userType) {
        List<CompanyMenu> menuList = null;
        // 管理员显示所有菜单信息
        if (CompanyUser.isAdmin(userType))
        {
            menuList = companyMenuMapper.selectCompanyMenuList(menu);
        }
        else
        {
            menu.getParams().put("userId", userId);
            menuList = companyMenuMapper.selectCompanyMenuList(menu);
        }
        return menuList;
    }

    @Override
    public List<CompanyMenu> selectMenuListByCompany(CompanyMenu menu, Long userId, String userType) {
        List<CompanyMenu> menuList = null;
        // 管理员显示所有菜单信息
        if (CompanyUser.isAdmin(userType))
        {
            menuList = companyMenuMapper.selectCompanyMenuListByCompany(menu);
        }
        else
        {
            menu.getParams().put("userId", userId);
            menuList = companyMenuMapper.selectCompanyMenuListByCompany(menu);
        }
        return menuList;
    }

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

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

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

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

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

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

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

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

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

    }
    public boolean isParentView(CompanyMenu menu)
    {
        return menu.getParentId().intValue() != 0 && UserConstants.TYPE_DIR.equals(menu.getMenuType());
    }

}
