package com.yunzhupaas.service.impl;

import cn.hutool.core.net.url.UrlBuilder;
import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.useragent.UserAgent;
import cn.hutool.http.useragent.UserAgentUtil;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.ImmutableList;
import com.yunzhupaas.base.UserInfo;
import com.yunzhupaas.base.entity.*;
import com.yunzhupaas.base.model.base.SystemBaeModel;
import com.yunzhupaas.base.model.button.ButtonModel;
import com.yunzhupaas.base.model.column.ColumnModel;
import com.yunzhupaas.base.model.form.ModuleFormModel;
import com.yunzhupaas.base.model.module.ModuleModel;
import com.yunzhupaas.base.model.resource.ResourceModel;
import com.yunzhupaas.base.service.*;
import com.yunzhupaas.config.ConfigValueUtil;
import com.yunzhupaas.constant.EventConst;
import com.yunzhupaas.constant.YunzhupaasConst;
import com.yunzhupaas.constant.MsgCode;
import com.yunzhupaas.constant.PermissionConst;
import com.yunzhupaas.database.util.TenantDataSourceUtil;
import com.yunzhupaas.exception.TenantDatabaseException;
import com.yunzhupaas.message.entity.MessageTemplateConfigEntity;
import com.yunzhupaas.message.service.MessageService;
import com.yunzhupaas.message.service.MessageTemplateConfigService;
import com.yunzhupaas.model.BaseSystemInfo;
import com.yunzhupaas.model.BuildUserCommonInfoModel;
import com.yunzhupaas.model.tenant.TenantAuthorizeModel;
import com.yunzhupaas.model.tenant.TenantVO;
import com.yunzhupaas.module.ProjectEventBuilder;
import com.yunzhupaas.permission.entity.SignEntity;
import com.yunzhupaas.portal.constant.PortalConst;
import com.yunzhupaas.portal.service.PortalDataService;
import com.yunzhupaas.exception.LoginException;
import com.yunzhupaas.granter.UserDetailsServiceBuilder;
import com.yunzhupaas.model.login.*;
import com.yunzhupaas.permission.entity.*;
import com.yunzhupaas.permission.model.authorize.AuthorizeVO;
import com.yunzhupaas.permission.service.*;
import com.yunzhupaas.permissions.PermissionInterfaceImpl;
import com.yunzhupaas.portal.service.PortalService;
import com.yunzhupaas.properties.SecurityProperties;
import com.yunzhupaas.service.LoginService;
import com.yunzhupaas.util.*;
import com.yunzhupaas.util.context.RequestContext;
import com.yunzhupaas.util.treeutil.ListToTreeUtil;
import com.yunzhupaas.util.treeutil.SumTree;
import com.yunzhupaas.util.treeutil.newtreeutil.TreeDotUtils;
import com.yunzhupaas.util.LoginHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

import static com.yunzhupaas.util.Constants.ADMIN_KEY;

/**
 * @author 云筑产品开发平台组
 * @version V3.1.0
 * @copyright 深圳市乐程软件有限公司（<a href="http://www.szlecheng.cn">...</a>）
 * @date 2024/3/16
 */
@Slf4j
@Service
public class LoginServiceImpl implements LoginService {
    @Autowired
    private ConfigValueUtil configValueUtil;
    @Autowired
    private SecurityProperties securityProperties;

    @Autowired
    private UserService userApi;
    @Autowired
    private UserRelationService userRelationApi;
    @Autowired
    private OrganizeService organizeApi;
    @Autowired
    private PositionService positionApi;
    @Autowired
    private RoleService roleApi;
    @Autowired
    private GroupService groupApi;
    @Autowired
    private AuthorizeService authorizeApi;
    @Autowired
    private SysconfigService sysconfigApi;
    @Autowired
    private PortalService portalApi;
    @Autowired
    private PortalDataService portalDataService;
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private CacheKeyUtil cacheKeyUtil;
    @Autowired
    private OrganizeRelationService organizeRelationApi;
    @Autowired
    private SystemService systemApi;
    @Autowired
    private UserDetailsServiceBuilder userDetailsServiceBuilder;
    @Autowired
    private SignService signService;
    @Autowired
    private MessageTemplateConfigService messageTemplateApi;
    @Autowired
    private MessageService sentMessageApi;
    @Autowired
    private OrganizeAdministratorService organizeAdminTratorApi;
    @Autowired
    private ModuleService moduleApi;
    @Autowired
    private PermissionGroupService permissionGroupApi;
    @Autowired
    private ModuleButtonService buttonApi;
    @Autowired
    private ModuleColumnService columnApi;
    @Autowired
    private ModuleFormService formApi;
    @Autowired
    private ModuleDataAuthorizeSchemeService dataAuthorizeSchemeApi;

    @Override
    public UserInfo getTenantAccount(UserInfo userInfo) throws LoginException {
        String tenantId = null;
        if (configValueUtil.isMultiTenancy()) {
            String[] tenantAccount = userInfo.getUserAccount().split("\\@");
            if (tenantAccount.length == 1) {
                // 只输入账号, 1:配置的二级域名下只输入账号, 2:主域名下输入了租户号
                String referer = ServletUtil.getHeader("Referer");
                if (StringUtil.isNotEmpty(referer)) {
                    String remoteHost = UrlBuilder.of(referer).getHost();
                    String apiHost = UrlBuilder.of(RequestContext.isOrignPc() ? configValueUtil.getFrontDomain()
                            : configValueUtil.getAppDomain()).getHost();
                    if (!ObjectUtil.equals(remoteHost, apiHost)
                            && remoteHost.endsWith(apiHost)) {
                        // 二级域名访问, 输入的是账号
                        tenantId = remoteHost.split("\\.")[0];
                        userInfo.setUserAccount(tenantAccount[0]);
                    }
                }
                if (tenantId == null) {
                    // 主域名访问, 输入的是租户号
                    tenantId = tenantAccount[0];
                    userInfo.setUserAccount(ADMIN_KEY);
                }
            } else {
                // 租户号@账号
                tenantId = tenantAccount[0];
                userInfo.setUserAccount(tenantAccount[1]);
            }
            if (StringUtil.isEmpty(tenantId) || tenantAccount.length > 2
                    || StringUtil.isEmpty(userInfo.getUserAccount())) {
                throw new LoginException(MsgCode.LOG102.get());
            }
            TenantVO tenantVO = TenantDataSourceUtil.getRemoteTenantInfo(tenantId);
            TenantDataSourceUtil.switchTenant(tenantId, tenantVO);
            // 切换成租户库
            userInfo.setTenantId(tenantId);
            userInfo.setTenantDbConnectionString(tenantVO.getDbName());
            userInfo.setTenantDbType(tenantVO.getType());
            // 查库测试
            BaseSystemInfo baseSystemInfo = null;
            try {
                baseSystemInfo = getBaseSystemConfig(userInfo.getTenantId());
            } catch (Exception e) {
                log.error("登录获取系统配置失败: {}", e.getMessage());
            }
            if (baseSystemInfo == null || baseSystemInfo.getSingleLogin() == null) {
                throw new TenantDatabaseException();
            }
        }
        return userInfo;
    }

