package jnpf.personnels.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jnpf.base.UserInfo;
import jnpf.base.entity.SuperBaseEntity;
import jnpf.model.cultivate.vo.identify.IdentifyAppAuthorityAppraiserVO;
import jnpf.model.personnels.dto.authoritys.FtbAddNewPermissionsDTO;
import jnpf.model.personnels.dto.authoritys.FtbAddNewPermissionsUpdateDTO;
import jnpf.model.personnels.dto.authoritys.FtbPermissionInfoDTO;
import jnpf.model.personnels.po.FtbPersonnelsAuthoritys;
import jnpf.model.personnels.po.FtbPersonnelsPermissionUser;
import jnpf.model.personnels.po.FtbPersonnelsPermissions;
import jnpf.model.personnels.po.FtbPersonnelsStaffRoster;
import jnpf.model.personnels.vo.authoritys.FtbPermissionInfoVO;
import jnpf.model.personnels.vo.authoritys.FtbPersonnelsPermissionUserVO;
import jnpf.model.personnels.vo.authoritys.FtbPersonnelsPermissionVO;
import jnpf.model.personnels.vo.authoritys.FtbPersonnelsScopeVO;
import jnpf.permission.OrganizeApi;
import jnpf.permission.PositionApi;
import jnpf.permission.UserApi;
import jnpf.permission.entity.UserEntity;
import jnpf.permission.model.ListIdDTO;
import jnpf.permission.model.position.PositionGradesInfoBoundVO;
import jnpf.permission.model.user.SubordinateUserInfoVO;
import jnpf.permission.model.user.UserBoundMoreInfoVO;
import jnpf.personnels.mapper.FtbPersonnelsAuthoritysMapper;
import jnpf.personnels.mapper.FtbPersonnelsPermissionsMapper;
import jnpf.personnels.service.FtbPersonnelsPermissionUserService;
import jnpf.personnels.service.FtbPersonnelsPermissionsService;
import jnpf.personnels.service.FtbPersonnelsStaffRosterService;
import jnpf.personnels.utils.PersonnelPerUtils;
import jnpf.util.UploaderUtil;
import jnpf.util.UserProvider;
import jnpf.util.data.DataSourceContextHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class FtbPersonnelsPermissionsServiceImpl extends ServiceImpl<FtbPersonnelsPermissionsMapper, FtbPersonnelsPermissions> implements FtbPersonnelsPermissionsService {

    @Resource
    private FtbPersonnelsPermissionUserService ftbPersonnelsPermissionUserService;

    @Resource
    private FtbPersonnelsAuthoritysMapper ftbPersonnelsAuthoritysMapper;

    @Resource
    private PositionApi positionApi;

    @Autowired
    private OrganizeApi organizeApi;

    @Autowired
    private UserApi userApi;

    @Resource
    private FtbPersonnelsStaffRosterService ftbPersonnelsStaffRosterService;

    @Resource
    private PersonnelPerUtils personnelPerUtils;

    /**
     * 特殊权限标识
     */
    public static final Set<String> SPECIAL_PERMISSION_IDENTIFIER = Set.of("Personnel:Configuration:configuration", "Examination:Paper:Marking"
            , "Appraisal:Practical:Review", "Audit:Cases");

    @Override
    @Transactional
    public void deletePermissions(String id) {
        LambdaQueryWrapper<FtbPersonnelsPermissionUser> ftbPersonnelsPermissionUserLambdaQueryWrapper = Wrappers.lambdaQuery();
        ftbPersonnelsPermissionUserLambdaQueryWrapper.eq(FtbPersonnelsPermissionUser::getPermissionId, id);
        ftbPersonnelsPermissionUserService.remove(ftbPersonnelsPermissionUserLambdaQueryWrapper);
        this.baseMapper.deleteById(id);
    }

    @Override
    public List<FtbPersonnelsPermissionVO> queryThePermissionListWhenAdding(Long moduleType) {
        LambdaQueryWrapper<FtbPersonnelsAuthoritys> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(FtbPersonnelsAuthoritys::getModuleType, moduleType);
        queryWrapper.eq(FtbPersonnelsAuthoritys::getEnableMark, 0);
        List<FtbPersonnelsAuthoritys> ftbPersonnelsAuthoritysList = ftbPersonnelsAuthoritysMapper.selectList(queryWrapper);
        return recursivePermissions(ftbPersonnelsAuthoritysList, "0", null);
    }

    @Override
    public List<String> queryPermissionList(UserInfo userInfo, String parentPermissions, Integer permissionType) {
        List<String> authorityIds = null;
        if (!userInfo.getIsAdministrator()) {
            LambdaQueryWrapper<FtbPersonnelsPermissions> queryWrapper = Wrappers.lambdaQuery();
            queryWrapper.eq(FtbPersonnelsPermissions::getUserId, userInfo.getUserId());
            queryWrapper.eq(FtbPersonnelsPermissions::getPermissionType, permissionType);
            FtbPersonnelsPermissions ftbPersonnelsPermissions = this.baseMapper.selectOne(queryWrapper);
            if (Objects.isNull(ftbPersonnelsPermissions)) {
                return null;
            }
            LambdaQueryWrapper<FtbPersonnelsPermissionUser> ftbPersonnelsPermissionUserLambdaQueryWrapper = Wrappers.lambdaQuery();
            ftbPersonnelsPermissionUserLambdaQueryWrapper.eq(FtbPersonnelsPermissionUser::getPermissionId, ftbPersonnelsPermissions.getId());
            List<FtbPersonnelsPermissionUser> ftbPersonnelsPermissionUserList = ftbPersonnelsPermissionUserService.list(ftbPersonnelsPermissionUserLambdaQueryWrapper);
            authorityIds = ftbPersonnelsPermissionUserList.stream().map(FtbPersonnelsPermissionUser::getAuthorityId).collect(Collectors.toList());
        }

        LambdaQueryWrapper<FtbPersonnelsAuthoritys> ftbPersonnelsAuthoritysLambdaQueryWrapper = Wrappers.lambdaQuery();
        ftbPersonnelsAuthoritysLambdaQueryWrapper.in(FtbPersonnelsAuthoritys::getAuthorityIdentify, List.of(parentPermissions.split(StringPool.COMMA)));
        List<FtbPersonnelsAuthoritys> ftbPersonnelsAuthoritys = ftbPersonnelsAuthoritysMapper.selectList(ftbPersonnelsAuthoritysLambdaQueryWrapper);
        // 登记表配置、试卷批阅、批阅实操鉴定、审核案例
        if (SPECIAL_PERMISSION_IDENTIFIER.contains(parentPermissions)) {
            if (userInfo.getIsAdministrator() || authorityIds.contains("68")
                    || authorityIds.contains("70") || authorityIds.contains("71")
                    || authorityIds.contains("135")) {
                return List.of(parentPermissions);
            }
        }
        ftbPersonnelsAuthoritysLambdaQueryWrapper.clear();
        List<String> authoritysIds = ftbPersonnelsAuthoritys.stream().map(FtbPersonnelsAuthoritys::getId).collect(Collectors.toList());
        ftbPersonnelsAuthoritysLambdaQueryWrapper.in(FtbPersonnelsAuthoritys::getParentId, authoritysIds);
        ftbPersonnelsAuthoritysLambdaQueryWrapper.in(!CollectionUtils.isEmpty(authorityIds), FtbPersonnelsAuthoritys::getId, authorityIds);
        return ftbPersonnelsAuthoritysMapper.selectList(ftbPersonnelsAuthoritysLambdaQueryWrapper)
                .stream()
                .map(FtbPersonnelsAuthoritys::getAuthorityIdentify)
                .collect(Collectors.toList());

    }

    @Override
    @Transactional
    public void addNewPermissions(FtbAddNewPermissionsDTO ftbAddNewPermissionsDTO) {
        // 是否已添加
        LambdaQueryWrapper<FtbPersonnelsPermissions> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(FtbPersonnelsPermissions::getUserId, ftbAddNewPermissionsDTO.getUserId());
        queryWrapper.eq(FtbPersonnelsPermissions::getPermissionType, ftbAddNewPermissionsDTO.getPermissionType());
        if (this.baseMapper.selectCount(queryWrapper) > 0) {
            throw new RuntimeException("请勿对同一用户设置重复权限");
        }
        savePermissons(ftbAddNewPermissionsDTO);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addNewPermissionsChange(FtbAddNewPermissionsUpdateDTO ftbAddNewPermissionsUpdateDTO) {
        LambdaQueryWrapper<FtbPersonnelsPermissions> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(SuperBaseEntity.SuperIBaseEntity::getId, ftbAddNewPermissionsUpdateDTO.getId());
        LambdaQueryWrapper<FtbPersonnelsPermissionUser> ftbPersonnelsPermissionUserLambdaQueryWrapper = Wrappers.lambdaQuery();
        ftbPersonnelsPermissionUserLambdaQueryWrapper.eq(FtbPersonnelsPermissionUser::getPermissionId, ftbAddNewPermissionsUpdateDTO.getId());
        FtbPersonnelsPermissions ftbPersonnelsPermissions = this.baseMapper.selectById(ftbAddNewPermissionsUpdateDTO.getId());
        ftbAddNewPermissionsUpdateDTO.setOrgNames(ftbPersonnelsPermissions.getOrgNames());
        ftbAddNewPermissionsUpdateDTO.setPostRankNames(ftbPersonnelsPermissions.getPostRankNames());
        ftbAddNewPermissionsUpdateDTO.setPostNames(ftbPersonnelsPermissions.getPostNames());
        ftbAddNewPermissionsUpdateDTO.setOrgIds(ftbPersonnelsPermissions.getOrgIds());
        ftbAddNewPermissionsUpdateDTO.setPostRankIds(ftbPersonnelsPermissions.getPostRankIds());
        ftbAddNewPermissionsUpdateDTO.setPostIds(ftbPersonnelsPermissions.getPostIds());
        ftbAddNewPermissionsUpdateDTO.setPhone(ftbAddNewPermissionsUpdateDTO.getPhone());
        this.baseMapper.delete(queryWrapper);
        ftbPersonnelsPermissionUserService.remove(ftbPersonnelsPermissionUserLambdaQueryWrapper);
        savePermissons(ftbAddNewPermissionsUpdateDTO);
    }

    @Override
    public FtbPersonnelsPermissionUserVO adminDetails(String id, Long moduleType) {
        FtbPersonnelsPermissions ftbPersonnelsPermissions = this.baseMapper.selectById(id);
        FtbPersonnelsPermissionUserVO ftbPersonnelsPermissionUserVO = FtbPersonnelsPermissionUserVO.convertFtbPersonnelsPermissionUserVO(ftbPersonnelsPermissions);
        LambdaQueryWrapper<FtbPersonnelsStaffRoster> ftbpersonstaffstaffLambdaQueryWrapper = Wrappers.lambdaQuery();
        ftbpersonstaffstaffLambdaQueryWrapper.select(FtbPersonnelsStaffRoster::getName, FtbPersonnelsStaffRoster::getPhone);
        ftbpersonstaffstaffLambdaQueryWrapper.eq(FtbPersonnelsStaffRoster::getUserId, ftbPersonnelsPermissionUserVO.getUserId());
        ftbpersonstaffstaffLambdaQueryWrapper.last("limit 1");
        FtbPersonnelsStaffRoster ftbPersonnelsStaffRosters = ftbPersonnelsStaffRosterService.getBaseMapper().selectOne(ftbpersonstaffstaffLambdaQueryWrapper);
        // 姓名
        ftbPersonnelsPermissionUserVO.setUserName(Objects.nonNull(ftbPersonnelsStaffRosters) ? ftbPersonnelsStaffRosters.getName() : "花名册中暂无此人姓名");
        ftbPersonnelsPermissionUserVO.setPhone(Objects.nonNull(ftbPersonnelsStaffRosters) ? ftbPersonnelsStaffRosters.getPhone() : "花名册中暂无此人号码");
        LambdaQueryWrapper<FtbPersonnelsPermissionUser> ftbPersonnelsPermissionUserLambdaQueryWrapper = Wrappers.lambdaQuery();
        ftbPersonnelsPermissionUserLambdaQueryWrapper.eq(FtbPersonnelsPermissionUser::getPermissionId, id);
        List<FtbPersonnelsPermissionUser> ftbPersonnelsPermissionUsers = ftbPersonnelsPermissionUserService.list(ftbPersonnelsPermissionUserLambdaQueryWrapper);
        List<String> authorityIds = ftbPersonnelsPermissionUsers.stream().map(FtbPersonnelsPermissionUser::getAuthorityId).collect(Collectors.toList());
        LambdaQueryWrapper<FtbPersonnelsAuthoritys> ftbPersonnelsAuthoritysLambdaQueryWrapper = Wrappers.lambdaQuery();
        ftbPersonnelsAuthoritysLambdaQueryWrapper.eq(FtbPersonnelsAuthoritys::getEnableMark, 0);
        ftbPersonnelsAuthoritysLambdaQueryWrapper.eq(FtbPersonnelsAuthoritys::getModuleType, moduleType);
        List<FtbPersonnelsAuthoritys> ftbPersonnelsAuthoritys = ftbPersonnelsAuthoritysMapper.selectList(ftbPersonnelsAuthoritysLambdaQueryWrapper);
        List<FtbPersonnelsPermissionVO> ftbPersonnelsPermissionVOS = recursivePermissions(ftbPersonnelsAuthoritys, "0", authorityIds);
        ftbPersonnelsPermissionUserVO.setFtbPersonnelsPermissionVOS(ftbPersonnelsPermissionVOS);
        // 直属主管
        List<FtbPersonnelsPermissionUserVO.EmployeeOrganizationInformationVO> employeeOrganizationInformationVOS = new ArrayList<>();
        // 获取组织
      //  List<PositionGradesInfoBoundVO> orgPositionInfoList = positionApi.getOrgPositionInfoList(ftbPersonnelsPermissionUserVO.getUserId());
        List<UserBoundMoreInfoVO> userBoundMoreInfosByUserId = userApi.getUserBoundMoreInfosByUserId(ftbPersonnelsPermissionUserVO.getUserId());
        for (UserBoundMoreInfoVO userBoundMoreInfoVO : userBoundMoreInfosByUserId) {
                FtbPersonnelsPermissionUserVO.EmployeeOrganizationInformationVO employeeOrganizationInformationVO = new FtbPersonnelsPermissionUserVO.EmployeeOrganizationInformationVO();
                employeeOrganizationInformationVO.setPostName(userBoundMoreInfoVO.getPositionName());
                employeeOrganizationInformationVO.setPostRankName(userBoundMoreInfoVO.getPositionGradesName());
                employeeOrganizationInformationVO.setOrgName(userBoundMoreInfoVO.getOrganizeName());
                employeeOrganizationInformationVO.setNameOfImmediateSupervisor(userBoundMoreInfoVO.getManagerRealName());
                employeeOrganizationInformationVOS.add(employeeOrganizationInformationVO);
        }
        ftbPersonnelsPermissionUserVO.setEmployeeOrganizationInformationVOS(employeeOrganizationInformationVOS);
        return ftbPersonnelsPermissionUserVO;
    }

    @Override
    public Page<FtbPermissionInfoVO> permissionList(Page<FtbPermissionInfoVO> page, FtbPermissionInfoDTO ftbPermissionInfoDTO) {
        boolean keywordExists = StrUtil.isNotBlank(ftbPermissionInfoDTO.getKeyword());
        if (keywordExists) {
            List<String> userIds = baseMapper.rosterFuzzyQuery(ftbPermissionInfoDTO.getKeyword());
            ftbPermissionInfoDTO.getUserId().addAll(userIds);
        }
        // 是否勾选岗位、组织、职等
        boolean orgIdsExist = StrUtil.isNotBlank(ftbPermissionInfoDTO.getOrgId())
                || StrUtil.isNotBlank(ftbPermissionInfoDTO.getPostId())
                || StrUtil.isNotBlank(ftbPermissionInfoDTO.getPostRankId());
        if (orgIdsExist) {
            List<String> userIdsByGradesId = userApi.getUserIdsByGradesId(ftbPermissionInfoDTO.getOrgId(), ftbPermissionInfoDTO.getPostId(), ftbPermissionInfoDTO.getPostRankId());
            if (keywordExists && (CollectionUtils.isEmpty(ftbPermissionInfoDTO.getUserId()) || CollectionUtils.isEmpty(userIdsByGradesId))) {
                return page;
            } else if (!keywordExists && !CollectionUtils.isEmpty(userIdsByGradesId)) {
                ftbPermissionInfoDTO.getUserId().addAll(userIdsByGradesId);
            } else {
                Collection<String> intersection = CollUtil.intersection(ftbPermissionInfoDTO.getUserId(), userIdsByGradesId);
                ftbPermissionInfoDTO.getUserId().clear();
                ftbPermissionInfoDTO.getUserId().addAll(intersection);
            }
        }
        if ((keywordExists || orgIdsExist) && CollectionUtils.isEmpty(ftbPermissionInfoDTO.getUserId())) {
            return page;
        }
        Page<FtbPermissionInfoVO> result = this.baseMapper.permissionList(page, ftbPermissionInfoDTO);
        List<String> userIds = result.getRecords().stream().map(FtbPermissionInfoVO::getUserId).collect(Collectors.toList());
        // 实时查询用户名
        Map<String, String> userNames;
        Map<String, List<PositionGradesInfoBoundVO>> positionGradesInfoBoundVOMap;
        if (!userIds.isEmpty()) {
            LambdaQueryWrapper<FtbPersonnelsStaffRoster> ftbpersonstaffstaffLambdaQueryWrapper = Wrappers.lambdaQuery();
            ftbpersonstaffstaffLambdaQueryWrapper.select(FtbPersonnelsStaffRoster::getName,
                    FtbPersonnelsStaffRoster::getUserId, FtbPersonnelsStaffRoster::getPhone);
            ftbpersonstaffstaffLambdaQueryWrapper.in(FtbPersonnelsStaffRoster::getUserId, userIds);
            List<FtbPersonnelsStaffRoster> ftbPersonnelsStaffRosters = ftbPersonnelsStaffRosterService.getBaseMapper().selectList(ftbpersonstaffstaffLambdaQueryWrapper);
            userNames = ftbPersonnelsStaffRosters.stream()
                    .filter(a -> StrUtil.isNotBlank(a.getName()) && StrUtil.isNotBlank(a.getPhone()))
                    .collect(Collectors.toMap(FtbPersonnelsStaffRoster::getUserId, a -> a.getName() + "#" + a.getPhone()));

            ListIdDTO remoteUserIds = new ListIdDTO();
            remoteUserIds.setIds(userIds);
            List<PositionGradesInfoBoundVO> orgPositionInfoLists = positionApi.postOrgPositionInfoList(remoteUserIds);
            positionGradesInfoBoundVOMap = orgPositionInfoLists.stream().filter(a -> StrUtil.isNotBlank(a.getUserId()))
                    .collect(Collectors.groupingBy(PositionGradesInfoBoundVO::getUserId));
        } else {
            userNames = new HashMap<>();
            positionGradesInfoBoundVOMap = new HashMap<>();
        }
        UserInfo userInfo = UserProvider.getUser();
        result.getRecords().parallelStream().forEach(ftbPermissionInfoVO -> {
            try {
                DataSourceContextHolder.setDatasource(userInfo.getTenantId(), userInfo.getTenantDbConnectionString(), userInfo.isAssignDataSource());
                // 用户名、手机号、权限名
                String userNamesOrDefault = userNames.getOrDefault(ftbPermissionInfoVO.getUserId(), " # ");
                String[] userNamesSplit = userNamesOrDefault.split("#");
                ftbPermissionInfoVO.setUserName(userNamesSplit[0]);
                ftbPermissionInfoVO.setPhone(userNamesSplit[1]);
                if (StrUtil.isNotBlank(ftbPermissionInfoDTO.getPermissionId())) {
                    List<FtbPermissionInfoVO.PermissionsVO> authorityNames = this.baseMapper
                            .getTopLevelPermissions(null, Arrays.asList(ftbPermissionInfoVO.getPermissionIds().split(",")));
                    ftbPermissionInfoVO.setPermissionNames(authorityNames);
                } else {
                    if (StrUtil.isNotBlank(ftbPermissionInfoVO.getPermissionIds())) {
                        List<FtbPermissionInfoVO.PermissionsVO> authorityNames = this.baseMapper
                                .getTopLevelPermissions(1, Arrays.asList(ftbPermissionInfoVO.getPermissionIds().split(",")));
                        ftbPermissionInfoVO.setPermissionNames(authorityNames);
                    }
                }
                // 根据员工id获取其所有组织、岗位、职等
                List<PositionGradesInfoBoundVO> orgPositionInfoList = positionGradesInfoBoundVOMap.get(ftbPermissionInfoVO.getUserId());
                if (!CollectionUtils.isEmpty(orgPositionInfoList)) {
                    List<String> orgName = orgPositionInfoList.stream().map(PositionGradesInfoBoundVO::getOrganizeNames)
                            .filter(Objects::nonNull)
                            .flatMap(Collection::stream)
                            .distinct().collect(Collectors.toList());
                    List<String> postName = orgPositionInfoList.stream().map(PositionGradesInfoBoundVO::getPositionName).distinct().collect(Collectors.toList());
                    List<String> postRankName = orgPositionInfoList.stream().map(PositionGradesInfoBoundVO::getPositionGradesName).distinct().collect(Collectors.toList());
                    ftbPermissionInfoVO.setOrgName(orgName);
                    ftbPermissionInfoVO.setPostName(postName);
                    ftbPermissionInfoVO.setPostRankName(postRankName);
                }
            } finally {
                DataSourceContextHolder.clearDatasourceType();
            }
        });
        return result;
    }

    @Override
    @SuppressWarnings("Duplicates")
    public List<IdentifyAppAuthorityAppraiserVO> queryAuthorityAppraiser(String orgId) {
        List<String> reviewerPermissions = baseMapper.getReviewerPermissions(List.of("71"));
        if (CollectionUtils.isEmpty(reviewerPermissions)) {
            return null;
        }
        LambdaQueryWrapper<FtbPersonnelsPermissions> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(FtbPersonnelsPermissions::getEnableMark, 0);
        queryWrapper.in(SuperBaseEntity.SuperIBaseEntity::getId, reviewerPermissions);
        List<FtbPersonnelsPermissions> ftbPersonnelsPermissions = baseMapper.selectList(queryWrapper);
        if (CollectionUtils.isEmpty(ftbPersonnelsPermissions)) {
            return null;
        }
        String userId = UserProvider.getLoginUserId();
        // 校验是否有关联关系
        List<String> userIds = new ArrayList<>();
        String userIdAndOrgId = userId + "#" + orgId;
        for (FtbPersonnelsPermissions ftbPersonnelsPermission : ftbPersonnelsPermissions) {
            if (ftbPersonnelsPermission.getScopePermission() == 2) {
                // 通过人员去排查
                List<SubordinateUserInfoVO> subordinateUserInfoVOS = userApi.userInfoByLeaderId(ftbPersonnelsPermission.getUserId());
                if (CollectionUtils.isEmpty(subordinateUserInfoVOS)) {
                    continue;
                }
                List<String> childrenUserIds = subordinateUserInfoVOS.stream()
                        .filter(a -> !CollectionUtils.isEmpty(a.getPositionMoreBoundVOList()))
                        .flatMap(a -> a.getPositionMoreBoundVOList().stream())
                        .map(a -> a.getUserId() + "#" + a.getOrganizeId()).collect(Collectors.toList());
                if (childrenUserIds.contains(userIdAndOrgId)) {
                    userIds.add(ftbPersonnelsPermission.getUserId());
                }
            }
            // 所在组织和下级组织员工,查询组织id进行比对
            List<String> organizeIdsAdnChildByUserId = null;
            if (ftbPersonnelsPermission.getScopePermission() == 0) {
                organizeIdsAdnChildByUserId = organizeApi.getOrganizeIdsAdnChildByUserId(ftbPersonnelsPermission.getUserId());
            }
            // 所在组织员工,查询组织id进行比对
            if (ftbPersonnelsPermission.getScopePermission() == 1) {
                organizeIdsAdnChildByUserId = organizeApi.getOrganizeIdsByUserId(ftbPersonnelsPermission.getUserId());
            }
            // 指定组织,组织id进行比对
            if (ftbPersonnelsPermission.getScopePermission() == 3) {
                organizeIdsAdnChildByUserId = Arrays.asList(ftbPersonnelsPermission.getSpecifyOrgIds().split(StringPool.COMMA));
            }
            if (!CollectionUtils.isEmpty(organizeIdsAdnChildByUserId) && organizeIdsAdnChildByUserId.contains(orgId)) {
                userIds.add(ftbPersonnelsPermission.getUserId());
            }
        }
        // 数据组装，过滤自己
        return userIds.stream().filter(a -> !userId.equals(a)).map(a -> {
            IdentifyAppAuthorityAppraiserVO identifyAppAuthorityAppraiserVO = new IdentifyAppAuthorityAppraiserVO();
            identifyAppAuthorityAppraiserVO.setId(a);
            UserEntity userEntity = userApi.getInfoById(a);
            if (Objects.nonNull(userEntity)) {
                identifyAppAuthorityAppraiserVO.setRealName(userEntity.getRealName());
                identifyAppAuthorityAppraiserVO.setHeadIcon(UploaderUtil.uploaderImg(userEntity.getHeadIcon()));
            }
            // 组织信息
            List<UserBoundMoreInfoVO> userBoundMoreInfosByUserId = userApi.getUserBoundMoreInfosByUserId(a);
            List<IdentifyAppAuthorityAppraiserVO.IdentifyAppAuthorityAppraiserInner> boundInfos = new ArrayList<>();
            if (!CollectionUtils.isEmpty(userBoundMoreInfosByUserId)) {
                userBoundMoreInfosByUserId.forEach(userBoundMoreInfoVO -> {
                    IdentifyAppAuthorityAppraiserVO.IdentifyAppAuthorityAppraiserInner identifyAppAuthorityAppraiserInner
                            = new IdentifyAppAuthorityAppraiserVO.IdentifyAppAuthorityAppraiserInner();
                    identifyAppAuthorityAppraiserInner.setOrganizeId(userBoundMoreInfoVO.getOrganizeId());
                    identifyAppAuthorityAppraiserInner.setOrganizeName(userBoundMoreInfoVO.getOrganizeName());
                    identifyAppAuthorityAppraiserInner.setPositionId(userBoundMoreInfoVO.getPositionId());
                    identifyAppAuthorityAppraiserInner.setPositionName(userBoundMoreInfoVO.getPositionName());
                    identifyAppAuthorityAppraiserInner.setPositionGradesId(userBoundMoreInfoVO.getPositionGradesId());
                    identifyAppAuthorityAppraiserInner.setPositionGradesName(userBoundMoreInfoVO.getPositionGradesName());
                    boundInfos.add(identifyAppAuthorityAppraiserInner);
                });
            }
            identifyAppAuthorityAppraiserVO.setBoundInfos(boundInfos);
            return identifyAppAuthorityAppraiserVO;
        }).collect(Collectors.toList());
    }

    @Override
    public FtbPersonnelsScopeVO selectOrganizationScope() {
        FtbPersonnelsScopeVO ftbPersonnelsScopeVO = new FtbPersonnelsScopeVO();
        List<String> orgIds = personnelPerUtils.obtainPersonnelOrganizationIdDataPermissions();
        if (orgIds == null) {
            ftbPersonnelsScopeVO.setSuperAdmin(1);
            return ftbPersonnelsScopeVO;
        }
        ftbPersonnelsScopeVO.setSuperAdmin(0);
        ftbPersonnelsScopeVO.setDataPermissions(orgIds);
        return ftbPersonnelsScopeVO;
    }

    @Override
    public FtbPersonnelsScopeVO selectEmployeeRange() {
        FtbPersonnelsScopeVO ftbPersonnelsScopeVO = new FtbPersonnelsScopeVO();
        List<String> userIds = personnelPerUtils.obtainPersonnelDataPermissions();
        if (userIds == null) {
            ftbPersonnelsScopeVO.setSuperAdmin(1);
            return ftbPersonnelsScopeVO;
        }
        ftbPersonnelsScopeVO.setSuperAdmin(0);
        ftbPersonnelsScopeVO.setDataPermissions(userIds);
        return ftbPersonnelsScopeVO;
    }

    @Override
    public void clearUserPermissions(String userId) {
        LambdaQueryWrapper<FtbPersonnelsPermissions> permissionsLambdaQueryWrapper = Wrappers.lambdaQuery();
        permissionsLambdaQueryWrapper.select(FtbPersonnelsPermissions::getId);
        permissionsLambdaQueryWrapper.eq(FtbPersonnelsPermissions::getEnableMark, 0);
        permissionsLambdaQueryWrapper.eq(FtbPersonnelsPermissions::getUserId, userId);
        List<FtbPersonnelsPermissions> ftbPersonnelsPermissions = this.baseMapper.selectList(permissionsLambdaQueryWrapper);
        ftbPersonnelsPermissions.forEach(a -> deletePermissions(a.getId()));
    }

    @Override
    public Boolean isThisUserAnEmployee() {
        UserInfo userInfo = UserProvider.getUser();
        if (userInfo.getIsAdministrator()) {
            return false;
        }
        LambdaQueryWrapper<FtbPersonnelsPermissions> permissionsLambdaQueryWrapper = Wrappers.lambdaQuery();
        permissionsLambdaQueryWrapper.eq(FtbPersonnelsPermissions::getEnableMark, 0);
        permissionsLambdaQueryWrapper.eq(FtbPersonnelsPermissions::getUserId, userInfo.getUserId());
        Long count = this.baseMapper.selectCount(permissionsLambdaQueryWrapper);
        return count == 0;
    }


    /**
     * 权限新增
     */
    private <T extends FtbAddNewPermissionsDTO> void savePermissons(T ftbAddNewPermissionsDTO) {
        FtbPersonnelsPermissions ftbPersonnelsPermissions = FtbAddNewPermissionsDTO.convertFtbPersonnelsPermissions(ftbAddNewPermissionsDTO);
        String userCustomId = ftbPersonnelsStaffRosterService.querySystemWorkerId(ftbAddNewPermissionsDTO.getUserId());
        // 根据员工id获取其所有组织、岗位、职等
        List<PositionGradesInfoBoundVO> orgPositionInfoList = positionApi.getOrgPositionInfoList(ftbAddNewPermissionsDTO.getUserId());
        if (!CollectionUtils.isEmpty(orgPositionInfoList)) {
            String orgIds = orgPositionInfoList.stream().map(PositionGradesInfoBoundVO::getOrganizeIds)
                    .filter(Objects::nonNull)
                    .flatMap(Collection::stream)
                    .distinct().collect(Collectors.joining(","));
            String postIds = orgPositionInfoList.stream().map(PositionGradesInfoBoundVO::getPositionId).distinct().collect(Collectors.joining(","));
            String postRankIds = orgPositionInfoList.stream().map(PositionGradesInfoBoundVO::getPositionGradesId).distinct().collect(Collectors.joining(","));
            ftbPersonnelsPermissions.setOrgIds(orgIds);
            ftbPersonnelsPermissions.setPostIds(postIds);
            ftbPersonnelsPermissions.setPostRankIds(postRankIds);
        }
        ftbPersonnelsPermissions.setUserCustomId(userCustomId);
        this.baseMapper.insert(ftbPersonnelsPermissions);
        List<FtbPersonnelsPermissionUser> ftbPersonalsPermissionUsers = ftbAddNewPermissionsDTO.getPermissionIds().stream().map(permissionId -> {
            FtbPersonnelsPermissionUser ftbPersonnelsPermissionUser = new FtbPersonnelsPermissionUser();
            ftbPersonnelsPermissionUser.setAuthorityId(permissionId);
            ftbPersonnelsPermissionUser.setPermissionId(ftbPersonnelsPermissions.getId());
            return ftbPersonnelsPermissionUser;
        }).collect(Collectors.toList());
        ftbPersonnelsPermissionUserService.saveBatch(ftbPersonalsPermissionUsers);
    }

    /**
     * 递归权限
     */
    private List<FtbPersonnelsPermissionVO> recursivePermissions(List<FtbPersonnelsAuthoritys> ftbPersonnelsAuthoritysList,
                                                                 String parentId, List<String> includeMap) {
        List<FtbPersonnelsPermissionVO> result = new ArrayList<>();
        for (FtbPersonnelsAuthoritys authority : ftbPersonnelsAuthoritysList) {
            FtbPersonnelsPermissionVO permissionVO = new FtbPersonnelsPermissionVO();
            permissionVO.setId(authority.getId());
            permissionVO.setAuthorityName(authority.getAuthorityName());
            permissionVO.setAuthorityType(authority.getAuthorityType());
            permissionVO.setAuthorityIdentify(authority.getAuthorityIdentify());
            permissionVO.setParentId(authority.getParentId());
            permissionVO.setChecked(includeMap != null && includeMap.contains(authority.getId()));
            if (parentId.equals(permissionVO.getParentId())) {
                permissionVO.setChildrenList(recursivePermissions(ftbPersonnelsAuthoritysList, authority.getId(), includeMap));
                result.add(permissionVO);
            }
        }
        return result;
    }




}
