package cc.smtweb.system.bpm.web.sys.user.role;

import cc.smtweb.framework.core.util.CommUtil;
import cc.smtweb.system.bpm.web.sys.user.dataRight.DataRightDefine;
import cc.smtweb.system.bpm.web.sys.user.dataRight.DataRightDefineCache;
import cc.smtweb.system.bpm.web.sys.user.dataRightGroup.DataRightGroup;
import cc.smtweb.system.bpm.web.sys.user.dataRightGroup.DataRightGroupCache;
import cc.smtweb.system.bpm.web.sys.user.menuPlan.*;
import cc.smtweb.system.bpm.web.sys.user.user.User;
import cc.smtweb.system.bpm.web.sys.user.user.UserCache;
import cc.smtweb.system.bpm.web.sys.user.user.UserRoleCache;

import javax.print.DocFlavor;
import java.util.*;

/**
 * @Author: tanghp
 * @Date: 2022-09-06 18:35
 * @Desc: 角色辅助类
 */
public final class RoleHelper {
    public static boolean isAdmin(long userId){
        if(userId ==1L) return true;
       User user = UserCache.getInstance().get(userId);
       if(user!=null){
           return "admin".equalsIgnoreCase(user.getNicky());
       }
       return false;
    }
    /**
     * 获取角色权限
     * @param userId 用户ID
     * @param menuPlanId 菜单方案ID
     * @return
     */
    public static List<RoleRight> getRoleRightList(long userId, long menuPlanId){
        return null;
    }
    /**
     * 获取用户的菜单权限
     * @param userId 用户ID
     * @param partyId 机构ID
     * @param incParent 是否包含父节点，（子节点配置了，把父节点也查出来）
     * @return
     */
    public static Set<Long> getRoleMenuIds(long userId,long partyId,boolean incParent){
        Set<Long> mpIds = getMenuPlanIds(userId,partyId);
        if(mpIds.size()==0){
            return  new HashSet<>();
        }
        return getRoleMenuIds(userId,partyId,mpIds.iterator().next(),incParent);
    }
    /**
     * 获取用户的菜单权限
     * @param userId 用户ID
     * @param partyId 机构ID
     * @param menuPlanId 菜单方案ID
     * @param incParent 是否包含父节点，（子节点配置了，把父节点也查出来）
     * @return
     */
    public static Set<Long>  getRoleMenuIds(long userId,long partyId, long menuPlanId,boolean incParent){
        Set<Long> menuIds = new HashSet<>();
        MenuPlan menuPlan = MenuPlanCache.getInstance().get(menuPlanId);
        if(menuPlan==null)return menuIds;
        Set<Long> roleIds = UserRoleCache.getInstance().getRoleIdByUP(userId,partyId);
        RoleCache roleCache = RoleCache.getInstance();
        roleIds.forEach((roleId)-> {
            Role role = roleCache.get(roleId);
            if(role==null || role.getSmpId()!=menuPlanId){
                return;
            }
            RoleRightContent roleRightContent = new RoleRightContent(role.getPrivilege());
            menuIds.addAll(roleRightContent.getMenuRightIds());
        });
        MenuPlanContent menuPlanContent = new MenuPlanContent(menuPlan.getContent());
        if(incParent){
            Set<Long> tempIds = new HashSet<>(menuIds);
            tempIds.forEach(id->{
                fillMenuId(id,menuPlanContent,menuIds);
            });
        }
        return menuIds;
    }
    private static void fillMenuId(Long id,MenuPlanContent menuPlanContent, Set<Long> menuIds){
        menuIds.add(id);
        MenuPlanItem parent = menuPlanContent.findParentById(id);
        if(parent!=null){
            if(!menuIds.contains(parent.getId())){
                fillMenuId(parent.getId(),menuPlanContent,menuIds);
            }
        }
    }
    /**
     * 获取用户的菜单方案
     * @param userId 用户ID
     * @param partyId 机构ID
     * @return 菜单方案ID
     */
    public static Set<Long> getMenuPlanIds(long userId,long partyId){
        Set<Long> mpList = new HashSet<>();
        Set<Long> roleIds = UserRoleCache.getInstance().getRoleIdByUP(userId,partyId);
        RoleCache roleCache = RoleCache.getInstance();
        roleIds.forEach((roleId)-> {
            Role role = roleCache.get(roleId);
            if(role!=null&&role.getSmpId()>0L){
                mpList.add(role.getSmpId());
            }
        });
        return mpList;
    }
    /**
     * 获取用户的菜单方案
     * @param userId 用户ID
     * @param partyId 机构ID
     * @return 菜单方案
     */
    public static Set<MenuPlan> getMenuPlans(long userId,long partyId){
        Set<MenuPlan> mpList = new HashSet<>();
        Set<Long> roleIds = UserRoleCache.getInstance().getRoleIdByUP(userId,partyId);
        roleIds.forEach((roleId)-> {
            Role role =  RoleCache.getInstance().get(roleId);
            if(role!=null&&role.getSmpId()>0L){
                MenuPlan mp = MenuPlanCache.getInstance().get(role.getSmpId());
                if(mp!=null){
                    mpList.add(mp);
                }
            }
        });
        return mpList;
    }