    @Override
    public UserInfo userInfo(UserInfo userInfo, BaseSystemInfo sysConfigInfo) throws LoginException {
        // 获取账号信息
        UserEntity userEntity = LoginHolder.getUserEntity();
        if (userEntity == null) {
            userEntity = userDetailsServiceBuilder.getUserDetailService(userInfo.getUserDetailKey())
                    .loadUserEntity(userInfo);
            LoginHolder.setUserEntity(userEntity);
        }

        checkUser(userEntity, userInfo, sysConfigInfo);

        userInfo.setUserId(userEntity.getId());
        userInfo.setUserAccount(userEntity.getAccount());
        userInfo.setUserName(userEntity.getRealName());
        userInfo.setUserIcon(userEntity.getHeadIcon());
        userInfo.setTheme(userEntity.getTheme());
        userInfo.setOrganizeId(userEntity.getOrganizeId());
        userInfo.setPortalId(userEntity.getPortalId());
        userInfo.setMobilePhone(userEntity.getMobilePhone());
        userInfo.setEmail(userEntity.getEmail());
        userInfo.setEnabledMark(userEntity.getEnabledMark());
        userInfo.setCreateTime(userEntity.getCreatorTime());
        userInfo.setUserGender(userEntity.getGender());
        userInfo.setIsAdministrator(BooleanUtil.toBoolean(String.valueOf((userEntity.getIsAdministrator()))));
        if (!ADMIN_KEY.equals(userInfo.getUserAccount())) {
            if (ObjectUtil.isNotEmpty(userEntity.getStanding())) {
                userInfo.setIsAdministrator(Objects.equals(userEntity.getStanding(), 1));
            }
        }
        // 添加过期时间
        String time = sysConfigInfo.getTokenTimeout();
        if (StringUtil.isNotEmpty(time)) {
            Integer minu = Integer.valueOf(time);
            userInfo.setOverdueTime(DateUtil.dateAddMinutes(null, minu));
            userInfo.setTokenTimeout(minu);
        }

        String ipAddr = IpUtil.getIpAddr();
        userInfo.setLoginIpAddress(ipAddr);
        userInfo.setLoginIpAddressName(IpUtil.getIpCity(ipAddr));
        userInfo.setLoginTime(DateUtil.getmmNow());
        UserAgent userAgent = UserAgentUtil.parse(ServletUtil.getUserAgent());
        if (userAgent != null) {
            userInfo.setLoginPlatForm(userAgent.getPlatform().getName() + " " + userAgent.getOsVersion());
            userInfo.setBrowser(userAgent.getBrowser().getName() + " " + userAgent.getVersion());
        }
        userInfo.setPrevLoginTime(userEntity.getPrevLogTime());
        userInfo.setPrevLoginIpAddress(userEntity.getPrevLogIp());
        userInfo.setPrevLoginIpAddressName(IpUtil.getIpCity(userEntity.getPrevLogIp()));
        // 生成id
        String token = RandomUtil.uuId();
        userInfo.setId(cacheKeyUtil.getLoginToken(userInfo.getTenantId()) + token);

        createUserOnline(userInfo);
        return userInfo;
    }

    @Override
    public void updatePasswordMessage() {
        UserInfo userInfo = UserProvider.getUser();
        UserEntity userEntity = userApi.getInfo(userInfo.getUserId());
        BaseSystemInfo baseSystemInfo = sysconfigApi.getSysInfo();
        if (baseSystemInfo.getPasswordIsUpdatedRegularly() == 1) {
            Date changePasswordDate = userEntity.getCreatorTime();
            if (userEntity.getChangePasswordDate() != null) {
                changePasswordDate = userEntity.getChangePasswordDate();
            }
            // 当前时间
            Date nowDate = DateUtil.getNowDate();
            // 更新周期
            Integer updateCycle = baseSystemInfo.getUpdateCycle();
            // 提前N天提醒
            Integer updateInAdvance = baseSystemInfo.getUpdateInAdvance();
            Integer day = DateUtil.getDiffDays(changePasswordDate, nowDate);
            if (day >= (updateCycle - updateInAdvance)) {
                MessageTemplateConfigEntity entity = messageTemplateApi.getInfoByEnCode("XTXXTX001", "1");
                if (entity != null) {
                    List<String> toUserIds = new ArrayList<>();
                    toUserIds.add(userInfo.getUserId());
                    sentMessageApi.sentMessage(toUserIds, entity.getTitle(), entity.getContent(), userInfo,
                            Integer.parseInt(entity.getMessageSource()), Integer.parseInt(entity.getMessageType()));
                }
            }
        }
    }

    /**
     * 创建用户在线信息
     *
     * @param userInfo
     */
    private void createUserOnline(UserInfo userInfo) {
        String userId = userInfo.getUserId();
        // long time= DateUtil.getTime(userInfo.getOverdueTime()) - DateUtil.getTime(new
        // Date());

        String authorize = String.valueOf(redisUtil.getString(cacheKeyUtil.getUserAuthorize() + userId));
        // String loginOnlineKey=cacheKeyUtil.getLoginOnline() + userId;
        redisUtil.remove(authorize);
        // 记录Token
        // redisUtil.insert(userInfo.getId(), userInfo,time);
        // 记录在线
        if (ServletUtil.getIsMobileDevice()) {
            // redisUtil.insert(cacheKeyUtil.getMobileLoginOnline() + userId,
            // userInfo.getId(), time);
            // 记录移动设备CID,用于消息推送
            if (ServletUtil.getHeader("clientId") != null) {
                String clientId = ServletUtil.getHeader("clientId");
                Map<String, String> map = new HashMap<>(16);
                map.put(userInfo.getUserId(), clientId);
                redisUtil.insert(cacheKeyUtil.getMobileDeviceList(), map);
            }
        } else {
            // redisUtil.insert(loginOnlineKey, userInfo.getId(), time);
        }
    }

