KpiReportRatioTask.java 26.2 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607
package cn.fw.morax.server.task;

import cn.fw.common.cache.locker.DistributedLocker;
import cn.fw.morax.common.constant.TimeTaskConstant;
import cn.fw.morax.common.utils.PublicUtil;
import cn.fw.morax.domain.db.kpi.KpiGroup;
import cn.fw.morax.domain.db.kpi.KpiGroupRank;
import cn.fw.morax.domain.db.kpi.KpiPool;
import cn.fw.morax.domain.db.kpi.KpiRatio;
import cn.fw.morax.domain.dto.GroupCalKpiRatioDTO;
import cn.fw.morax.domain.enums.ReportDimensionEnum;
import cn.fw.morax.rpc.ehr.EhrRpcService;
import cn.fw.morax.rpc.ehr.dto.*;
import cn.fw.morax.rpc.oop.OopRpcService;
import cn.fw.morax.rpc.oop.dto.ShopDTO;
import cn.fw.morax.service.data.kpi.KpiGroupRankService;
import cn.fw.morax.service.data.kpi.KpiGroupService;
import cn.fw.morax.service.data.kpi.KpiPoolService;
import cn.fw.morax.service.data.kpi.KpiRatioService;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.google.common.collect.Lists;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.map.MultiKeyMap;
import org.redisson.api.RLock;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.time.YearMonth;
import java.util.*;
import java.util.concurrent.locks.Lock;
import java.util.function.Predicate;
import java.util.stream.Collectors;

/**
 * @author : jiangchao
 * @className : KpiReportRatioTask
 * @description : 绩效报表定时器
 * @date : 2022-04-07 15:29
 */
@Component
@Slf4j
@RequiredArgsConstructor
@ConditionalOnProperty(prefix = "task", name = "switch", havingValue = "on")
public class KpiReportRatioTask {

    private final KpiGroupRankService kpiGroupRankService;
    private final DistributedLocker distributedLocker;
    private final KpiGroupService kpiGroupService;
    private final KpiPoolService kpiPoolService;
    private final KpiRatioService kpiRatioService;
    private final EhrRpcService ehrRpcService;
    private final OopRpcService oopRpcService;

    @Value("${spring.cache.custom.global-prefix}:kpi:group:report")
    @Getter
    private String kpiGroupReportDistKey;

    /**
     * 绩效报表定时任务
     *
     */
    @Scheduled(cron = TimeTaskConstant.KPI_REPORT)
    @Transactional(rollbackFor = Exception.class)
    public void kpiReportTask() {
//        this.kpiReport(LocalDate.now().minusDays(1));
    }

