package com.yunzhupaas.permission.service.impl;

import cn.hutool.core.text.StrPool;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.dynamic.datasource.annotation.DSTransactional;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
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.portalManage.PortalManagePageDO;
import com.yunzhupaas.base.model.portalManage.PortalModel;
import com.yunzhupaas.base.model.portalManage.SavePortalAuthModel;
import com.yunzhupaas.base.model.resource.ResourceModel;
import com.yunzhupaas.base.service.*;
import com.yunzhupaas.config.ConfigValueUtil;
import com.yunzhupaas.constant.YunzhupaasConst;
import com.yunzhupaas.constant.MsgCode;
import com.yunzhupaas.constant.PermissionConst;
import com.yunzhupaas.consts.DeviceType;
import com.yunzhupaas.database.model.dto.PrepSqlDTO;
import com.yunzhupaas.database.model.superQuery.SuperJsonModel;
import com.yunzhupaas.database.model.superQuery.SuperQueryJsonModel;
import com.yunzhupaas.database.sql.util.SqlFrameFastUtil;
import com.yunzhupaas.database.util.DataSourceUtil;
import com.yunzhupaas.database.util.DbTypeUtil;
import com.yunzhupaas.database.util.JdbcUtil;
import com.yunzhupaas.database.util.TenantDataSourceUtil;
import com.yunzhupaas.emnus.SearchMethodEnum;
import com.yunzhupaas.model.login.UserSystemVO;
import com.yunzhupaas.model.tenant.TenantAuthorizeModel;
import com.yunzhupaas.model.visualJson.FieLdsModel;
import com.yunzhupaas.model.visualJson.config.ConfigModel;
import com.yunzhupaas.permission.constant.AuthorizeConst;
import com.yunzhupaas.permission.entity.AuthorizeEntity;
import com.yunzhupaas.permission.entity.OrganizeAdministratorEntity;
import com.yunzhupaas.permission.entity.UserEntity;
import com.yunzhupaas.permission.entity.UserRelationEntity;
import com.yunzhupaas.permission.mapper.AuthorizeMapper;
import com.yunzhupaas.permission.model.authorize.*;
import com.yunzhupaas.permission.service.*;
import com.yunzhupaas.util.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

/**
 * 操作权限
 *
 * @author 云筑产品开发平台组
 * @version V3.1.0
 * @copyright 深圳市乐程软件有限公司
 * @date 2024-09-26 上午9:18
 */