    private UserCommonInfoVO data(BuildUserCommonInfoModel buildUserCommonInfoModel) {
        UserInfo userInfo = buildUserCommonInfoModel.getUserInfo();
        String type = buildUserCommonInfoModel.getType();
        // 公司Id
        // List<OrganizeEntity> list = organizeApi.getList(false);
        UserEntity userEntity = buildUserCommonInfoModel.getUserEntity();
        userInfo.setManagerId(userInfo.getManagerId());
        boolean b = userInfo.getIsAdministrator();
        if (StringUtil.isEmpty(userEntity.getSystemId())) {
            SystemEntity systemEntity = buildUserCommonInfoModel.getMainSystemEntity();
            userInfo.setSystemId(systemEntity.getId());
            userEntity.setSystemId(systemEntity.getId());
        }
        if (StringUtil.isEmpty(userEntity.getAppSystemId())) {
            SystemEntity systemEntity = buildUserCommonInfoModel.getWorkSystemEntity();
            userInfo.setAppSystemId(systemEntity.getId());
            userEntity.setAppSystemId(systemEntity.getId());
        }
        this.userInfo(userInfo, userInfo.getUserId(), b, userEntity, buildUserCommonInfoModel.getSystemId());
        // userInfo.setSubOrganizeIds(this.getSubOrganizeIds(list,
        // userInfo.getOrganizeId(), b));
        List<String> subordinateIdsList = userApi.getListByManagerId(userInfo.getUserId(), null).stream()
                .map(UserEntity::getId).collect(Collectors.toList());
        userInfo.setSubordinateIds(subordinateIdsList);
        userInfo.setLoginTime(DateUtil.getmmNow());
        // if (StringUtil.isNotEmpty(userInfo.getId())) {
        // redisUtil.insert(userInfo.getId(), userInfo,
        // DateUtil.getTime(userInfo.getOverdueTime()) - DateUtil.getTime(new Date()));
        // }
        BaseSystemInfo baseSystemInfo = buildUserCommonInfoModel.getBaseSystemInfo();
        UserCommonInfoVO infoVO = JsonUtil.getJsonToBean(genUserInfo(userInfo, baseSystemInfo), UserCommonInfoVO.class);
        infoVO.setGroupIds(userInfo.getGroupIds());
        infoVO.setGroupNames(userInfo.getGroupNames());
        // 角色数组
        infoVO.setRoleIds(userInfo.getRoleIds());
        // 最后一次修改密码时间
        infoVO.setChangePasswordDate(userEntity.getChangePasswordDate());
        // 角色名称
        StringBuilder roleName = new StringBuilder();
        for (RoleEntity entity : roleApi.getListByIds(userInfo.getRoleIds(), null, false)) {
            roleName.append("," + entity.getFullName());
        }
        if (roleName.length() > 0) {
            infoVO.setRoleName(roleName.toString().replaceFirst(",", ""));
        }
        // 主管
        UserEntity info = userApi.getInfo(userEntity.getManagerId());
        if (info != null) {
            infoVO.setManager(info.getRealName() + "/" + info.getAccount());
        }
        // 手机
        infoVO.setMobilePhone(userEntity.getMobilePhone());
        // 邮箱
        infoVO.setEmail(userEntity.getEmail());
        // 生日
        infoVO.setBirthday(userEntity.getBirthday() != null ? userEntity.getBirthday().getTime() : null);
        // 姓名
        infoVO.setUserName(userEntity.getRealName());
        // 组织
        OrganizeEntity organizeEntity = organizeApi.getInfo(userInfo.getOrganizeId());
        String organizeName = null;
        String departmentId = null;
        String departmentName = null;
        List<String> departmentIdList = null;
        String organizeId = null;
        if (organizeEntity != null) {
            if (PermissionConst.DEPARTMENT.equals(organizeEntity.getCategory())) {
                organizeName = organizeEntity.getFullName();
                organizeId = organizeEntity.getId();
            }
            if (StringUtil.isNotEmpty(organizeEntity.getOrganizeIdTree())) {
                String[] split = organizeEntity.getOrganizeIdTree().split(",");
                departmentId = split.length > 0 ? split[split.length - 1] : "";
                departmentIdList = split.length > 0 ? Arrays.asList(split) : new ArrayList<>();
                departmentName = organizeApi.getFullNameByOrgIdTree(null, organizeEntity.getOrganizeIdTree(), "/");
            }
        }
        userInfo.setOrganize(departmentName);
        infoVO.setOrganizeName(departmentName);
        infoVO.setOrganizeId(departmentId);
        infoVO.setOrganizeIdList(departmentIdList == null ? new ArrayList<>() : departmentIdList);
        // 部门id
        infoVO.setDepartmentId(organizeId);
        // 部门名称
        infoVO.setDepartmentName(organizeName);
        infoVO.setIsAdministrator(BooleanUtil.toBoolean(String.valueOf(userEntity.getIsAdministrator())));
        if (!ADMIN_KEY.equals(userEntity.getAccount())) {
            if (ObjectUtil.isNotEmpty(userEntity.getStanding())) {
                userInfo.setIsAdministrator(Objects.equals(userEntity.getStanding(), 1));
                infoVO.setIsAdministrator(Objects.equals(userEntity.getStanding(), 1));
            }
        }
        return infoVO;
    }