    /**
     * 绩效报表定时任务
     *
     * @param date
     */
    @Transactional(rollbackFor = Exception.class)
    public void kpiReport(LocalDate date) {
        Lock lock = distributedLocker.lock(getKpiGroupReportDistKey());
        if (! ((RLock) lock).isLocked()) {
            return;
        }
        try {
            log.info("定时任务【绩效报表数据抽取】开始执行");

            kpiRatioService.update(Wrappers.<KpiRatio>lambdaUpdate()
                    .set(KpiRatio::getYn, Boolean.FALSE)
                    .eq(KpiRatio::getDate, date)
            );

            /**
             * 获取所有生效中的绩效组
             */
            List<KpiGroup> allKpiGroups = kpiGroupService.queryKgiGroupsByDay(date);
            Map<Long, List<KpiGroup>> groupKpiGroupMap = allKpiGroups.stream().collect(Collectors.groupingBy(KpiGroup::getGroupId));
            List<KpiRatio> kpiRatios = Lists.newArrayListWithCapacity(500);
            YearMonth curMonth = YearMonth.from(date);
            YearMonth preMonth = YearMonth.from(date.minusMonths(1));
            YearMonth preTwoMonth = YearMonth.from(date.minusMonths(2));

            //遍历集团
            oopRpcService.allGroups().stream().forEach(group -> {
                //构建查询参数
                Long groupId = group.getId();
                /**
                 * calDTO 得到计算的基础数据,包含当月N,上月N-1,上上月N-2的绩效人的绩效数据,还有绩效排名组信息,绩效组信息
                 */
                GroupCalKpiRatioDTO calDTO = buildParam(curMonth, preMonth, preTwoMonth, groupId);
                calDTO.setKpiGroups(groupKpiGroupMap.getOrDefault(groupId, new ArrayList<>()));

                //查询所有绩效组包含的所有门店
                Set<Long> shopIds = calDTO.getKpiGroups().stream().map(salaryGroup -> {
                    return salaryGroup.getShopIds().stream().map(Long::new).collect(Collectors.toList());
                }).collect(HashSet::new, Set::addAll, Set::addAll);
                if (PublicUtil.isEmpty(shopIds)) {
                    return;
                }
                List<ShopDTO> shopDTOs = oopRpcService.queryShops(new ArrayList<>(shopIds));

                //计算管理者数据
                calManagerData(calDTO, kpiRatios, shopDTOs, shopIds);
                //计算绩效排名组 门店
                calKpiRankData(calDTO, kpiRatios, shopDTOs);
                //计算员工
                calStaffData(calDTO, kpiRatios);
                //计算绩效组门店
                calShopData(calDTO, kpiRatios, shopDTOs);
            });
            if (PublicUtil.isNotEmpty(kpiRatios)) {
                kpiRatios.stream().forEach(kpiRatio -> {
                    kpiRatio.setDate(date);
                    kpiRatio.setYn(Boolean.TRUE);
                });
                kpiRatioService.saveBatch(kpiRatios);
            }

        } catch (Exception e){
            log.error(e.getMessage(), e);
        } finally {
            lock.unlock();
        }
    }

    /**
     *
     * 构建查询参数
     * @param curMonth
     * @param preMonth
     * @param preTwoMonth
     * @param groupId
     * @return
     */
    public GroupCalKpiRatioDTO buildParam(YearMonth curMonth, YearMonth preMonth, YearMonth preTwoMonth, Long groupId) {

        List<YearMonth> yearMonths = new ArrayList<YearMonth>(){{add(curMonth);add(preMonth);add(preTwoMonth);}};

        /**
         * 获取某集团下指定月度下(当月N,上月N-1,上上月N-2)所有人的绩效数据
         * kpi_pool 表 UNIQUE KEY `pool_kpi_id_user_id_monthly_uindex` (`kpi_group_id`,`user_id`,`monthly`),
         */
        List<KpiPool> kpiPools = kpiPoolService.list(Wrappers.<KpiPool>lambdaQuery()
                .in(KpiPool::getMonthly, yearMonths)
                .eq(KpiPool::getYn, Boolean.TRUE)
                .eq(KpiPool::getGroupId, groupId)
        );
        /**
         * 得到(当月N,上月N-1,上上月N-2)对应的各自月度的绩效人数据
         */
        Map<YearMonth, List<KpiPool>> poolMap = kpiPools.stream().collect(Collectors.groupingBy(KpiPool::getMonthly));
        List<KpiPool> curMonthPools = poolMap.getOrDefault(curMonth, new ArrayList<>());
        List<KpiPool> preMonthPools = poolMap.getOrDefault(preMonth, new ArrayList<>());
        List<KpiPool> preTwoMonthPools = poolMap.getOrDefault(preTwoMonth, new ArrayList<>());

        /**
         * 获取绩效排名组数据
         */
        List<KpiGroupRank> kpiGroupRanks = kpiGroupRankService.list(Wrappers.<KpiGroupRank>lambdaQuery()
                .eq(KpiGroupRank::getYn, Boolean.TRUE)
                .eq(KpiGroupRank::getGroupId, groupId)
        );

        GroupCalKpiRatioDTO calDTO = new GroupCalKpiRatioDTO();
        calDTO.setCurMonthPools(curMonthPools);
        calDTO.setPreMonthPools(preMonthPools);
        calDTO.setPreTwoMonthPools(preTwoMonthPools);
        calDTO.setGroupId(groupId);
        calDTO.setKpiGroupRanks(kpiGroupRanks);

        return calDTO;

    }

