package com.fs.hospital.service.impl;

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

import com.fs.common.constant.UserConstants;
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.CompanyRoleMapper;
import com.fs.company.mapper.CompanyRoleMenuMapper;
import com.fs.hospital.domain.HospitalMenuTreeSelect;
import com.fs.hospital.domain.HospitalRole;
import com.fs.hospital.domain.HospitalUser;
import com.fs.hospital.mapper.HospitalRoleMapper;
import com.fs.hospital.mapper.HospitalRoleMenuMapper;
import com.fs.hospital.vo.MetaVO;
import com.fs.hospital.vo.RouterVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.fs.hospital.mapper.HospitalMenuMapper;
import com.fs.hospital.domain.HospitalMenu;
import com.fs.hospital.service.IHospitalMenuService;

/**
 * 菜单权限Service业务层处理
 *
 * @author fs
 * @date 2024-02-26
 */
@Service
public class HospitalMenuServiceImpl implements IHospitalMenuService
{
    @Autowired
    private HospitalMenuMapper hospitalMenuMapper;
    @Autowired
    private HospitalRoleMapper roleMapper;

    @Autowired
    private HospitalRoleMenuMapper roleMenuMapper;
    /**
     * 查询菜单权限
     *
     * @param menuId 菜单权限主键
     * @return 菜单权限
     */
    @Override
    public HospitalMenu selectHospitalMenuByMenuId(Long menuId)
    {
        return hospitalMenuMapper.selectHospitalMenuByMenuId(menuId);
    }

    /**
     * 查询菜单权限列表
     *
     * @param hospitalMenu 菜单权限
     * @return 菜单权限
     */
    @Override
    public List<HospitalMenu> selectHospitalMenuList(HospitalMenu hospitalMenu)
    {
        return hospitalMenuMapper.selectHospitalMenuList(hospitalMenu);
    }

    /**
     * 新增菜单权限
     *
     * @param hospitalMenu 菜单权限
     * @return 结果
     */
    @Override
    public int insertHospitalMenu(HospitalMenu hospitalMenu)
    {
        hospitalMenu.setCreateTime(DateUtils.getNowDate());
        return hospitalMenuMapper.insertHospitalMenu(hospitalMenu);
    }

    /**
     * 修改菜单权限
     *
     * @param hospitalMenu 菜单权限
     * @return 结果
     */
    @Override
    public int updateHospitalMenu(HospitalMenu hospitalMenu)
    {
        hospitalMenu.setUpdateTime(DateUtils.getNowDate());
        return hospitalMenuMapper.updateHospitalMenu(hospitalMenu);
    }

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

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

    @Override
    public Collection<String> selectMenuPermsByUserId(Long userId) {
        List<String> perms = hospitalMenuMapper.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<HospitalMenu> selectMenuTreeByUserId(Long userId, boolean isAdmin) {
        List<HospitalMenu> menus = null;
        if (isAdmin)
        {
            menus = hospitalMenuMapper.selectMenuTreeAll();
        }
        else
        {
            menus = hospitalMenuMapper.selectMenuTreeByUserId(userId);
        }
        return getChildPerms(menus, 0);
    }

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

        List<RouterVO> routers = new LinkedList<RouterVO>();
        for (HospitalMenu 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<HospitalMenu> 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 List<HospitalMenu> selectMenuList(HospitalMenu menu, Long userId, String userType) {
        List<HospitalMenu> menuList = null;
        // 管理员显示所有菜单信息
        if (HospitalUser.isAdmin(userType))
        {
            menuList = hospitalMenuMapper.selectHospitalMenuList(menu);
        }
        else
        {
            menu.getParams().put("userId", userId);
            menuList = hospitalMenuMapper.selectHospitalMenuList(menu);
        }
        return menuList;
    }

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

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

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

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

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

    /**
     * 是否为菜单内部跳转
     *
     * @param menu 菜单信息
     * @return 结果
     */
    public boolean isMenuFrame(HospitalMenu 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(HospitalMenu menu)
    {
        String routerName = StringUtils.capitalize(menu.getPath());
        // 非外链并且是一级目录（类型为目录）
        if (isMenuFrame(menu))
        {
            routerName = StringUtils.EMPTY;
        }
        return routerName;
    }

    /**
     * 获取路由地址
     *
     * @param menu 菜单信息
     * @return 路由地址
     */
    public String getRouterPath(HospitalMenu 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(HospitalMenu 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(HospitalMenu menu)
    {
        return menu.getParentId().intValue() != 0 && UserConstants.TYPE_DIR.equals(menu.getMenuType());
    }



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

    @Override
    public boolean hasChildByMenuId(Long menuId) {
        int result = hospitalMenuMapper.hasChildByMenuId(menuId);
        return result > 0 ? true : false;
    }
    @Override
    public List<Integer> selectMenuListByRoleId(Long roleId) {
        return hospitalMenuMapper.selectMenuListByRoleId(roleId, true);
    }
}