    public UserEntity checkUser(UserEntity userEntity, UserInfo userInfo, BaseSystemInfo sysConfigInfo)
            throws LoginException {
        if (userEntity == null) {
            throw new LoginException(MsgCode.LOG101.get());
        }
        // 判断是否组织、岗位、角色、部门主管是否为空，为空则抛出异常
        // 判断是否为管理员，是否为Admin(Admin为最高账号，不受限制)
        if (!ADMIN_KEY.equals(userEntity.getAccount()) || userEntity.getIsAdministrator() != 1) {
            // 组织id为空则直接抛出异常
            if (StringUtil.isEmpty(userEntity.getOrganizeId())) {
                throw new LoginException(MsgCode.LOG004.get());
            }
        }
        if (userEntity.getIsAdministrator() == 0) {
            if (userEntity.getEnabledMark() == null) {
                throw new LoginException(MsgCode.LOG005.get());
            }
            if (userEntity.getEnabledMark() == 0) {
                throw new LoginException(MsgCode.LOG006.get());
            }
        }
        if (userEntity.getDeleteMark() != null && userEntity.getDeleteMark() == 1) {
            throw new LoginException(MsgCode.LOG007.get());
        }
        // 安全验证
        String ipAddr = IpUtil.getIpAddr();
        userInfo.setLoginIpAddress(IpUtil.getIpAddr());
        // 判断白名单
        if (!ADMIN_KEY.equals(userEntity.getAccount()) && "1".equals(sysConfigInfo.getWhitelistSwitch())) {
            List<String> ipList = Arrays.asList(sysConfigInfo.getWhitelistIp().split(","));
            if (!ipList.contains(ipAddr)) {
                throw new LoginException(MsgCode.LOG010.get());
            }
        }
        // 判断用户所属的角色是否被禁用
        if (userEntity.getIsAdministrator() == 0 &&
                organizeAdminTratorApi.getInfoByUserId(userEntity.getId()).size() == 0) {
            List<PermissionGroupEntity> permissionGroupByUserIdAndTenantId = permissionGroupApi
                    .getPermissionGroupByUserId(userEntity.getId(), null, false, null);
            if (permissionGroupByUserIdAndTenantId.size() == 0) {
                throw new LoginException(MsgCode.OA009.get());
            }
            // 如果只有组织权限的话就切换到有权限的组织
            String organizeIdByUserIdAndTenantId = permissionGroupApi.getPermissionGroupByUserId(userEntity.getId());
            if (StringUtil.isNotEmpty(organizeIdByUserIdAndTenantId)) {
                userEntity.setOrganizeId(organizeIdByUserIdAndTenantId);
            }
        }
        // 判断当前账号是否被锁定
        Integer lockMark = userEntity.getEnabledMark();
        if (Objects.nonNull(lockMark) && lockMark == 2) {
            // 获取解锁时间
            Date unlockTime = userEntity.getUnlockTime();
            // 账号锁定
            if (sysConfigInfo.getLockType() == 1 || Objects.isNull(unlockTime)) {
                throw new LoginException(MsgCode.LOG012.get());
            }
            // 延迟登陆锁定
            long millis = System.currentTimeMillis();
            // 系统设置的错误次数
            int passwordErrorsNumber = sysConfigInfo.getPasswordErrorsNumber() != null
                    ? sysConfigInfo.getPasswordErrorsNumber()
                    : 0;
            // 用户登录错误次数
            int logErrorCount = userEntity.getLogErrorCount() != null ? userEntity.getLogErrorCount() : 0;
            if (unlockTime.getTime() > millis) {
                // 转成分钟
                int time = (int) ((unlockTime.getTime() - millis) / (1000 * 60));
                throw new LoginException(MsgCode.LOG108.get(time + 1));
            } else if (unlockTime.getTime() < millis && logErrorCount >= passwordErrorsNumber) {
                // 已经接触错误时间锁定的话就重置错误次数
                userEntity.setLogErrorCount(0);
                userEntity.setEnabledMark(1);
                userApi.updateById(userEntity);
            }
        }
        return userEntity;
    }