    /**
     * 计算管理者维度数据 (门店、绩效组)
     *
     * @param calDto
     */
    public void calManagerData(GroupCalKpiRatioDTO calDto,
                               List<KpiRatio> kpiRatios,
                               List<ShopDTO> shopDTOs,
                               Set<Long> shopIds
    ) {
        List<KpiPool> curMonthPools = calDto.getCurMonthPools();
        List<KpiPool> preMonthPools = calDto.getPreMonthPools();
        List<KpiPool> preTwoMonthPools = calDto.getPreTwoMonthPools();
        List<KpiGroup> kpiGroups = calDto.getKpiGroups();

        /**
         * 绩效组下所有 岗位 对应->门店信息 (1:N)
         */
        Map<Long, Set<Long>> kpiGroupPostShopIds = kpiGroups.stream().collect(Collectors.toMap(
                KpiGroup::getPostId, kpiGroup -> new HashSet<>(kpiGroup.getShopIds()),
                (v1, v2) -> {v1.addAll(v2);return v1;}));
        MultiKeyMap<Long, Long> kpiGroupPostShopIdMap = new MultiKeyMap<>();
        for (KpiGroup kpiGroup : kpiGroups) {
            for (Long shopId : kpiGroup.getShopIds()) {
                /**
                 * 岗位 + 门店 :-> 绩效组
                 */
                kpiGroupPostShopIdMap.put(kpiGroup.getPostId(), shopId, kpiGroup.getId());
            }
        }

        /**
         * 绩效组下所有门店对应的管理者集合
         */
        List<ManagerDTO> managerDTOS = ehrRpcService.getRealTimeShopManager(new ArrayList<>(shopIds));

        for (ManagerDTO manager : managerDTOS) {
            Map<Long, Set<Long>> createShopPostIdMap = new HashMap<>();
            Set<Long> createKpiGroupIds = new HashSet<>();

            //管理岗位
            for (ManagerStaffDTO managerStaffDTO : manager.getScopeList()) {
                Long postId = managerStaffDTO.getPostId();
                //绩效组所有岗位,只处理能匹配符合绩效组下的对应岗位的数据,不符合不处理
                if (! kpiGroupPostShopIds.keySet().contains(postId)) {
                    continue;
                }
                //管理门店
                for (ManagerStaffShopDTO shopDTO : managerStaffDTO.getShopList()) {
                    //绩效组岗位所有门店,只处理能匹配符合绩效组下的岗位对应门店的数据,不符合不处理
                    if (! kpiGroupPostShopIds.get(postId).contains(shopDTO.getShopId())) {
                        continue;
                    }

                    Long shopId = shopDTO.getShopId();
                    if (createShopPostIdMap.containsKey(shopId)) {
                        createShopPostIdMap.get(shopId).add(postId);
                    } else {
                        //门店: 多岗位 (1:N)
                        createShopPostIdMap.put(shopId, new HashSet<Long>(){{add(postId);}});
                    }

                    if (kpiGroupPostShopIdMap.containsKey(postId, shopDTO.getShopId())) {
                        createKpiGroupIds.add(kpiGroupPostShopIdMap.get(postId, shopDTO.getShopId()));
                    }
                }
            }

            //管理者门店、岗位 与 绩效组门店、岗位没有匹配
            if (PublicUtil.isEmpty(createShopPostIdMap)) {
                continue;
            }

            //管理的所有员工id集合
            Set<Long> manageStaffIds = manager.getManageStaffList().stream().map(StaffBaseInfoDTO::getId).collect(Collectors.toSet());

            kpiGroups.stream().filter(kpiGroup -> createKpiGroupIds.contains(kpiGroup.getId())).forEach(kpiGroup -> {
                KpiRatio kpiRatio = new KpiRatio(ReportDimensionEnum.MANAGER_KPI_GROUP, calDto.getGroupId());
                kpiRatio.setS1(manager.getStaffName());
                kpiRatio.setL1(manager.getStaffId());
                kpiRatio.setS4(kpiGroup.getName());
                kpiRatio.setL4(kpiGroup.getId());
                kpiRatio.setS3(kpiGroup.getPostName());
                kpiRatio.setL3(kpiGroup.getPostId());
                Predicate<KpiPool> predicate = pool -> {
                    return kpiGroup.getId().equals(pool.getKpiGroupId()) && manageStaffIds.contains(pool.getUserId())
                            && Boolean.TRUE.equals(pool.getInclusion());
                };
                kpiRatio.setB1(averageRatio(curMonthPools, predicate));
                kpiRatio.setB2(monthRatio(curMonthPools, predicate));
                kpiRatio.setB3(monthRatio(preMonthPools, predicate));
                kpiRatio.setB4(monthRatio(preTwoMonthPools, predicate));

                kpiRatio.setS8(String.join(",", kpiGroup.getShopIds().stream().map(String::valueOf).collect(Collectors.toList())));
                kpiRatios.add(kpiRatio);
            });

            Set<Long> createShopIds = createShopPostIdMap.keySet();
            shopDTOs.stream().filter(shopDTO -> createShopIds.contains(shopDTO.getId())).forEach(shopDTO -> {
                KpiRatio kpiRatio = new KpiRatio(ReportDimensionEnum.MANAGER_SHOP, calDto.getGroupId());
                Long shopId = shopDTO.getId();
                String shopName = shopDTO.getShopName();
                kpiRatio.setS1(manager.getStaffName());
                kpiRatio.setL1(manager.getStaffId());
                kpiRatio.setL2(shopId);
                kpiRatio.setS2(shopName);

                Set<Long> postIds = createShopPostIdMap.get(shopDTO.getId());
                if (PublicUtil.isNotEmpty(postIds)) {
                    kpiRatio.setS8(String.join(",", postIds.stream().map(String::valueOf).collect(Collectors.toList())));
                }

                Predicate<KpiPool> predicate = pool -> {
                    return shopId.equals(pool.getShopId()) && manageStaffIds.contains(pool.getUserId())
                            && Boolean.TRUE.equals(pool.getInclusion());
                };
                kpiRatio.setB1(averageRatio(curMonthPools, predicate));
                kpiRatio.setB2(monthRatio(curMonthPools, predicate));
                kpiRatio.setB3(monthRatio(preMonthPools, predicate));
                kpiRatio.setB4(monthRatio(preTwoMonthPools, predicate));
                kpiRatio.setB7(countStaffNum(curMonthPools, predicate));
                kpiRatios.add(kpiRatio);
            });


            KpiRatio kpiRatio = new KpiRatio(ReportDimensionEnum.MANAGER, calDto.getGroupId());
            kpiRatio.setS1(manager.getStaffName());
            kpiRatio.setL1(manager.getStaffId());
            Set<String> roleCodes = manager.getScopeList().stream()
                    .flatMap(managerStaffVo -> managerStaffVo.getRoleList().stream())
                    .map(ManagerStaffRoleDTO::getRoleCode)
                    .collect(Collectors.toSet());
            Set<String> roleNames = manager.getScopeList().stream()
                    .flatMap(managerStaffVo -> managerStaffVo.getRoleList().stream())
                    .map(ManagerStaffRoleDTO::getRoleName)
                    .collect(Collectors.toSet());
            if (PublicUtil.isNotEmpty(roleCodes)) {
                kpiRatio.setS6(String.join(",", roleCodes));
            }
            if (PublicUtil.isNotEmpty(roleNames)) {
                kpiRatio.setS7(String.join(",", roleNames));
            }
            if (PublicUtil.isNotEmpty(createShopIds)) {
                kpiRatio.setS9(String.join(",", createShopIds.stream().map(String::valueOf).collect(Collectors.toList())));
            }
            Predicate<KpiPool> predicate = pool -> {
                return manageStaffIds.contains(pool.getUserId()) && Boolean.TRUE.equals(pool.getInclusion());
            };
            kpiRatio.setB1(averageRatio(curMonthPools, predicate));
            kpiRatio.setB2(monthRatio(curMonthPools, predicate));
            kpiRatio.setB3(monthRatio(preMonthPools, predicate));
            kpiRatio.setB4(monthRatio(preTwoMonthPools, predicate));
            kpiRatios.add(kpiRatio);

        }
    }