@Slf4j
@Service
public class AuthorizeServiceImpl extends SuperServiceImpl<AuthorizeMapper, AuthorizeEntity>
        implements AuthorizeService {

    @Autowired
    private UserRelationService userRelationService;
    @Autowired
    private DataSourceUtil dataSourceUtils;
    @Autowired
    private CacheKeyUtil cacheKeyUtil;
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private UserService userService;
    @Autowired
    private OrganizeService organizeService;
    @Autowired
    private OrganizeAdministratorService organizeAdminIsTratorService;
    @Autowired
    private SystemService systemApi;
    @Autowired
    private ConfigValueUtil configValueUtil;
    @Autowired
    private PermissionGroupService permissionGroupService;
    @Autowired
    private ModuleService moduleApi;
    @Autowired
    private ModuleButtonService buttonApi;
    @Autowired
    private ModuleColumnService columnApi;
    @Autowired
    private ModuleFormService formApi;
    @Autowired
    private ModuleDataAuthorizeSchemeService dataAuthorizeSchemeApi;
    @Autowired
    private PortalManageService portalManageApi;

    @Override
    public AuthorizeVO getAuthorize(boolean isCache, boolean singletonOrg) {
        return getAuthorize(isCache, singletonOrg, false);
    }

    @Override
    public AuthorizeVO getAuthorize(boolean isCache, boolean singletonOrg, boolean isMainSystem) {
        UserInfo userInfo = UserProvider.getUser();
        List<UserSystemVO> standingAll = getUserStanding(false, userInfo.getUserId());
        boolean isAdmin = standingAll.stream().filter(t -> "1".equals(t.getId()) || "2".equals(t.getId())).count() > 0;
        List<UserSystemVO> userStanding = standingAll.stream().filter(t -> "2".equals(t.getId()))
                .collect(Collectors.toList());
        int stand = isAdmin ? 1 : userStanding.size() > 0 ? 2 : 3;
        return getAuthorize(userInfo, singletonOrg, stand, isMainSystem);
    }

    @Override
    public void getPortal(List<SystemEntity> systemList, List<PortalModel> portalList, Long dateTime,
            List<String> collect) {
        Map<String, SystemEntity> systemBaeModelMap = systemList.stream()
                .collect(Collectors.toMap(SystemEntity::getId, Function.identity()));
        List<String> systemIds = systemList.stream().map(SystemEntity::getId).collect(Collectors.toList());
        List<PortalManagePageDO> portalManagePageDOS = portalManageApi.selectPortalBySystemIds(systemIds, collect);
        if (portalManagePageDOS.size() == 0) {
            return;
        }
        Map<String, List<PortalManagePageDO>> systemIdAndPortalMap = portalManagePageDOS.stream()
                .collect(Collectors.groupingBy(PortalManagePageDO::getSystemId));
        if (systemIdAndPortalMap != null) {
            systemIdAndPortalMap.keySet().forEach(t -> {
                if (Optional.ofNullable(systemBaeModelMap.get(t)).isPresent()) {
                    PortalModel systemModel = JsonUtil.getJsonToBean(systemBaeModelMap.get(t), PortalModel.class);
                    systemModel.setParentId("-1");
                    portalList.add(systemModel);
                    Map<String, String> platFormId = new HashMap<>();
                    List<PortalManagePageDO> portalManagePageDOList = systemIdAndPortalMap.get(t);
                    Map<String, List<PortalManagePageDO>> platFormMap = portalManagePageDOList.stream()
                            .collect(Collectors.groupingBy(PortalManagePageDO::getPlatform));
                    List<PortalManagePageDO> web = platFormMap.get("Web");
                    List<PortalManagePageDO> app = platFormMap.get("App");
                    if (web != null && web.size() > 0) {
                        PortalModel platForm = new PortalModel();
                        platForm.setId(systemModel.getId() + "1");
                        platForm.setParentId(systemModel.getId());
                        platForm.setFullName("WEB门户");
                        platForm.setIcon("icon-ym icon-ym-pc");
                        platForm.setSortCode(0L);
                        platForm.setCreatorTime(dateTime);
                        platFormId.put("Web", platForm.getId());
                        portalList.add(platForm);
                    }
                    if (app != null && app.size() > 0) {
                        PortalModel platForm = new PortalModel();
                        platForm.setId(systemModel.getId() + "2");
                        platForm.setParentId(systemModel.getId());
                        platForm.setFullName("APP门户");
                        platForm.setIcon("icon-ym icon-ym-mobile");
                        platForm.setSortCode(0L);
                        platForm.setCreatorTime(dateTime);
                        platFormId.put("App", platForm.getId());
                        portalList.add(platForm);
                    }
                    portalManagePageDOList.forEach(pageDO -> {
                        // if (!categoryList.contains(pageDO.getCategoryId())) {
                        // categoryList.add(pageDO.getCategoryId());
                        // PortalModel categoryModel = new PortalModel();
                        // categoryModel.setId(pageDO.getCategoryId());
                        // categoryModel.setParentId(platFormId.get(pageDO.getPlatform()));
                        // categoryModel.setFullName(pageDO.getCategoryName());
                        // categoryModel.setOnlyId(RandomUtil.uuId());
                        // list.add(categoryModel);
                        // }
                        PortalModel model = JsonUtil.getJsonToBean(pageDO, PortalModel.class);
                        // model.setParentId(pageDO.getCategoryId());
                        model.setParentId(platFormId.get(pageDO.getPlatform()));
                        model.setFullName(pageDO.getPortalName());
                        portalList.add(model);
                    });
                }
            });
        }
    }

    @Override
    @DSTransactional
    public void saveItemAuth(SavePortalAuthModel portalAuthModel) {
        List<String> ids = portalAuthModel.getIds();
        String id = portalAuthModel.getId();
        String type = portalAuthModel.getType();
        String userId = UserProvider.getLoginUserId();
        // 原始授权角色
        List<AuthorizeEntity> list = new ArrayList<>();
        for (int i = 0; i < ids.size(); i++) {
            AuthorizeEntity authorizeEntity = new AuthorizeEntity();
            authorizeEntity.setId(RandomUtil.uuId());
            authorizeEntity.setItemType(type);
            authorizeEntity.setItemId(ids.get(i));
            authorizeEntity.setObjectType(AuthorizeConst.ROLE);
            authorizeEntity.setObjectId(id);
            authorizeEntity.setSortCode((long) i);
            authorizeEntity.setCreatorTime(new Date());
            authorizeEntity.setCreatorUserId(userId);
            list.add(authorizeEntity);
        }
        QueryWrapper<AuthorizeEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(AuthorizeEntity::getItemType, type);
        queryWrapper.lambda().eq(AuthorizeEntity::getObjectId, id);
        this.remove(queryWrapper);
        list.forEach(this::save);
    }

    @Override
    @DSTransactional
    public void saveObjectAuth(SavePortalAuthModel portalAuthModel) {
        List<String> ids = portalAuthModel.getIds();
        String id = portalAuthModel.getId();
        String type = portalAuthModel.getType();
        String userId = UserProvider.getLoginUserId();
        QueryWrapper<AuthorizeEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(AuthorizeEntity::getItemType, type);
        queryWrapper.lambda().eq(AuthorizeEntity::getItemId, id);
        this.remove(queryWrapper);

        List<AuthorizeEntity> portalSystem = new ArrayList<>();
        boolean isPortal = AuthorizeConst.AUTHORIZE_PORTAL_MANAGE.equals(type);
        if (isPortal && !ids.isEmpty() && StringUtil.isNotEmpty(portalAuthModel.getSystemId())) {
            QueryWrapper<AuthorizeEntity> wrapper = new QueryWrapper<>();
            wrapper.lambda().eq(AuthorizeEntity::getItemType, AuthorizeConst.SYSTEM);
            wrapper.lambda().eq(AuthorizeEntity::getItemId, portalAuthModel.getSystemId());
            wrapper.lambda().in(AuthorizeEntity::getObjectId, ids);
            portalSystem.addAll(this.list(wrapper));
        }
        // 原始授权角色
        List<AuthorizeEntity> list = new ArrayList<>();
        for (int i = 0; i < ids.size(); i++) {
            String objectId = ids.get(i);
            AuthorizeEntity authorizeEntity = new AuthorizeEntity();
            authorizeEntity.setId(RandomUtil.uuId());
            authorizeEntity.setItemType(type);
            authorizeEntity.setObjectId(objectId);
            authorizeEntity.setObjectType(AuthorizeConst.ROLE);
            authorizeEntity.setItemId(id);
            authorizeEntity.setSortCode((long) i);
            authorizeEntity.setCreatorTime(new Date());
            authorizeEntity.setCreatorUserId(userId);
            list.add(authorizeEntity);
            if (isPortal && StringUtil.isNotEmpty(portalAuthModel.getSystemId())) {
                boolean portalCount = portalSystem.stream().filter(t -> Objects.equals(t.getObjectId(), objectId))
                        .count() == 0;
                if (portalCount) {
                    AuthorizeEntity systemAuthorize = new AuthorizeEntity();
                    systemAuthorize.setId(RandomUtil.uuId());
                    systemAuthorize.setItemType(AuthorizeConst.SYSTEM);
                    systemAuthorize.setObjectId(ids.get(i));
                    systemAuthorize.setObjectType(AuthorizeConst.ROLE);
                    systemAuthorize.setItemId(portalAuthModel.getSystemId());
                    systemAuthorize.setSortCode(0l);
                    systemAuthorize.setCreatorTime(new Date());
                    systemAuthorize.setCreatorUserId(userId);
                    list.add(systemAuthorize);
                }
            }
        }
        list.forEach(this::save);
    }

    @Override
    public List<AuthorizeEntity> getAuthorizeByItem(String itemType, String itemId) {
        QueryWrapper<AuthorizeEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(AuthorizeEntity::getItemType, itemType);
        queryWrapper.lambda().eq(AuthorizeEntity::getItemId, itemId);
        return this.list(queryWrapper);
    }

    @Override
    public AuthorizeVO getAuthorizeByUser(boolean singletonOrg) {
        AuthorizeVO authorizeModel = this.getAuthorize(false, singletonOrg);
        return authorizeModel;
    }

    @Override
    public AuthorizeVO getMainSystemAuthorize(List<String> moduleIds, List<String> moduleAuthorize,
            List<String> moduleUrlAddressAuthorize, boolean singletonOrg) {
        SystemEntity systemEntity = systemApi.getInfoByEnCode(YunzhupaasConst.MAIN_SYSTEM_CODE);
        if (systemEntity == null || moduleAuthorize.contains(systemEntity.getId())) {
            return new AuthorizeVO();
        }
        SystemBaeModel systemBaeModel = JsonUtil.getJsonToBean(systemEntity, SystemBaeModel.class);
        List<ModuleEntity> moduleList = new ArrayList<>();
        if (moduleIds.size() > 0) {
            moduleList = moduleApi.getModuleByIds(moduleIds, moduleAuthorize, moduleUrlAddressAuthorize, singletonOrg);
        } else {
            moduleList = moduleApi.getMainModule(moduleAuthorize, moduleUrlAddressAuthorize, singletonOrg);
        }
        List<ModuleModel> moduleModelList = JsonUtil.getJsonToList(moduleList, ModuleModel.class);
        List<ModuleButtonEntity> buttonByModuleId = buttonApi
                .getListByModuleIds(moduleModelList.stream().map(ModuleModel::getId).collect(Collectors.toList()));
        List<ButtonModel> buttonJsonToList = JsonUtil.getJsonToList(buttonByModuleId, ButtonModel.class);

        List<ModuleColumnEntity> columnByModuleId = columnApi
                .getListByModuleId(moduleModelList.stream().map(ModuleModel::getId).collect(Collectors.toList()));
        List<ColumnModel> columnJsonToList = JsonUtil.getJsonToList(columnByModuleId, ColumnModel.class);

        List<ModuleDataAuthorizeSchemeEntity> resourceByModuleId = dataAuthorizeSchemeApi
                .getListByModuleId(moduleModelList.stream().map(ModuleModel::getId).collect(Collectors.toList()));
        List<ResourceModel> resourceJsonToList = JsonUtil.getJsonToList(resourceByModuleId, ResourceModel.class);

        List<ModuleFormEntity> formByModuleId = formApi
                .getListByModuleId(moduleModelList.stream().map(ModuleModel::getId).collect(Collectors.toList()));
        List<ModuleFormModel> formJsonToList = JsonUtil.getJsonToList(formByModuleId, ModuleFormModel.class);

        return new AuthorizeVO(moduleModelList, buttonJsonToList, columnJsonToList, resourceJsonToList, formJsonToList,
                Collections.singletonList(systemBaeModel));
    }

    @Override
    public List<AuthorizeEntity> getListByRoleIdsAndItemType(List<String> roleIds, String itemType) {
        if (roleIds.size() == 0) {
            return Collections.EMPTY_LIST;
        }
        QueryWrapper<AuthorizeEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(AuthorizeEntity::getItemType, itemType);
        queryWrapper.lambda().in(AuthorizeEntity::getObjectId, roleIds);
        return this.list(queryWrapper);
    }

    @Override
    public void save(String objectId, AuthorizeDataUpForm authorizeList) {
        SaveBatchForm form = JsonUtil.getJsonToBean(authorizeList, SaveBatchForm.class);
        form.setRoleIds(new String[] { objectId });
        this.saveBatch(form, false);
    }

    @Override
    public void saveBatch(SaveBatchForm saveBatchForm, boolean isBatch) {
        try {
            UserInfo userInfo = UserProvider.getUser();

            List<AuthorizeEntity> objectList = new ArrayList<>();
            List<AuthorizeEntity> authorizeList = new ArrayList<>();
            // 设置权限归属对象
            setEntity(saveBatchForm.getUserIds(), AuthorizeConst.USER, objectList, true);
            setEntity(saveBatchForm.getPositionIds(), AuthorizeConst.POSITION, objectList, true);
            setEntity(saveBatchForm.getRoleIds(), AuthorizeConst.ROLE, objectList, true);
            // setEntity(saveBatchForm.getSystemIds(), AuthorizeConst.SYSTEM, objectList,
            // true);
            // 设置权限模块
            setEntity(saveBatchForm.getButton(), AuthorizeConst.BUTTON, authorizeList, false);
            setEntity(saveBatchForm.getModule(), AuthorizeConst.MODULE, authorizeList, false);
            setEntity(saveBatchForm.getColumn(), AuthorizeConst.COLUMN, authorizeList, false);
            setEntity(saveBatchForm.getResource(), AuthorizeConst.RESOURCE, authorizeList, false);
            setEntity(saveBatchForm.getForm(), AuthorizeConst.FROM, authorizeList, false);
            setEntity(saveBatchForm.getSystemIds(), AuthorizeConst.SYSTEM, authorizeList, false);

            // 移除权限缓存
            this.removeAuthByUserOrMenu(null, Arrays.asList(saveBatchForm.getModule()));

            // 删除角色相关信息
            List<String> objectIdAll = objectList.stream().map(AuthorizeEntity::getObjectId)
                    .collect(Collectors.toList());
            userService.delCurRoleUser(MsgCode.PS010.get(), objectIdAll);
            if (!isBatch) {
                String ids = String.join(",", objectIdAll);
                JdbcUtil.creUpDe(new PrepSqlDTO(
                        XSSEscape.escapeEmpty(SqlFrameFastUtil.AUTHOR_DEL.replace("{authorizeIds}", ids)))
                        .withConn(dataSourceUtils, null));
            }

            // 插入数据
            String sql = DbTypeUtil.checkOracle(dataSourceUtils) || DbTypeUtil.checkPostgre(dataSourceUtils)
                    ? SqlFrameFastUtil.INSERT_AUTHORIZE2
                    : SqlFrameFastUtil.INSERT_AUTHORIZE;

            String column_key = StringUtil.EMPTY, column_plceholder = StringUtil.EMPTY,
                    column_value = TenantDataSourceUtil.getTenantColumn();
            if (StringUtil.isNotEmpty(column_value)) {
                column_key = StrPool.COMMA + configValueUtil.getMultiTenantColumn();
                column_plceholder = ",?";
            }
            sql = sql.replace("%COLUMN_KEY%", column_key).replace("%COLUMN_PLACEHOLDER%", column_plceholder);
            PrepSqlDTO dto = new PrepSqlDTO(sql).withConn(dataSourceUtils, null);
            for (int i = 0; i < objectList.size(); i++) {
                for (AuthorizeEntity entityItem : authorizeList) {
                    List<Object> data = new LinkedList<>();
                    data.add(RandomUtil.uuId());
                    data.add(entityItem.getItemType());
                    data.add(entityItem.getItemId());
                    data.add(objectList.get(i).getObjectType());
                    data.add(objectList.get(i).getObjectId());
                    data.add(i);
                    data.add(DateUtil.getNow());
                    data.add(userInfo.getUserId());
                    if (StringUtil.isNotEmpty(column_value)) {
                        data.add(column_value);
                    }
                    dto.addMultiData(data);
                }
            }
            JdbcUtil.creUpDeBatchOneSql(dto);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("权限报错:" + e.getMessage());
        }
    }

    /**
     * 权限
     */
    private void setEntity(String[] ids, String type, List<AuthorizeEntity> entityList, Boolean objectFlag) {
        if (ids != null) {
            for (String id : ids) {
                AuthorizeEntity entity = new AuthorizeEntity();
                if (objectFlag) {
                    entity.setObjectType(type);
                    entity.setObjectId(id);
                } else {
                    entity.setItemType(type);
                    entity.setItemId(id);
                }
                entityList.add(entity);
            }
        }
    }

    @Override
    public List<AuthorizeEntity> getListByUserId(boolean isAdmin, String userId) {
        if (!isAdmin) {
            QueryWrapper<UserRelationEntity> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().in(UserRelationEntity::getUserId, userId);
            List<UserRelationEntity> list = userRelationService.list(queryWrapper);
            List<String> userRelationList = list.stream().map(u -> u.getObjectId()).collect(Collectors.toList());
            userRelationList.add(userId);
            QueryWrapper<AuthorizeEntity> wrapper = new QueryWrapper<>();
            wrapper.lambda().in(AuthorizeEntity::getObjectId, userRelationList);
            return this.list(wrapper);
        } else {
            return new ArrayList<>();
        }
    }

    @Override
    public List<AuthorizeEntity> getListByObjectId(List<String> objectId) {
        if (objectId.size() == 0) {
            return new ArrayList<>();
        }
        QueryWrapper<AuthorizeEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().in(AuthorizeEntity::getObjectId, objectId);
        return this.list(queryWrapper);
    }

    @Override
    public Boolean existAuthorize(String roleId, String systemId) {
        QueryWrapper<AuthorizeEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(AuthorizeEntity::getObjectId, roleId);
        if (StringUtil.isNotEmpty(systemId)) {
            queryWrapper.lambda().eq(AuthorizeEntity::getItemId, systemId);
            queryWrapper.lambda().eq(AuthorizeEntity::getItemType, AuthorizeConst.SYSTEM);
        }
        return this.count(queryWrapper) > 0;
    }

    @Override
    public List<AuthorizeEntity> getListByRoleId(String roleId) {
        QueryWrapper<AuthorizeEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(AuthorizeEntity::getObjectId, roleId);
        return this.list(queryWrapper);
    }

    @Override
    public List<AuthorizeEntity> getListByObjectId(String objectId, String itemType) {
        QueryWrapper<AuthorizeEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(AuthorizeEntity::getObjectId, objectId);
        queryWrapper.lambda().eq(AuthorizeEntity::getItemType, itemType);
        return this.list(queryWrapper);
    }

    @Override
    public List<AuthorizeEntity> getListByObjectAndItem(String itemId, String objectType) {
        QueryWrapper<AuthorizeEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(AuthorizeEntity::getObjectType, objectType).eq(AuthorizeEntity::getItemId, itemId);
        return this.list(queryWrapper);
    }

    @Override
    public List<AuthorizeEntity> getListByObjectAndItemIdAndType(String itemId, String itemType) {
        QueryWrapper<AuthorizeEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(AuthorizeEntity::getItemType, itemType).eq(AuthorizeEntity::getItemId, itemId);
        return this.list(queryWrapper);
    }

    @Override
    public List<UserSystemVO> getUserStanding(boolean isLogin, String userId) {
        return getUserStanding(isLogin, userId, null);
    }

    @Override
    public List<UserSystemVO> getUserStanding(boolean isLogin, String userId, String loginDevice) {
        UserInfo userInfo = UserProvider.getUser();
        List<UserSystemVO> systemVOS = new ArrayList<>();
        UserEntity info = userService.getInfo(userId);
        String device = StringUtil.isNotEmpty(loginDevice) ? loginDevice : userInfo.getLoginDevice();
        if (DeviceType.PC.getDevice().equals(device)) {
            if (ObjectUtil.isNotEmpty(info.getStanding())) {
                UserSystemVO vo = new UserSystemVO();
                vo.setId(info.getStanding() + "");
                vo.setCurrentStanding(true);
                systemVOS.add(vo);
            }
        } else {
            if (ObjectUtil.isNotEmpty(info.getAppStanding())) {
                UserSystemVO vo = new UserSystemVO();
                vo.setId(info.getAppStanding() + "");
                vo.setCurrentStanding(true);
                systemVOS.add(vo);
            }
        }
        List<OrganizeAdministratorEntity> infoByUserId = organizeAdminIsTratorService.getInfoByUserId(userId);
        if (isLogin) {
            if (infoByUserId.size() > 0) {
                UserSystemVO vo = new UserSystemVO();
                vo.setId("2");
                systemVOS.add(vo);
            }
        } else {
            if (systemVOS.size() == 0) {
                if (Objects.equals(info.getIsAdministrator(), 1)) {
                    UserSystemVO vo = new UserSystemVO();
                    vo.setId("1");
                    systemVOS.add(vo);
                } else if (infoByUserId.size() > 0) {
                    UserSystemVO vo = new UserSystemVO();
                    vo.setId("2");
                    systemVOS.add(vo);
                } else {
                    UserSystemVO vo = new UserSystemVO();
                    vo.setId("3");
                    systemVOS.add(vo);
                }
            }
        }
        return systemVOS;
    }

    @Override
    public AuthorizeVO getAuthorize(UserInfo userInfo, boolean singletonOrg, Integer stand, boolean isMainSystem) {
        List<ModuleModel> moduleList = new ArrayList<>();
        List<ButtonModel> buttonList = new ArrayList<>();
        List<ColumnModel> columnList = new ArrayList<>();
        List<ResourceModel> resourceList = new ArrayList<>();
        List<ModuleFormModel> formsList = new ArrayList<>();
        List<SystemBaeModel> systemList = new ArrayList<>();
        List<OrganizeAdministratorEntity> organizeAdministratorEntity = new ArrayList<>();
        boolean isAdmin = userInfo.getIsAdministrator();
        if (ObjectUtil.isNotEmpty(stand)) {
            isAdmin = Objects.equals(stand, 1);
            if (Objects.equals(stand, 2)) {
                organizeAdministratorEntity.addAll(organizeAdminIsTratorService.getInfoByUserId(userInfo.getUserId()));
            }
        }
        SystemEntity entity = systemApi.getInfoByEnCode(YunzhupaasConst.MAIN_SYSTEM_CODE);
        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();
        }
        // 开发平台权限获取
        AuthorizeVO mainSystemAuthorize = new AuthorizeVO();
        if (isMainSystem) {
            if (isAdmin || organizeAdministratorEntity.size() > 0) {
                List<String> mainModuleId = new ArrayList<>();
                List<String> moduleId = organizeAdministratorEntity.stream()
                        .filter(t -> PermissionConst.MODULE.equals(t.getOrganizeType()))
                        .map(OrganizeAdministratorEntity::getOrganizeId).collect(Collectors.toList());
                mainModuleId.addAll(moduleId);
                if (organizeAdministratorEntity.size() > 0) {
                    mainModuleId.add(YunzhupaasConst.MAIN_SYSTEM_CODE);
                }
                AuthorizeVO mainAuthorize = this.getMainSystemAuthorize(mainModuleId, moduleAuthorize,
                        moduleUrlAddressAuthorize, singletonOrg);
                mainSystemAuthorize.setModuleList(mainAuthorize.getModuleList());
                mainSystemAuthorize.setButtonList(mainAuthorize.getButtonList());
                mainSystemAuthorize.setColumnList(mainAuthorize.getColumnList());
                mainSystemAuthorize.setResourceList(mainAuthorize.getResourceList());
                mainSystemAuthorize.setFormsList(mainAuthorize.getFormsList());
                if ((organizeAdministratorEntity.size() > 0 && moduleId.size() > 0) || isAdmin) {
                    mainSystemAuthorize.setSystemList(mainAuthorize.getSystemList());
                }
            }
        }
        if (!isAdmin) {
            if (organizeAdministratorEntity.size() > 0) {
                List<String> systemId = organizeAdministratorEntity.stream()
                        .filter(t -> PermissionConst.SYSTEM.equals(t.getOrganizeType()))
                        .map(OrganizeAdministratorEntity::getOrganizeId).collect(Collectors.toList());
                List<SystemEntity> systemEntities = systemApi.getListByIds(systemId, moduleAuthorize);
                List<SystemBaeModel> systemJsonToList = JsonUtil.getJsonToList(systemEntities, SystemBaeModel.class);
                systemList.addAll(systemJsonToList);
                List<String> systemIds = systemJsonToList.stream().map(SystemBaeModel::getId)
                        .collect(Collectors.toList());
                List<ModuleEntity> moduleBySystemIds = moduleApi.getModuleBySystemIds(systemIds, moduleAuthorize,
                        moduleUrlAddressAuthorize);
                List<ModuleModel> moduleJsonToList = JsonUtil.getJsonToList(moduleBySystemIds, ModuleModel.class);
                moduleList.addAll(moduleJsonToList);
                List<ModuleButtonEntity> buttonByModuleId = buttonApi.getListByModuleIds(
                        moduleJsonToList.stream().map(ModuleModel::getId).collect(Collectors.toList()));
                List<ButtonModel> buttonJsonToList = JsonUtil.getJsonToList(buttonByModuleId, ButtonModel.class);
                buttonList.addAll(buttonJsonToList);
                List<ModuleColumnEntity> columnByModuleId = columnApi.getListByModuleId(
                        moduleJsonToList.stream().map(ModuleModel::getId).collect(Collectors.toList()));
                List<ColumnModel> columnJsonToList = JsonUtil.getJsonToList(columnByModuleId, ColumnModel.class);
                columnList.addAll(columnJsonToList);
                List<ModuleDataAuthorizeSchemeEntity> resourceByModuleId = dataAuthorizeSchemeApi.getListByModuleId(
                        moduleJsonToList.stream().map(ModuleModel::getId).collect(Collectors.toList()));
                List<ResourceModel> resourceJsonToList = JsonUtil.getJsonToList(resourceByModuleId,
                        ResourceModel.class);
                resourceList.addAll(resourceJsonToList);
                List<ModuleFormEntity> formByModuleId = formApi.getListByModuleId(
                        moduleJsonToList.stream().map(ModuleModel::getId).collect(Collectors.toList()));
                List<ModuleFormModel> formJsonToList = JsonUtil.getJsonToList(formByModuleId, ModuleFormModel.class);
                formsList.addAll(formJsonToList);
            } else {
                List<String> roleIdList = new ArrayList<>();
                permissionGroupService
                        .getPermissionGroupByUserId(userInfo.getUserId(), userInfo.getOrganizeId(), true, null)
                        .forEach(t -> {
                            roleIdList.add(t.getId());
                        });
                List<AuthorizeEntity> authorizeList = new ArrayList<>();
                if (roleIdList.size() > 0) {
                    QueryWrapper<AuthorizeEntity> wrapper = new QueryWrapper<>();
                    wrapper.lambda().in(AuthorizeEntity::getObjectId, roleIdList);
                    authorizeList = this.list(wrapper);
                }
                // 应用
                List<String> systemId = authorizeList.stream()
                        .filter(t -> AuthorizeConst.SYSTEM.equals(t.getItemType())).map(AuthorizeEntity::getItemId)
                        .collect(Collectors.toList());
                systemId.remove(entity.getId());
                if (systemId.size() > 0) {
                    List<SystemEntity> systemAdmin = systemApi.getListByIds(systemId, moduleAuthorize);
                    systemList = JsonUtil.getJsonToList(systemAdmin, SystemBaeModel.class);
                    systemId = systemAdmin.stream().map(SystemEntity::getId).collect(Collectors.toList());
                }
                // 菜单 无开发平台
                List<String> moduleId = authorizeList.stream()
                        .filter(t -> AuthorizeConst.MODULE.equals(t.getItemType())).map(AuthorizeEntity::getItemId)
                        .collect(Collectors.toList());
                if (moduleId.size() > 0 && systemId.size() > 0) {
                    moduleList = this.baseMapper.findModule(moduleId, systemId, moduleAuthorize,
                            moduleUrlAddressAuthorize, singletonOrg ? 0 : 1, YunzhupaasConst.MODULE_CODE);
                }
                // 按钮
                List<String> buttonId = authorizeList.stream()
                        .filter(t -> AuthorizeConst.BUTTON.equals(t.getItemType())).map(AuthorizeEntity::getItemId)
                        .collect(Collectors.toList());
                if (buttonId.size() > 0) {
                    buttonList = this.baseMapper.findButton(buttonId);
                }
                // 列表
                List<String> columnId = authorizeList.stream()
                        .filter(t -> AuthorizeConst.COLUMN.equals(t.getItemType())).map(AuthorizeEntity::getItemId)
                        .collect(Collectors.toList());
                if (columnId.size() > 0) {
                    columnList = this.baseMapper.findColumn(columnId);
                }
                // 数据
                List<String> resourceId = authorizeList.stream()
                        .filter(t -> AuthorizeConst.RESOURCE.equals(t.getItemType())).map(AuthorizeEntity::getItemId)
                        .collect(Collectors.toList());
                if (resourceId.size() > 0) {
                    resourceList = this.baseMapper.findResource(resourceId);
                }
                // 表单
                List<String> formId = authorizeList.stream().filter(t -> AuthorizeConst.FROM.equals(t.getItemType()))
                        .map(AuthorizeEntity::getItemId).collect(Collectors.toList());
                if (formId.size() > 0) {
                    formsList = this.baseMapper.findForms(formId);
                }
            }
        } else {
            buttonList = this.baseMapper.findButtonAdmin(1);
            columnList = this.baseMapper.findColumnAdmin(1);
            resourceList = this.baseMapper.findResourceAdmin(1);
            formsList = this.baseMapper.findFormsAdmin(1);
            List<SystemEntity> systemAdmin = systemApi.findSystemAdmin(singletonOrg ? 0 : 1,
                    YunzhupaasConst.MAIN_SYSTEM_CODE, moduleAuthorize);
            systemList = JsonUtil.getJsonToList(systemAdmin, SystemBaeModel.class);
            List<String> systemId = systemList.stream().map(SystemBaeModel::getId).collect(Collectors.toList());
            List<ModuleEntity> moduleAdmin = moduleApi.findModuleAdmin(singletonOrg ? 0 : 1, entity.getId(),
                    moduleAuthorize, moduleUrlAddressAuthorize);
            moduleList = JsonUtil.getJsonToList(moduleAdmin, ModuleModel.class).stream()
                    .filter(t -> systemId.contains(t.getSystemId())).collect(Collectors.toList());
        }
        systemList.addAll(mainSystemAuthorize.getSystemList());
        moduleList.addAll(mainSystemAuthorize.getModuleList());
        buttonList.addAll(mainSystemAuthorize.getButtonList());
        columnList.addAll(mainSystemAuthorize.getColumnList());
        resourceList.addAll(mainSystemAuthorize.getResourceList());
        formsList.addAll(mainSystemAuthorize.getFormsList());
        return new AuthorizeVO(moduleList, buttonList, columnList, resourceList, formsList, systemList);
    }

    @Override
    @DS("")
    public List<SuperJsonModel> getConditionSql(String moduleId) {
        List<SuperJsonModel> list = new ArrayList<>();
        UserInfo userInfo = UserProvider.getUser();
        String reidsKey = cacheKeyUtil.getUserAuthorize() + moduleId + "_" + userInfo.getUserId();
        long time = 60 * 5;
        if (redisUtil.exists(reidsKey)) {
            return JsonUtil.getJsonToList(redisUtil.getString(reidsKey).toString(), SuperJsonModel.class);
        }

        AuthorizeVO model = this.getAuthorizeByUser(false);
        if (model == null) {
            redisUtil.insert(reidsKey, JsonUtil.getObjectToString(new ArrayList<>()), time);
            return new ArrayList<>();
        }
        List<ResourceModel> resourceListAll = model.getResourceList().stream()
                .filter(m -> m.getModuleId().equals(moduleId)).collect(Collectors.toList());
        // 先遍历一次 查找其中有没有全部方案
        boolean isAll = resourceListAll.stream().filter(item -> "yunzhupaas_alldata".equals(item.getEnCode())
                || item.getEnCode().startsWith("yunzhupaas_alldata")).count() > 0;
        // 未分配权限方案
        if (isAll || userInfo.getIsAdministrator()) {
            SuperJsonModel superJsonModel = new SuperJsonModel();
            list.add(superJsonModel);
            redisUtil.insert(reidsKey, JsonUtil.getObjectToString(list), time);
            return list;
        }
        Map<String, List<ResourceModel>> authorizeMap = resourceListAll.stream()
                .filter(t -> StringUtil.isNotEmpty(t.getObjectId()))
                .collect(Collectors.groupingBy(ma -> ma.getObjectId()));
        int num = 0;
        // 方案
        for (String key : authorizeMap.keySet()) {
            List<ResourceModel> resourceList = authorizeMap.get(key);
            boolean authorizeLogic = num == 0;
            for (ResourceModel item : resourceList) {
                String matchLogic = StringUtil.isNotEmpty(item.getMatchLogic()) ? item.getMatchLogic()
                        : SearchMethodEnum.And.getSymbol();
                List<SuperQueryJsonModel> conditionList = new ArrayList<>();
                List<ConditionModel> conditionModelList = JsonUtil.getJsonToList(item.getConditionJson(),
                        ConditionModel.class);
                // 分组
                for (ConditionModel conditionModel : conditionModelList) {
                    String logic = conditionModel.getLogic();
                    List<FieLdsModel> groupList = new ArrayList<>();
                    // 条件
                    for (ConditionModel.ConditionItemModel fieldItem : conditionModel.getGroups()) {
                        SearchMethodEnum itemMethod = SearchMethodEnum.getSearchMethod(fieldItem.getOp());
                        String itemField = fieldItem.getField();
                        String table = fieldItem.getBindTable();
                        if (itemField.contains(".") && itemField.split("\\.").length == 2) {
                            table = itemField.split("\\.")[0];
                            itemField = itemField.split("\\.")[1];
                        }
                        String bindTable = table;
                        String vModel = itemField;
                        String fileId = "";
                        FieLdsModel fieLdsModel = new FieLdsModel();
                        ConfigModel config = new ConfigModel();
                        String yunzhupaasKey = fieldItem.getConditionText();
                        if (AuthorizeConditionEnum.CURRENTTIME.getCondition().equals(yunzhupaasKey)) {
                            yunzhupaasKey = AuthorizeConst.DATE_PICKER;
                        }
                        switch (fieldItem.getFieldRule()) {
                            case "1":
                                fileId = "yunzhupaas_" + bindTable + "_yunzhupaas_" + vModel;
                                break;
                            case "2":
                                fileId = fieldItem.getChildTableKey() + "-" + vModel;
                                break;
                            default:
                                fileId = vModel;
                                break;
                        }

                        config.setYunzhupaasKey(yunzhupaasKey);
                        config.setTableName(bindTable);
                        fieLdsModel.setConfig(config);
                        fieLdsModel.setSymbol(itemMethod.getSymbol());
                        fieLdsModel.setVModel(vModel);
                        fieLdsModel.setId(fileId);
                        fieLdsModel.setFieldValue(fieldItem.getValue());
                        groupList.add(fieLdsModel);
                    }
                    // 搜索条件
                    SuperQueryJsonModel queryJsonModel = new SuperQueryJsonModel();
                    queryJsonModel.setGroups(groupList);
                    queryJsonModel.setLogic(logic);
                    conditionList.add(queryJsonModel);
                }
                if (conditionList.size() > 0) {
                    SuperJsonModel superJsonModel = new SuperJsonModel();
                    superJsonModel.setMatchLogic(matchLogic);
                    superJsonModel.setConditionList(conditionList);
                    superJsonModel.setAuthorizeLogic(authorizeLogic);
                    list.add(superJsonModel);
                }
            }
            num += list.size() > 0 ? 1 : 0;
        }
        redisUtil.insert(reidsKey, JsonUtil.getObjectToString(list), time);
        return list;
    }

    @Override
    public void removeAuthByUserOrMenu(List<String> userIds, List<String> menuIds) {
        userIds = userIds == null ? new ArrayList<>() : userIds;
        menuIds = menuIds == null ? new ArrayList<>() : menuIds;
        Set<String> allKeys = redisUtil.getAllKeys();
        for (String cacheKey : allKeys) {
            for (String user : userIds) {
                if (cacheKey.startsWith(cacheKeyUtil.getUserAuthorize()) && cacheKey.contains(user)) {
                    redisUtil.remove(cacheKey);
                }
            }
            for (String menuId : menuIds) {
                if (cacheKey.startsWith(cacheKeyUtil.getUserAuthorize()) && cacheKey.contains(menuId)) {
                    redisUtil.remove(cacheKey);
                }
            }
        }
    }

    @Override
    public boolean getUserCurrentStanding(String userId, Integer standType) {
        if (UserProvider.getUser() == null || UserProvider.getUser().getUserId() == null)
            return false;
        List<UserSystemVO> userStanding = this.getUserStanding(false, UserProvider.getUser().getUserId());
        if (standType != null && userStanding.stream().anyMatch(t -> standType.toString().equals(t.getId()))) {
            return true;
        }
        return false;
    }
}