    /**
     * 获取用户登陆信息
     *
     * @return
     */
    @Override
    public PcUserVO getCurrentUser(String type, String systemCode) {
        List<Integer> standingList = new ArrayList() {
            {
                add(3);
            }
        };
        UserInfo userInfo = UserProvider.getUser();
        SystemEntity mainSystemEntity = systemApi.getInfoByEnCode(YunzhupaasConst.MAIN_SYSTEM_CODE);
        SystemEntity workSystemEntity = systemApi.getInfoByEnCode(YunzhupaasConst.WORK_SYSTEM_CODE);
        UserEntity userEntity = userApi.getInfo(userInfo.getUserId());
        if (userEntity == null) {
            return null;
        }
        SystemEntity systemCodeEntity = systemApi.getInfoByEnCode(systemCode);
        if (StringUtil.isNotEmpty(systemCode)) {
            userInfo.setSystemCode(systemCode);
            if ("App".equals(type)) {
                throw new LoginException(MsgCode.OA010.get());
            }
            if (systemCodeEntity == null) {
                UserProvider.logout();
                throw new LoginException(MsgCode.OA011.get());
            } else if (ObjectUtil.equal(systemCodeEntity.getEnabledMark(), 0)) {
                UserProvider.logout();
                throw new LoginException(MsgCode.OA012.get());
            }
        }

        BaseSystemInfo baseSystemInfo = sysconfigApi.getSysInfo();
        List<UserSystemVO> userStanding = authorizeApi.getUserStanding(false, userEntity.getId());
        for (UserSystemVO systemVO : userStanding) {
            int stand = StringUtil.isEmpty(systemVO.getId()) ? 3 : Integer.parseInt(systemVO.getId());
            if (ObjectUtil.isEmpty(userEntity.getStanding())) {
                userEntity.setStanding(stand);
            }
            if (ObjectUtil.isEmpty(userEntity.getAppStanding())) {
                userEntity.setAppStanding(stand);
            }
        }
        BuildUserCommonInfoModel buildUserCommonInfoModel = new BuildUserCommonInfoModel(userInfo, mainSystemEntity,
                workSystemEntity, userEntity, baseSystemInfo,
                Optional.ofNullable(systemCodeEntity).isPresent() ? systemCodeEntity.getId() : null, type);
        UserCommonInfoVO infoVO = this.data(buildUserCommonInfoModel);
        AuthorizeVO authorizeModel = authorizeApi.getAuthorize(false, false, true); // this.getAuthorize(false,
                                                                                    // singletonOrg)
        List<SystemBaeModel> systemList = authorizeModel.getSystemList();
        // 从分管中获取菜单
        List<UserSystemVO> standing = authorizeApi.getUserStanding(true, userEntity.getId()).stream()
                .filter(t -> "2".equals(t.getId())).collect(Collectors.toList());
        List<OrganizeAdministratorEntity> listByUserId1 = organizeAdminTratorApi
                .getOrganizeAdministratorEntity(userInfo.getUserId(), PermissionConst.MODULE, false);
        List<String> moduleAuthorize = new ArrayList<>();
        List<String> moduleUrlAddressAuthorize = new ArrayList<>();
        if (configValueUtil.isMultiTenancy()) {
            TenantAuthorizeModel tenantAuthorizeModel = TenantDataSourceUtil
                    .getCacheModuleAuthorize(userInfo.getTenantId());
            moduleAuthorize = tenantAuthorizeModel.getModuleIdList();
            moduleUrlAddressAuthorize = tenantAuthorizeModel.getUrlAddressList();
        }
        List<ModuleEntity> moduleEntities = moduleApi.getModuleByIds(
                listByUserId1.stream().map(OrganizeAdministratorEntity::getOrganizeId).collect(Collectors.toList()),
                moduleAuthorize, moduleUrlAddressAuthorize, false);
        List<ModuleModel> moduleJsonToList = new ArrayList<>();
        if ("App".equals(type)) {
            List<SystemBaeModel> appSystemList = systemList.stream()
                    .filter(t -> !mainSystemEntity.getId().equals(t.getId())).collect(Collectors.toList());
            List<ModuleEntity> appModuleList = moduleEntities.stream()
                    .filter(t -> !mainSystemEntity.getId().equals(t.getSystemId())).collect(Collectors.toList());
            boolean appStanding = standing.stream().filter(t -> t.isCurrentStanding()).count() > 0;
            systemList.retainAll(appSystemList);
            if (appStanding) {
                moduleEntities.retainAll(appModuleList);
                moduleJsonToList.addAll(JsonUtil.getJsonToList(moduleEntities, ModuleModel.class));
            }
        } else {
            if (moduleEntities.size() > 0) {
                boolean pcStanding = standing.stream().filter(t -> t.isCurrentStanding()).count() > 0;
                if (pcStanding) {
                    SystemBaeModel systemBaeModel = JsonUtil.getJsonToBean(mainSystemEntity, SystemBaeModel.class);
                    systemList.add(systemBaeModel);
                    systemList = systemList.stream().distinct().collect(Collectors.toList());
                    moduleJsonToList.addAll(JsonUtil.getJsonToList(moduleEntities, ModuleModel.class));
                }
            }
        }
        if (standing.size() > 0) {
            standingList.add(2);
        }

        // 获取菜单权限
        List<ModuleModel> moduleList = authorizeModel.getModuleList();
        moduleList.addAll(moduleJsonToList);
        moduleList = moduleList.stream().distinct().collect(Collectors.toList());

        authorizeModel.setModuleList(moduleList);
        List<ModuleModel> moduleList1 = new ArrayList<>();
        List<ModuleModel> menuList = moduleList.stream().filter(t -> type.equals(t.getCategory()))
                .sorted(Comparator.comparing(ModuleModel::getSortCode)).collect(Collectors.toList());
        moduleList1.addAll(moduleList);

        // 岗位
        /*
         * List<String> posiList = Arrays.asList(userInfo.getPositionIds());
         * List<PositionEntity> positionList = positionApi.getPositionName(posiList,
         * false);
         * List<UserPositionVO> positionVO = new ArrayList<>();
         * for (PositionEntity positionEntity : positionList) {
         * UserPositionVO userPositionVO = new UserPositionVO();
         * userPositionVO.setName(positionEntity.getFullName());
         * userPositionVO.setId(positionEntity.getId());
         * positionVO.add(userPositionVO);
         * }
         */
        List<PermissionModel> models = new ArrayList<>();

        // 按钮等权限增加分级管理的
        // 按钮
        List<ButtonModel> buttonList = authorizeModel.getButtonList();
        List<ModuleButtonEntity> buttonByModuleId = buttonApi
                .getListByModuleIds(moduleJsonToList.stream().map(ModuleModel::getId).collect(Collectors.toList()));
        List<ButtonModel> buttonJsonToList = JsonUtil.getJsonToList(buttonByModuleId, ButtonModel.class);
        buttonList.addAll(buttonJsonToList);
        buttonList = buttonList.stream().distinct().collect(Collectors.toList());
        // 列表
        List<ColumnModel> columnList = authorizeModel.getColumnList();
        List<ModuleColumnEntity> columnByModuleId = columnApi
                .getListByModuleId(moduleJsonToList.stream().map(ModuleModel::getId).collect(Collectors.toList()));
        List<ColumnModel> columnJsonToList = JsonUtil.getJsonToList(columnByModuleId, ColumnModel.class);
        columnList.addAll(columnJsonToList);
        columnList = columnList.stream().distinct().collect(Collectors.toList());
        // 表单
        List<ModuleFormModel> formsList = authorizeModel.getFormsList();
        List<ModuleFormEntity> formByModuleId = formApi
                .getListByModuleId(moduleJsonToList.stream().map(ModuleModel::getId).collect(Collectors.toList()));
        List<ModuleFormModel> formJsonToList = JsonUtil.getJsonToList(formByModuleId, ModuleFormModel.class);
        formsList.addAll(formJsonToList);
        formsList = formsList.stream().distinct().collect(Collectors.toList());
        // 数据
        List<ResourceModel> resourceList = authorizeModel.getResourceList();
        List<ModuleDataAuthorizeSchemeEntity> resourceByModuleId = dataAuthorizeSchemeApi
                .getListByModuleId(moduleJsonToList.stream().map(ModuleModel::getId).collect(Collectors.toList()));
        List<ResourceModel> resourceJsonToList = JsonUtil.getJsonToList(resourceByModuleId, ResourceModel.class);
        resourceList.addAll(resourceJsonToList);
        resourceList = resourceList.stream().distinct().collect(Collectors.toList());
        authorizeModel.setButtonList(buttonList);
        authorizeModel.setColumnList(columnList);
        authorizeModel.setFormsList(formsList);
        authorizeModel.setResourceList(resourceList);
        for (ModuleModel moduleModel : menuList) {
            PermissionModel model = new PermissionModel();
            model.setModelId(moduleModel.getId());
            model.setModuleName(moduleModel.getFullName());

            List<ButtonModel> buttonModels = authorizeModel.getButtonList().stream()
                    .filter(t -> moduleModel.getId().equals(t.getModuleId())).collect(Collectors.toList());
            List<ColumnModel> columnModels = authorizeModel.getColumnList().stream()
                    .filter(t -> moduleModel.getId().equals(t.getModuleId())).collect(Collectors.toList());
            List<ResourceModel> resourceModels = authorizeModel.getResourceList().stream()
                    .filter(t -> moduleModel.getId().equals(t.getModuleId())).collect(Collectors.toList());
            List<ModuleFormModel> moduleFormModels = authorizeModel.getFormsList().stream()
                    .filter(t -> moduleModel.getId().equals(t.getModuleId())).collect(Collectors.toList());
            model.setButton(JsonUtil.getJsonToList(buttonModels, PermissionVO.class));
            model.setColumn(JsonUtil.getJsonToList(columnModels, PermissionVO.class));
            model.setResource(JsonUtil.getJsonToList(resourceModels, PermissionVO.class));
            model.setForm(JsonUtil.getJsonToList(moduleFormModels, PermissionVO.class));
            if (moduleModel.getType() != 1) {
                models.add(model);
            }
        }
        // 岗位
        List<UserRelationEntity> relationList = userRelationApi.getListByUserId(userEntity.getId(),
                PermissionConst.POSITION);
        List<String> positionIds = relationList.stream().map(UserRelationEntity::getObjectId)
                .collect(Collectors.toList());
        List<PositionEntity> positionName = positionApi.getPositionName(positionIds, false).stream()
                .filter(t -> t.getEnabledMark() != null && t.getEnabledMark() == 1).collect(Collectors.toList());
        List<UserPositionVO> positionIdVO = new ArrayList<>();
        positionName.forEach(t -> {
            if (!t.getOrganizeId().equals(userEntity.getOrganizeId())) {
                return;
            }
            UserPositionVO userPositionVO = new UserPositionVO();
            userPositionVO.setId(t.getId());
            userPositionVO.setName(t.getFullName());
            positionIdVO.add(userPositionVO);
        });
        infoVO.setPositionIds(positionIdVO);
        PositionEntity positionEntity = positionName.stream().filter(t -> t.getId().equals(userEntity.getPositionId()))
                .findFirst().orElse(null);
        infoVO.setPositionId(positionEntity != null ? positionEntity.getId() : "");
        infoVO.setPositionName(positionEntity != null ? positionEntity.getFullName() : "");
        // 获取签名信息
        SignEntity signEntity = signService.getDefaultByUserId(userEntity.getId());
        infoVO.setSignImg(signEntity != null ? signEntity.getSignImg() : "");
        infoVO.setSignId(signEntity != null ? signEntity.getId() : "");

        SystemInfo jsonToBean = JsonUtil.getJsonToBean(baseSystemInfo, SystemInfo.class);
        jsonToBean.setYunzhupaasDomain(configValueUtil.getApiDomain());

        // 构建菜单树
        if (StringUtil.isNotEmpty(systemCode)) {
            systemList = systemList.stream().filter(t -> systemCode.equals(t.getEnCode())).collect(Collectors.toList());
            moduleList1 = moduleList1.stream().filter(t -> systemCodeEntity.getId().equals(t.getSystemId()))
                    .collect(Collectors.toList());
        }
        List<AllMenuSelectVO> menuSelectVOS = buildModule(systemList, moduleList1, type, userEntity, infoVO, systemCode,
                baseSystemInfo);
        List<AllMenuSelectVO> children = new ArrayList<>();
        AllMenuSelectVO allMenuSelectVO = null;
        if ("App".equals(type)) {
            allMenuSelectVO = menuSelectVOS.stream().filter(t -> userEntity.getAppSystemId().equals(t.getId()))
                    .findFirst().orElse(null);
        } else {
            if (StringUtil.isNotEmpty(systemCode)) {
                allMenuSelectVO = menuSelectVOS.stream().filter(t -> systemCode.equals(t.getEnCode())).findFirst()
                        .orElse(null);
            } else {
                allMenuSelectVO = menuSelectVOS.stream().filter(t -> userEntity.getSystemId().equals(t.getId()))
                        .findFirst().orElse(null);
            }
        }
        if (allMenuSelectVO != null && allMenuSelectVO.getChildren() != null) {
            children = allMenuSelectVO.getChildren();
            children.forEach(t -> t.setParentId("-1"));
        }
        if ("App".equals(type)) {
            infoVO.setAppSystemId(userEntity.getAppSystemId());
            userInfo.setAppSystemId(userEntity.getAppSystemId());
        } else {
            userInfo.setSystemId(userEntity.getSystemId());
            if (StringUtil.isNotEmpty(systemCode)) {
                infoVO.setSystemId(systemCodeEntity.getId());
            } else {
                infoVO.setSystemId(userEntity.getSystemId());
            }
        }
        if (BooleanUtil.toBoolean(String.valueOf((userEntity.getIsAdministrator())))) {
            standingList.add(1);
        }
        Integer min = standingList.stream().min(Integer::compareTo).get();
        if (ADMIN_KEY.equals(userInfo.getUserAccount())) {
            standingList = new ArrayList<>();
        }
        // 设置身份模型
        List<UserSystemVO> standingListVO = new ArrayList<>();
        standingList.forEach(t -> {
            UserSystemVO standingVO = new UserSystemVO();
            standingVO.setId(t + "");
            String name = "";
            if (Objects.equals(t, 1)) {
                name = MsgCode.OA025.get();
            } else if (Objects.equals(t, 2)) {
                name = MsgCode.OA026.get();
            } else if (Objects.equals(t, 3)) {
                name = MsgCode.OA027.get();
            }
            standingVO.setName(name);
            Integer stand = "Web".equals(type) ? userEntity.getStanding() : userEntity.getAppStanding();
            standingVO.setCurrentStanding(
                    ObjectUtil.isNotEmpty(stand) ? Objects.equals(stand, t) : Objects.equals(t, min));
            standingListVO.add(standingVO);
        });
        infoVO.setStandingList(standingListVO);

        // 设置系统模型
        List<UserSystemVO> jsonToList1 = new ArrayList<>();
        systemList.forEach(t -> {
            UserSystemVO systemVO = new UserSystemVO();
            systemVO.setId(t.getId());
            systemVO.setName(t.getFullName());
            systemVO.setIcon(t.getIcon());
            if ("App".equals(type) && userInfo.getAppSystemId().equals(t.getId())) {
                systemVO.setCurrentSystem(true);
            } else if ("Web".equals(type) && userInfo.getSystemId().equals(t.getId())) {
                systemVO.setCurrentSystem(true);
            }
            systemVO.setEnCode(t.getEnCode());
            jsonToList1.add(systemVO);
        });
        infoVO.setSystemIds(jsonToList1);
        userInfo.setSystemIds(systemList.stream().map(SystemBaeModel::getId).collect(Collectors.toList()));
        SystemBaeModel systemBaeModel = systemList.stream().filter(t -> userInfo.getSystemId().equals(t.getId()))
                .findFirst().orElse(null);
        if (systemBaeModel != null
        // && systemEntity.getIsMain() != null && systemEntity.getIsMain() != 1
        ) {
            if (StringUtil.isNotEmpty(systemBaeModel.getNavigationIcon())) {
                jsonToBean.setNavigationIcon(systemBaeModel.getNavigationIcon());
            }
        }
        PcUserVO userVO = new PcUserVO(children, models, infoVO, jsonToBean);
        // userVO.setMenuList(menuList);
        // userVO.setPermissionList(models);
        userVO.getUserInfo().setHeadIcon(UploaderUtil.uploaderImg(userInfo.getUserIcon()));
        // 更新userInfo对象
        if (StringUtil.isNotEmpty(userInfo.getId())) {
            UserProvider.setLoginUser(userInfo);
            UserProvider.setLocalLoginUser(userInfo);
        }
        // 门户Web
        try {
            String defaultPortalId = portalDataService.getCurrentDefault(PortalConst.WEB);
            infoVO.setPortalId(defaultPortalId);
        } catch (Exception e) {
            infoVO.setPortalId("");
            e.printStackTrace();
        }
        // 门户App
        try {
            String defaultAppPortalId = portalDataService.getCurrentDefault(PortalConst.APP);
            infoVO.setAppPortalId(defaultAppPortalId);
        } catch (Exception e) {
            infoVO.setAppPortalId("");
            e.printStackTrace();
        }

        // 初始化接口权限
        if (securityProperties.isEnablePreAuth()) {
            // 清空旧权限
            String account = userInfo.getIsAdministrator() ? ADMIN_KEY : userInfo.getUserId();
            PermissionInterfaceImpl.setAuthorityList(account, Collections.EMPTY_SET, null);
            PermissionInterfaceImpl.setRoleList(account, Collections.EMPTY_SET, null);
            // 如需使用远程事件, 改用publish
            PublishEventUtil.publishLocalEvent(
                    new ProjectEventBuilder(EventConst.EVENT_INIT_LOGIN_PERMISSION, authorizeModel).setAsync(false));
        }
        return userVO;
    }