    /**
     * 计算绩效排名组-门店维度数据
     *
     * @param calDto
     * @param kpiRatios
     */
    public void calKpiRankData(GroupCalKpiRatioDTO calDto,
                               List<KpiRatio> kpiRatios,
                               List<ShopDTO> shopDTOs
    ) {
        List<KpiPool> curMonthPools = calDto.getCurMonthPools();
        List<KpiPool> preMonthPools = calDto.getPreMonthPools();
        List<KpiPool> preTwoMonthPools = calDto.getPreTwoMonthPools();
        List<KpiGroup> kpiGroups = calDto.getKpiGroups();

        for (KpiGroupRank rank : calDto.getKpiGroupRanks()) {
            List<Long> kpiGroupIds = rank.getKpiGroupIds();
            //绩效排名组下对应的绩效组集合
            List<KpiGroup> rankKpiGroups = kpiGroups.stream()
                    .filter(kpiGroup -> kpiGroupIds.contains(kpiGroup.getId()))
                    .collect(Collectors.toList());
            Set<Long> createShopIds = rankKpiGroups.stream().flatMap(kpiGroup -> kpiGroup.getShopIds().stream()).collect(Collectors.toSet());

            shopDTOs.stream().filter(shop -> createShopIds.contains(shop.getId())).forEach(shop -> {
                KpiRatio kpiRatio = new KpiRatio(ReportDimensionEnum.KPI_RANK_SHOP, calDto.getGroupId());;

                Long shopId = shop.getId();
                Predicate<KpiPool> predicate = pool -> {
                    return shopId.equals(pool.getShopId()) && kpiGroupIds.contains(pool.getKpiGroupId()) && Boolean.TRUE.equals(pool.getInclusion());
                };
                kpiRatio.setS5(rank.getName());
                kpiRatio.setL5(rank.getId());
                kpiRatio.setL2(shopId);
                kpiRatio.setS2(shop.getShopName());
                kpiRatio.setB1(averageRatio(curMonthPools, predicate));
                kpiRatio.setB7(countStaffNum(curMonthPools, predicate));
                kpiRatio.setB2(monthRatio(curMonthPools, predicate));
                kpiRatio.setB3(monthRatio(preMonthPools, predicate));
                kpiRatio.setB4(monthRatio(preTwoMonthPools, predicate));
                kpiRatios.add(kpiRatio);
            });

            KpiRatio kpiRatio = new KpiRatio(ReportDimensionEnum.KPI_RANK, calDto.getGroupId());;
            Predicate<KpiPool> predicate = pool -> {
                return kpiGroupIds.contains(pool.getKpiGroupId()) && Boolean.TRUE.equals(pool.getInclusion());
            };
            kpiRatio.setS5(rank.getName());
            kpiRatio.setL5(rank.getId());
            if (PublicUtil.isNotEmpty(createShopIds)) {
                kpiRatio.setS9(String.join(",", createShopIds.stream().map(String::valueOf).collect(Collectors.toList())));
            }

            kpiRatio.setB1(averageRatio(curMonthPools, predicate));
            kpiRatio.setB2(monthRatio(curMonthPools, predicate));
            kpiRatio.setB3(monthRatio(preMonthPools, predicate));
            kpiRatio.setB4(monthRatio(preTwoMonthPools, predicate));
            kpiRatios.add(kpiRatio);

        }
    }