    /**
     * 获取用户指定类型的数据权限组
     * @param userId 用户ID
     * @param partyId 登录的单位
     * @param menuId 菜单明细ID
     * @param dsType 数据权限类型编码
     * @return 数据权限组集合
     */
    public static Set<DataRightGroup> getDataRightGroup(long userId,long partyId,long menuId,String dsType){
        MenuPlanItemProvider.MenuPlanItem2 menuPlanItem2 =MenuPlanItemProvider.getInstance().getMenuPlanItem(menuId);
        if(menuPlanItem2 ==null){
            return  new HashSet<>();
        }
        return getDataRightGroup(userId,partyId,menuId,dsType,menuPlanItem2.getMpId());
    }

    /**
     *  获取用户指定类型的数据权限组
     * @param userId 用户ID
     * @param partyId 登录单位
     * @param dsType 数据权限类型编码 参见 BpmEnum.DataRightType
     * @param menuPlanId 菜单方案id
     * @return 据权限组集合
     */
    public static Set<DataRightGroup> getDataRightGroup(long userId,long partyId,long menuId,String dsType,long menuPlanId){
        Map<Long,DataRightGroup> mapGroup = new HashMap<>();
        //先看数据权限类型存在不
        DataRightDefine drd = DataRightDefineCache.getInstance().getByCode(dsType);
        if(drd==null)return new HashSet<>();

        Set<Long> roleIds = UserRoleCache.getInstance().getRoleIdByUP(userId,partyId);
        RoleCache roleCache = RoleCache.getInstance();
        roleIds.forEach((roleId)-> {
            Role role = roleCache.get(roleId);
            if(role==null || role.getSmpId()!=menuPlanId){
                return;
            }
            RoleRightContent roleRightContent = new RoleRightContent(role.getPrivilege());
            long groupId =roleRightContent.getDataRightGroupId(menuId,drd.getEntityId());
            if(groupId>0L){
                DataRightGroup dataRightGroup = DataRightGroupCache.getInstance().get(groupId);
                if(dataRightGroup!=null){
                    mapGroup.put(groupId,dataRightGroup);
                }
            }
        });
        return new HashSet<>(mapGroup.values());
    }

    /**
     * 获取功能权限和字段权限
     * @param userId 用户ID
     * @param partyId 登录单位ID
     * @param menuId 菜单明细ID
     * @return
     */
    public static Map<String,Object> getFuncAndFieldRight(long userId,long partyId,long menuId){
        MenuPlanItemProvider.MenuPlanItem2 menuPlanItem2 =MenuPlanItemProvider.getInstance().getMenuPlanItem(menuId);
        if(menuPlanItem2 ==null){
            return  new HashMap<>();
        }
        return getFuncAndFieldRight(userId,partyId,menuId,menuPlanItem2.getMpId());
    }

    /**
     * 获取功能权限和字段权限
     * @param userId 用户ID
     * @param partyId 登录单位ID
     * @param menuId 菜单明细ID
     * @param menuPlanId 菜单方案ID
     * @return
     */
    public static Map<String,Object> getFuncAndFieldRight(long userId,long partyId,long menuId,long menuPlanId){
        Set<Long> roleIds = UserRoleCache.getInstance().getRoleIdByUP(userId,partyId);
        RoleCache roleCache = RoleCache.getInstance();
        Set<String> fun = new HashSet<>();
        Map<String,Integer> fieldMap = new HashMap<>();
        roleIds.forEach((roleId)-> {
            Role role = roleCache.get(roleId);
            if(role==null || role.getSmpId()!=menuPlanId){
                return;
            }
            RoleRightContent roleRightContent = new RoleRightContent(role.getPrivilege());
            RoleRight roleRight = roleRightContent.getRoleRight(menuId);
            if(roleRight!=null){
                // 功能权限
               Set<String> tempFun = roleRight.getRightFunc();
               if(!CommUtil.isEmpty(tempFun)){
                   fun.addAll(tempFun);
               }
                // 字段权限
               Map<String,Integer> tempFieldMap = roleRight.getRightField();
               if(tempFieldMap!=null){
                   tempFieldMap.forEach((key,value)-> {
                       if(!fieldMap.containsKey(key)){
                           fieldMap.put(key,value);
                       }else {
                           if(fieldMap.get(key)<value){
                               fieldMap.put(key,value);
                           }
                       }
                   });
               }
            }
        });
        Map<String,Object> rtMap = new HashMap<>();
        rtMap.put("func",fun);
        rtMap.put("field",fieldMap);
        return  rtMap;
    }
}