    @Override
    public BaseSystemInfo getBaseSystemConfig(String tenantId) {
        if (tenantId != null) {
            TenantDataSourceUtil.switchTenant(tenantId);
        }
        return sysconfigApi.getSysInfo();
    }

    private List<AllMenuSelectVO> buildModule(List<SystemBaeModel> systemList, List<ModuleModel> moduleList,
            String type, UserEntity entity, UserCommonInfoVO infoVO, String systemCode, BaseSystemInfo baseSystemInfo) {
        boolean enabledFow = false;
        if (configValueUtil.isMultiTenancy()) {
            TenantAuthorizeModel tenantAuthorizeModel = TenantDataSourceUtil
                    .getCacheModuleAuthorize(UserProvider.getUser().getTenantId());
            List<String> cacheModuleAuthorize = tenantAuthorizeModel.getModuleIdList();
            if (cacheModuleAuthorize != null) {
                enabledFow = !cacheModuleAuthorize.contains("-999");
            }
        } else {
            enabledFow = true;
        }
        // 获取所有菜单树（区分Web、APP）
        moduleList = moduleList.stream().filter(t -> type.equals(t.getCategory()))
                .sorted(Comparator.comparing(ModuleModel::getSortCode)).collect(Collectors.toList());
        String systemId = "Web".equals(type) ? entity.getSystemId() : entity.getAppSystemId();
        int stand = "Web".equals(type) ? entity.getStanding() : entity.getAppStanding();
        boolean isAddModuleCode = true;
        if (Objects.equals(stand, 2)) {
            List<OrganizeAdministratorEntity> organizeAdministratorEntity = organizeAdminTratorApi
                    .getOrganizeAdministratorEntity(entity.getId(), null);
            List<String> list = ImmutableList.of(PermissionConst.MODULE, PermissionConst.SYSTEM);
            isAddModuleCode = organizeAdministratorEntity.stream().filter(t -> list.contains(t.getOrganizeType()))
                    .count() > 0;
        }
        List<String> moduleCode = new ArrayList<>(YunzhupaasConst.MODULE_CODE);
        if (!Objects.equals(baseSystemInfo.getFlowSign(), 1)) {
            moduleCode.remove(YunzhupaasConst.WORK_FLOWSIGN);
        }
        if (!Objects.equals(baseSystemInfo.getFlowTodo(), 1)) {
            moduleCode.remove(YunzhupaasConst.WORK_FLOWTODO);
        }
        if (isAddModuleCode) {
            List<ModuleEntity> listByEnCode = moduleApi.getListByEnCode(moduleCode);
            SystemBaeModel systemBaeModel = systemList.stream().filter(t -> t.getId().equals(systemId)).findFirst()
                    .orElse(null);
            // 当前有协同，无需切换，直接放入协同菜单
            if (systemBaeModel != null && (enabledFow && Objects.equals(systemBaeModel.getWorkflowEnabled(), 1))) {
                List<ModuleModel> jsonToList = JsonUtil.getJsonToList(listByEnCode, ModuleModel.class);
                jsonToList.forEach(t -> {
                    if ("-1".equals(t.getParentId())) {
                        t.setSortCode(-999L);
                        t.setParentId(systemId);
                    }
                });
                moduleList.addAll(jsonToList);
                infoVO.setWorkflowEnabled(1);
            } else if (systemBaeModel == null || !enabledFow || (Objects.equals(systemBaeModel.getWorkflowEnabled(), 0)
                    && moduleList.stream().noneMatch(t -> t.getSystemId().equals(systemId)))) {
                // 当前无协同，需切换，优先找开启协同的
                String currentSystemId = "";
                if (moduleList.stream().filter(t -> t.getSystemId().equals(systemId)).count() == 0) {
                    for (SystemBaeModel baeModel : systemList) {
                        if (Objects.equals(baeModel.getWorkflowEnabled(), 1)) {
                            currentSystemId = baeModel.getId();
                            break;
                        }
                    }
                    if (StringUtil.isNotEmpty(currentSystemId) && enabledFow) {
                        List<ModuleModel> jsonToList = JsonUtil.getJsonToList(listByEnCode, ModuleModel.class);
                        String finalCurrentSystemId = currentSystemId;
                        jsonToList.forEach(t -> {
                            if ("-1".equals(t.getParentId())) {
                                t.setSortCode(-999L);
                                t.setParentId(finalCurrentSystemId);
                            }
                        });
                        moduleList.addAll(jsonToList);
                        infoVO.setWorkflowEnabled(1);
                    }
                    // 都未开启协同，找有菜单的
                    if (infoVO.getWorkflowEnabled() == 0 && moduleList.size() > 0) {
                        currentSystemId = moduleList.get(0).getSystemId();
                    }
                    UserEntity user = new UserEntity();
                    user.setId(entity.getId());
                    if ("Web".equals(type)) {
                        entity.setSystemId(currentSystemId);
                        user.setSystemId(currentSystemId);
                    } else {
                        entity.setAppSystemId(currentSystemId);
                        user.setAppSystemId(currentSystemId);
                    }
                    if (StringUtil.isEmpty(systemCode)) {
                        userApi.updateById(user);
                    }
                }
            }
        }

        moduleList = moduleList.stream().sorted(Comparator.comparing(ModuleModel::getSortCode))
                .collect(Collectors.toList());
        List<AllUserMenuModel> list = JsonUtil.getJsonToList(moduleList, AllUserMenuModel.class);
        list.forEach(t -> {
            if ("-1".equals(t.getParentId())) {
                t.setParentId(t.getSystemId());
            }
        });
        List<AllUserMenuModel> jsonToList = JsonUtil.getJsonToList(systemList, AllUserMenuModel.class);
        jsonToList.forEach(t -> {
            t.setType(0);
            t.setParentId("-1");
        });
        list.addAll(jsonToList);
        List<SumTree<AllUserMenuModel>> menuList = TreeDotUtils.convertListToTreeDotFilter(list);
        List<AllMenuSelectVO> menuvo = JsonUtil.getJsonToList(menuList, AllMenuSelectVO.class);
        return menuvo;
    }