    /**
     * 计算绩效组门店维度数据
     *
     * @param calDto
     * @param kpiRatios
     */
    public void calShopData(GroupCalKpiRatioDTO calDto,
                            List<KpiRatio> kpiRatios,
                            List<ShopDTO> shopDTOs
    ) {
        List<KpiPool> curMonthPools = calDto.getCurMonthPools();
        List<KpiPool> preMonthPools = calDto.getPreMonthPools();
        List<KpiPool> preTwoMonthPools = calDto.getPreTwoMonthPools();
        List<KpiGroup> kpiGroups = calDto.getKpiGroups();

        shopDTOs.stream().forEach(shop -> {
            KpiRatio kpiRatio = new KpiRatio(ReportDimensionEnum.SHOP, calDto.getGroupId());
            Long shopId = shop.getId();
            Predicate<KpiPool> predicate = pool -> {
                return shopId.equals(pool.getShopId()) && Boolean.TRUE.equals(pool.getInclusion());
            };
            kpiRatio.setL2(shopId);
            kpiRatio.setS2(shop.getShopName());
            kpiRatio.setB1(averageRatio(curMonthPools, predicate));
            kpiRatio.setB7(countStaffNum(curMonthPools, predicate));
            kpiRatio.setB2(monthRatio(curMonthPools, predicate));
            kpiRatio.setB3(monthRatio(preMonthPools, predicate));
            kpiRatio.setB4(monthRatio(preTwoMonthPools, predicate));
            kpiRatios.add(kpiRatio);

            for (KpiGroup kpiGroup : kpiGroups) {
                List<Long> shopIds = kpiGroup.getShopIds();
                if (! shopIds.contains(shopId)) {
                    continue;
                }

                KpiRatio kpiRatioKpiGroup = new KpiRatio(ReportDimensionEnum.SHOP_KPI_GROUP, calDto.getGroupId());
                Predicate<KpiPool> predicateKpiGroup = pool -> {
                    return shopId.equals(pool.getShopId()) && kpiGroup.getId().equals(pool.getKpiGroupId()) && Boolean.TRUE.equals(pool.getInclusion());
                };
                kpiRatioKpiGroup.setL2(shopId);
                kpiRatioKpiGroup.setS2(shop.getShopName());
                kpiRatioKpiGroup.setS4(kpiGroup.getName());
                kpiRatioKpiGroup.setL4(kpiGroup.getId());
                kpiRatioKpiGroup.setB1(averageRatio(curMonthPools, predicateKpiGroup));
                kpiRatioKpiGroup.setB2(monthRatio(curMonthPools, predicateKpiGroup));
                kpiRatioKpiGroup.setB3(monthRatio(preMonthPools, predicateKpiGroup));
                kpiRatioKpiGroup.setB4(monthRatio(preTwoMonthPools, predicateKpiGroup));
                kpiRatios.add(kpiRatioKpiGroup);


            }

        });




    }