    /**
     * 获取下属机构
     *
     * @param data
     * @param organizeId
     * @param isAdmin
     * @return
     */
    private String[] getSubOrganizeIds(List<OrganizeEntity> data, String organizeId, boolean isAdmin) {
        if (!isAdmin) {
            data = JsonUtil.getJsonToList(ListToTreeUtil.treeWhere(organizeId, data), OrganizeEntity.class);
        }
        return data.stream().map(SuperBaseEntity.SuperIBaseEntity::getId).toArray(String[]::new);
    }

    /**
     * 赋值
     *
     * @param userInfo
     * @param userId
     * @param isAdmin
     */
    private void userInfo(UserInfo userInfo, String userId, boolean isAdmin, UserEntity userEntity, String systemId) {
        // 得到用户和组织的关系
        List<UserRelationEntity> data = userRelationApi.getListByUserIdAndObjType(userId, PermissionConst.ORGANIZE);
        // 组织id
        String organizeId = "";
        String departmentId = "";
        List<String> roleId = new ArrayList<>();
        // 判断当前组织是否有权限
        if (organizeRelationApi.checkBasePermission(userEntity.getId(), userEntity.getOrganizeId(), systemId)
                .size() == 0) {
            if (!data.isEmpty()) {
                // 得到组织id
                organizeId = organizeRelationApi.autoGetMajorOrganizeId(userId,
                        data.stream().map(UserRelationEntity::getObjectId).collect(Collectors.toList()),
                        userEntity.getOrganizeId(), systemId);
            }
        } else {
            // 如果有权限
            organizeId = userEntity.getOrganizeId();
            // if (isAdmin) {
            // roleId = data.stream().map(t ->
            // t.getObjectId()).collect(Collectors.toList());
            // }
        }
        // 获取用户的角色
        List<UserRelationEntity> listByObjectId = userRelationApi.getListByUserId(userInfo.getUserId(),
                PermissionConst.ROLE);
        // 判断哪个角色是当前组织下的
        List<String> collect = listByObjectId.stream().filter(t -> StringUtil.isNotEmpty(t.getObjectId()))
                .map(UserRelationEntity::getObjectId).collect(Collectors.toList());
        // 如果有全局的角色则先赋值给权限集合
        for (String roleIds : collect) {
            // 得到角色
            RoleEntity info = roleApi.getInfo(roleIds);
            if (info != null && "1".equals(String.valueOf(info.getGlobalMark()))) {
                roleId.add(info.getId());
                continue;
            }
            // 判断哪些角色是当前组织的
            Boolean exist = organizeRelationApi.existByRoleIdAndOrgId(roleIds, organizeId);
            if (exist) {
                roleId.add(roleIds);
            }
        }
        // 获取分组
        List<UserRelationEntity> groupRelationByUserId = userRelationApi.getListByUserId(userInfo.getUserId(),
                PermissionConst.GROUP);
        List<String> groupIds = groupRelationByUserId.stream().map(UserRelationEntity::getObjectId)
                .collect(Collectors.toList());
        List<GroupEntity> groupName = groupApi.getListByIds(groupIds, true);
        userInfo.setGroupIds(groupName.stream().map(GroupEntity::getId).collect(Collectors.toList()));
        userInfo.setGroupNames(groupName.stream().map(GroupEntity::getFullName).collect(Collectors.toList()));
        // // 赋值岗位
        // List<String> positionList = data.stream().filter(m ->
        // "Position".equals(m.getObjectType())).map(t ->
        // t.getObjectId()).collect(Collectors.toList());
        // Set<String> id = new LinkedHashSet<>();
        // String[] position = StringUtil.isNotEmpty(userEntity.getPositionId()) ?
        // userEntity.getPositionId().split(",") : new String[]{};
        // List<String> positions = positionList.stream().filter(t ->
        // Arrays.asList(position).contains(t)).collect(Collectors.toList());
        // id.addAll(positions);
        // id.addAll(positionList);
        // String[] positionId = id.toArray(new String[id.size()]);
        // 部门处理
        OrganizeEntity info = organizeApi.getInfo(organizeId);
        if (info != null && Objects.equals(info.getCategory(), PermissionConst.DEPARTMENT)) {
            departmentId = organizeId;
        }
        userInfo.setOrganizeId(organizeId);
        userInfo.setDepartmentId(departmentId);
        userInfo.setRoleIds(roleId);
        userInfo.setPositionIds(new String[] { userEntity.getPositionId() });
        // 处理userInfo
        userInfo.setSystemId(userEntity.getSystemId());
        userInfo.setAppSystemId(userEntity.getAppSystemId());
        // 修改用户信息
        userEntity.setOrganizeId(organizeId);
        userEntity.setPositionId(
                organizeRelationApi.autoGetMajorPositionId(userId, organizeId, userEntity.getPositionId()));
        userApi.updateById(userEntity);
    }

    /**
     * 登录信息
     *
     * @param userInfo   回话信息
     * @param systemInfo 系统信息
     * @return
     */
    private Map<String, Object> genUserInfo(UserInfo userInfo, BaseSystemInfo systemInfo) {
        Map<String, Object> dictionary = new HashMap<>(16);
        dictionary.put("userId", userInfo.getUserId());
        dictionary.put("userAccount", userInfo.getUserAccount());
        dictionary.put("userName", userInfo.getUserName());
        dictionary.put("icon", userInfo.getUserIcon());
        dictionary.put("portalId", userInfo.getPortalId());
        dictionary.put("gender", userInfo.getUserGender());
        dictionary.put("organizeId", userInfo.getOrganizeId());
        dictionary.put("prevLogin", systemInfo.getLastLoginTimeSwitch() == 1 ? 1 : 0);
        dictionary.put("prevLoginTime", userInfo.getPrevLoginTime());
        dictionary.put("prevLoginIPAddress", userInfo.getPrevLoginIpAddress());
        dictionary.put("prevLoginIPAddressName", userInfo.getPrevLoginIpAddressName());
        dictionary.put("serviceDirectory", configValueUtil.getServiceDirectoryPath());
        dictionary.put("webDirectory", configValueUtil.getCodeAreasName());
        dictionary.put("isAdministrator", userInfo.getIsAdministrator());
        return dictionary;
    }

}