    /**
     * 计算员工维度数据
     *
     * @param calDto
     */
    public void calStaffData(GroupCalKpiRatioDTO calDto,
                           List<KpiRatio> kpiRatios
    ) {
        List<KpiPool> curMonthPools = calDto.getCurMonthPools();
        List<KpiPool> preMonthPools = calDto.getPreMonthPools();
        List<KpiPool> preTwoMonthPools = calDto.getPreTwoMonthPools();
        List<KpiGroup> kpiGroups = calDto.getKpiGroups();
        List<KpiGroupRank> kpiGroupRanks = calDto.getKpiGroupRanks();

        Map<Long, String> kpiGroupNameMap = kpiGroups.stream().collect(Collectors.toMap(KpiGroup::getId, KpiGroup::getName, (v1, v2) -> v1));
        Map<Long, KpiGroupRank> kpiGroupRankMap = new HashMap<>();
        for (KpiGroupRank rank : kpiGroupRanks) {
            for (Long kpiGroupId : rank.getKpiGroupIds()) {
                kpiGroupRankMap.put(kpiGroupId, rank);
            }
        }

        for (KpiPool pool : curMonthPools) {
            KpiRatio kpiRatio = new KpiRatio(ReportDimensionEnum.STAFF, calDto.getGroupId());;
            Long staffId = pool.getUserId();

            kpiRatio.setS1(pool.getUserName());
            kpiRatio.setS2(pool.getShopName());
            kpiRatio.setS3(pool.getPostName());
            kpiRatio.setI2(pool.getRank());
            kpiRatio.setB5(pool.getInclusion());
            kpiRatio.setI1(pool.getActualStar().getValue());
            kpiRatio.setL1(pool.getUserId());
            kpiRatio.setL2(pool.getShopId());
            kpiRatio.setL3(pool.getPostId());
            kpiRatio.setL6(pool.getId());
            kpiRatio.setL4(pool.getKpiGroupId());
            kpiRatio.setS4(kpiGroupNameMap.getOrDefault(pool.getKpiGroupId(), " "));

            if (kpiGroupRankMap.containsKey(pool.getKpiGroupId())) {
                KpiGroupRank rank = kpiGroupRankMap.get(pool.getKpiGroupId());
                kpiRatio.setL5(rank.getId());
                kpiRatio.setS5(rank.getName());
            }

            Predicate<KpiPool> predicate = poolDto -> staffId.equals(poolDto.getUserId()) && Boolean.TRUE.equals(pool.getInclusion());
            kpiRatio.setB1(averageRatio(curMonthPools, predicate));

            Optional<BigDecimal> curMonthOp = curMonthPools.stream()
                    .filter(poolDto -> poolDto.getUserId().equals(staffId) && Boolean.TRUE.equals(pool.getInclusion()))
                    .findFirst()
                    .map(KpiPool::getKpiScoreRatio);

            Optional<BigDecimal> preMonthOp = preMonthPools.stream()
                    .filter(poolDto -> poolDto.getUserId().equals(staffId) && Boolean.TRUE.equals(pool.getInclusion()))
                    .findFirst()
                    .map(KpiPool::getKpiScoreRatio);

            Optional<BigDecimal> preTwoMonthOp = preTwoMonthPools.stream()
                    .filter(poolDto -> poolDto.getUserId().equals(staffId) && Boolean.TRUE.equals(pool.getInclusion()))
                    .findFirst()
                    .map(KpiPool::getKpiScoreRatio);

            if (curMonthOp.isPresent()) {
                kpiRatio.setB2(curMonthOp.get().multiply(new BigDecimal("100")).setScale(2, RoundingMode.DOWN));
            }
            if (preMonthOp.isPresent()) {
                kpiRatio.setB3(preMonthOp.get().multiply(new BigDecimal("100")).setScale(2, RoundingMode.DOWN));
            }
            if (preTwoMonthOp.isPresent()) {
                kpiRatio.setB4(preTwoMonthOp.get().multiply(new BigDecimal("100")).setScale(2, RoundingMode.DOWN));
            }

            kpiRatios.add(kpiRatio);
        }
    }

    /**
     * 绩效池平均绩效得分率
     *
     * @param pools
     * @return
     */
    public BigDecimal countStaffNum(Collection<KpiPool> pools, Predicate<KpiPool> predicate) {
        if (CollectionUtils.isEmpty(pools)) {
            return BigDecimal.ZERO;
        }
        Long staffNum = pools.stream()
                .filter(predicate)
                .count();
        return new BigDecimal(staffNum);
    }

    /**
     * 绩效池平均绩效得分率
     *
     * @param pools
     * @return
     */
    public BigDecimal averageRatio(Collection<KpiPool> pools, Predicate<KpiPool> predicate) {
        if (CollectionUtils.isEmpty(pools)) {
            return BigDecimal.ZERO;
        }
        Double averageRatioDouble = pools.stream()
                .filter(predicate)
                .mapToDouble(r -> Optional.ofNullable(r.getAverageKpiScoreRatio()).orElse(BigDecimal.ZERO).doubleValue())
                .average()
                .orElse(0);
        BigDecimal averageRatio = new BigDecimal(averageRatioDouble.toString());
        return averageRatio.multiply(new BigDecimal("100")).setScale(2, RoundingMode.DOWN);
    }

    /**
     * 当月绩效池平均绩效得分率
     *
     * @param pools
     * @return
     */
    public BigDecimal monthRatio(Collection<KpiPool> pools, Predicate<KpiPool> predicate) {
        if (CollectionUtils.isEmpty(pools)) {
            return BigDecimal.ZERO;
        }
        Double averageRatioDouble = pools.stream()
                .filter(predicate)
                .mapToDouble(r -> Optional.ofNullable(r.getKpiScoreRatio()).orElse(BigDecimal.ZERO).doubleValue())
                .average()
                .orElse(0);
        BigDecimal averageRatio = new BigDecimal(averageRatioDouble.toString());
        return averageRatio.multiply(new BigDecimal("100")).setScale(2, RoundingMode.DOWN);
    }

}