KpiPoolBizService.java 45.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 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004
package cn.fw.morax.service.biz.kpi;

import cn.fw.common.exception.BusinessException;
import cn.fw.common.web.annotation.DisLock;
import cn.fw.morax.common.constant.Constant;
import cn.fw.morax.common.utils.DateUtil;
import cn.fw.morax.common.utils.MessageFormatUtil;
import cn.fw.morax.common.utils.PublicUtil;
import cn.fw.morax.common.utils.StringUtils;
import cn.fw.morax.domain.bo.kpi.KpiGroupCalculableBO;
import cn.fw.morax.domain.bo.kpi.KpiGroupCalculableRankBO;
import cn.fw.morax.domain.bo.kpi.KpiRankCalculableBO;
import cn.fw.morax.domain.bo.kpi.KpiStarLadderBO;
import cn.fw.morax.domain.db.kpi.*;
import cn.fw.morax.domain.dto.kpi.KpiGroupRankConfigQueryDTO;
import cn.fw.morax.domain.enums.*;
import cn.fw.morax.domain.vo.kpi.*;
import cn.fw.morax.service.data.kpi.*;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.BoundZSetOperations;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.lang.NonNull;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.time.LocalDate;
import java.time.YearMonth;
import java.util.*;
import java.util.stream.Collectors;

import static cn.fw.common.businessvalidator.Validator.BV;
import static cn.fw.morax.common.utils.MessageFormatUtil.MessageFormatTransfer;

/**
 * 绩效池业务处理服务
 *
 * @author kurisu
 */
@RequiredArgsConstructor
@Service
@Slf4j
public class KpiPoolBizService {

    private final KpiPoolService kpiPoolService;
    private final KpiGroupService kpiGroupService;
    private final KpiStarRuleService kpiStarRuleService;
    private final KpiGroupRankService kpiGroupRankService;
    private final StringRedisTemplate stringRedisTemplate;
    private final KpiGroupUserService kpiGroupUserService;
    private final KpiRewardPointService kpiRewardPointService;
    private final KpiStarLaddersService kpiStarLaddersService;
    private final KpiGroupIndicatorService kpiGroupIndicatorService;
    private final KpiGroupIndicatorHitLogService kpiGroupIndicatorHitLogService;
    private final KpiPoolIndicatorValueService kpiPoolIndicatorValueService;
    private final KpiGroupRankStarLaddersService kpiGroupRankStarLaddersService;
    private final KpiGroupIndicatorLaddersService kpiGroupIndicatorLaddersService;
    private final KpiAssessPenaltyStaffService kpiAssessPenaltyStaffService;
    private final KpiAssessPenaltyService kpiAssessPenaltyService;
    private final ReportKpiRankService reportKpiRankService;

    @Value("${spring.cache.custom.global-prefix}:calculate-scoring-rate:kpi-group")
    @Getter
    private String calcuScoringRateKey;

    @Value("${spring.cache.custom.global-prefix}:calculate-star-level:kpi-group")
    @Getter
    private String calcuStarKey;

    @Value("${spring.cache.custom.global-prefix}:scoring-rate:short-key")
    @Getter
    private String prefixShortKey;

    /**
     * 计算绩效组得分率
     */
    public void calcuScoringRate() {
        ListOperations<String, String> listOps = stringRedisTemplate.opsForList();
        List<String> errList = new ArrayList<>();
        String jsonStr;
        while ((jsonStr = listOps.leftPop(getCalcuScoringRateKey())) != null) {
            if (StringUtils.isEmpty(jsonStr)) {
                continue;
            }
            KpiGroupCalculableBO calculableBO = JSONObject.parseObject(jsonStr, KpiGroupCalculableBO.class);
            if (Objects.isNull(calculableBO)) {
                continue;
            }
            try {
                calcuScoringRate(calculableBO);
            } catch (Exception ex) {
                log.error("计算绩效组得分率失败:[{}]", jsonStr, ex);
                errList.add(jsonStr);
            }
        }
        if (!CollectionUtils.isEmpty(errList)) {
            listOps.rightPushAll(getCalcuScoringRateKey(), errList);
        }
    }

    /**
     * 计算绩效组得分率
     *
     * @param bo 绩效组信息和日期
     */
    @Transactional(rollbackFor = Exception.class)
    public void calcuScoringRate(final KpiGroupCalculableBO bo) {
        Long kpiGroupId = bo.getKpiGroupId();
        LocalDate localDate = bo.getLocalDate();
        KpiGroup kpiGroup = kpiGroupService.getById(kpiGroupId);
        BV.notNull(kpiGroup, () -> "绩效组配置不存在");
        List<KpiPool> poolList = kpiPoolService.list(Wrappers.<KpiPool>lambdaQuery()
                .eq(KpiPool::getKpiGroupId, kpiGroupId)
                .eq(KpiPool::getMonthly, YearMonth.from(localDate))
                .eq(KpiPool::getYn, Boolean.TRUE)
        );
        if (CollectionUtils.isEmpty(poolList)) {
            log.error("绩效池查无数据:[{}] [{}]", kpiGroupId, localDate);
            return;
        }
        List<KpiGroupIndicator> indicators = kpiGroupIndicatorService.list(Wrappers.<KpiGroupIndicator>lambdaQuery()
                .eq(KpiGroupIndicator::getKpiGroupId, kpiGroupId)
                .eq(KpiGroupIndicator::getYn, Boolean.TRUE)
        );
        final BigDecimal totalScore = indicators.stream().map(indicator -> BigDecimal.valueOf(indicator.getBaseScore()))
                .reduce(BigDecimal.ZERO, BigDecimal::add);

        KpiStarRule starRule = kpiStarRuleService.getOne(Wrappers.<KpiStarRule>lambdaQuery()
                        .eq(KpiStarRule::getGroupId, kpiGroup.getGroupId())
                        .eq(KpiStarRule::getYn, Boolean.TRUE)
                , Boolean.FALSE);
        BV.notNull(starRule, () -> "星级规则配置不存在");
        int rollMonth = Optional.ofNullable(starRule.getRollMonth()).orElse(3);

        for (KpiPool pool : poolList) {
            BigDecimal kpiScore = Optional.ofNullable(pool.getKpiScore()).orElse(BigDecimal.ZERO);
            BigDecimal kpiScoreRatio = kpiScore.divide(totalScore, 4, RoundingMode.HALF_UP);
            pool.setKpiScoreRatio(kpiScoreRatio);
            calcAverageRatio(pool,rollMonth);
        }
        kpiPoolService.updateBatchById(poolList);
    }


    /**
     * 计算绩效组人员星级
     */
    public void calcuStarLevel() {
        ListOperations<String, String> listOps = stringRedisTemplate.opsForList();
        List<String> errList = new ArrayList<>();
        String jsonStr;
        while ((jsonStr = listOps.leftPop(getCalcuStarKey())) != null) {
            if (StringUtils.isValid(jsonStr)) {
                KpiGroupCalculableRankBO calculableBO = JSONObject.parseObject(jsonStr, KpiGroupCalculableRankBO.class);
                if (Objects.nonNull(calculableBO)) {
                    try {
                        calcuStarLevel(calculableBO);
                    } catch (Exception ex) {
                        log.error("计算绩效星级失败:[{}]", jsonStr, ex);
                        errList.add(jsonStr);
                    }
                }
            }
        }
        if (!CollectionUtils.isEmpty(errList)) {
            listOps.rightPushAll(getCalcuStarKey(), errList);
        }
    }


    /**
     * 计算星级、排名
     *
     * @param bo
     */
    @Transactional(rollbackFor = Exception.class)
    public void calcuStarLevel(KpiGroupCalculableRankBO bo) {
        final List<Long> kpiGroupIds = bo.getKpiGroupIds();
        final LocalDate localDate = bo.getLocalDate();
        final BigDecimal revokedScoreRatio = bo.getRevokedScoreRatio();
        List<KpiGroup> kpiGroups = kpiGroupService.listByIds(kpiGroupIds);
        BV.notNull(kpiGroups, () -> "绩效组配置不能为空");

        KpiRankCalculableBO calculableBO = getStarConfig(bo, kpiGroups);
        StarEvaluationEnum starEvaluationType = calculableBO.getStarEvaluationType();

        // 查询绩效组下所有人的绩效池信息
        List<KpiPool> poolList = kpiPoolService.list(Wrappers.<KpiPool>lambdaQuery()
                .in(KpiPool::getKpiGroupId, kpiGroupIds)
                .eq(KpiPool::getMonthly, YearMonth.from(localDate))
                .eq(KpiPool::getYn, Boolean.TRUE)
        );
        if (CollectionUtils.isEmpty(poolList)) {
            return;
        }

        if (StarEvaluationEnum.SCORING_RATE.equals(starEvaluationType)) {
            for (KpiPool kpiPool : poolList) {
                if (!Boolean.TRUE.equals(kpiPool.getInclusion())) {
                    kpiPool.setStarLevel(StarLevelEnum.C);
                    kpiPool.setActualStar(StarLevelEnum.C);
                    continue;
                }
                calcRatioStarLevel(kpiPool, calculableBO.getStarLadders());
            }
        } else if (StarEvaluationEnum.PERSONNEL_RATE.equals(starEvaluationType)) {
            calcRateStarLevel(kpiGroups, poolList, calculableBO);
        }

        if (Objects.nonNull(revokedScoreRatio) && BigDecimal.ZERO.compareTo(revokedScoreRatio) < 0) {
            for (KpiPool pool : poolList) {
                BigDecimal kpiScore = pool.getKpiScore();
                StarLevelEnum actualStar = pool.getActualStar();
                if (kpiScore.compareTo(revokedScoreRatio) >= 0 && StarLevelEnum.D.equals(actualStar)) {
                    pool.setActualStar(StarLevelEnum.C);
                }
            }
        }
        //计算排名
        calcRank(poolList);
        calcActualRank(bo, poolList, kpiGroupIds);

        kpiPoolService.updateBatchById(poolList);
    }

    /**
     * 按绩效得分率
     */
    private void calcRatioStarLevel(KpiPool kpiPool, List<KpiStarLadderBO> startLadders) {
        final BigDecimal average = kpiPool.getAverageKpiScoreRatio();
        KpiStarLadderBO ladder = startLadders.stream()
                .filter(r -> average.compareTo(r.getLower()) >= 0)
                .filter(a -> average.compareTo(a.getUpper()) < 0)
                .findFirst()
                .orElseThrow(() -> new BusinessException("未找到对应阶梯值"));

        kpiPool.setStarLevel(ladder.getLevel());
        kpiPool.setActualStar(ladder.getLevel());
    }

    /**
     * 按人员数量
     */
    private void calcRateStarLevel(List<KpiGroup> kpiGroups, List<KpiPool> poolList, KpiRankCalculableBO calculableBO) {
        List<KpiStarLadderBO> startLadders = calculableBO.getStarLadders();
        BigDecimal revokedScoreRatio = calculableBO.getRevokedScoreRatio();
        String kgcStr = kpiGroups.stream().map(KpiGroup::getKgc).collect(Collectors.joining("-"));
        String key = getShortKey(kgcStr);
        BoundZSetOperations<String, String> zSetOps = stringRedisTemplate.boundZSetOps(key);
        stringRedisTemplate.expireAt(key, DateUtil.localDate2Date(LocalDate.now().plusDays(1L)));
        for (KpiPool kpiPool : poolList) {
            if (!Boolean.TRUE.equals(kpiPool.getInclusion())) {
                kpiPool.setStarLevel(StarLevelEnum.C);
                kpiPool.setActualStar(StarLevelEnum.C);
                continue;
            }
            zSetOps.add(kpiPool.getId().toString(), kpiPool.getAverageKpiScoreRatio().doubleValue());
        }
        Map<StarLevelEnum, KpiStarLadderBO> map = new HashMap<>(StarLevelEnum.values().length);
        for (KpiStarLadderBO ladder : startLadders) {
            map.put(ladder.getLevel(), ladder);
        }

        Map<String, StarLevelEnum> starLevelSetMap = calcPersonRateStarLevel(zSetOps, map, poolList, revokedScoreRatio);
        if (!CollectionUtils.isEmpty(starLevelSetMap)) {
            for (KpiPool pool : poolList) {
                if (!Boolean.TRUE.equals(pool.getInclusion())) {
                    continue;
                }
                Long poolId = pool.getId();
                StarLevelEnum starLevel = Optional.ofNullable(starLevelSetMap.get(String.valueOf(poolId))).orElse(StarLevelEnum.C);
                pool.setStarLevel(starLevel);
                pool.setActualStar(starLevel);
            }
        }
        stringRedisTemplate.delete(key);
    }

    /**
     * 按人数百分比计算等级
     *
     * @param zSetOps
     * @param map
     */
    private Map<String, StarLevelEnum> calcPersonRateStarLevel(BoundZSetOperations<String, String> zSetOps,
                                                               Map<StarLevelEnum, KpiStarLadderBO> map,
                                                               List<KpiPool> pools, BigDecimal revokedScoreRatio) {
        final Long personCount = zSetOps.size();
        if (Objects.isNull(personCount) || Objects.equals(personCount, 0L)) {
            return null;
        }
        Map<String, StarLevelEnum> levelIdMap = new HashMap<>();

        KpiStarLadderBO aladder = map.get(StarLevelEnum.A);
        BV.notNull(aladder, () -> "星级A阶梯配置不存在");
        BigDecimal upper = aladder.getUpper();
        int ai = upper.multiply(BigDecimal.valueOf(personCount)).divide(BigDecimal.ONE, 0, RoundingMode.FLOOR).intValue();
        if (ai > 0) {
            assembleLevelIdMap(levelIdMap, StarLevelEnum.A, zSetOps.reverseRange(0, ai - 1));

        }

        KpiStarLadderBO bladder = map.get(StarLevelEnum.B);
        BV.notNull(bladder, () -> "星级B阶梯配置不存在");
        BigDecimal bupper = bladder.getUpper();
        int bi = bupper.multiply(BigDecimal.valueOf(personCount)).divide(BigDecimal.ONE, 0, RoundingMode.FLOOR).intValue();
        if (bi > ai) {
            assembleLevelIdMap(levelIdMap, StarLevelEnum.B, zSetOps.reverseRange(ai, bi - 1));
        }

        KpiStarLadderBO dladder = map.get(StarLevelEnum.D);
        BV.notNull(dladder, () -> "星级D阶梯配置不存在");
        BigDecimal lower = dladder.getLower();
        int di = lower.multiply(BigDecimal.valueOf(personCount)).divide(BigDecimal.ONE, 0, RoundingMode.CEILING).intValue();
        if (di < personCount) {
            Set<String> poolIds = zSetOps.reverseRange(di, -1);
            if (PublicUtil.isEmpty(revokedScoreRatio) || (BigDecimal.ZERO.compareTo(revokedScoreRatio) == 0)) {
                assembleLevelIdMap(levelIdMap, StarLevelEnum.D, poolIds);
            } else {
                Map<String, BigDecimal> poolMap = pools.stream().collect(Collectors.toMap(pool -> pool.getId().toString(), KpiPool::getAverageKpiScoreRatio));
                Set<String> notRevokedIds = poolIds.stream().filter(poolId ->
                        poolMap.get(poolId).compareTo(revokedScoreRatio) < 0
                ).collect(Collectors.toSet());
                assembleLevelIdMap(levelIdMap, StarLevelEnum.D, notRevokedIds);
            }
        }
        return levelIdMap;
    }

    /**
     * 计算滚动月份平均得分率
     *
     * @param kpiPool
     * @param rollMonth
     * @return
     */
    private void calcAverageRatio(KpiPool kpiPool, int rollMonth) {
        //未纳入绩效考核人员也计算平均得分率,返回当月绩效完成率
        if (Boolean.FALSE.equals(kpiPool.getInclusion())) {
            kpiPool.setAverageKpiScoreRatio(Optional.ofNullable(kpiPool.getKpiScoreRatio()).orElse(BigDecimal.ZERO));
            kpiPool.setLastOneKpiScoreRatio(BigDecimal.ZERO);
            kpiPool.setLastTwoKpiScoreRatio(BigDecimal.ZERO);
            return;
        }
        List<KpiPool> poolList = kpiPoolService.list(Wrappers.<KpiPool>lambdaQuery()
                .eq(KpiPool::getUserId, kpiPool.getUserId())
                .eq(KpiPool::getPostId, kpiPool.getPostId())
                .eq(KpiPool::getInclusion, Boolean.TRUE)
                .le(KpiPool::getCreateTime, kpiPool.getCreateTime())
                .eq(KpiPool::getYn, Boolean.TRUE)
                .orderByDesc(KpiPool::getCreateTime)
                .last(MessageFormatUtil.MessageFormatTransfer(" limit  {0}", rollMonth))
        );
        double averageKpiScoreRatio = poolList.stream()
                .mapToDouble(r -> Optional.ofNullable(r.getKpiScoreRatio()).orElse(BigDecimal.ZERO).doubleValue())
                .average()
                .orElse(0);
        kpiPool.setAverageKpiScoreRatio(BigDecimal.valueOf(averageKpiScoreRatio));
        YearMonth lastMonth = kpiPool.getMonthly().minusMonths(1);
        YearMonth preTwoMonth = kpiPool.getMonthly().minusMonths(2);
        BigDecimal lastMonthRatio = poolList.stream()
                .filter(pool -> lastMonth.compareTo(pool.getMonthly()) == 0).findFirst()
                .map(KpiPool::getKpiScoreRatio).orElse(BigDecimal.ZERO);
        BigDecimal preTwoMonthRatio = poolList.stream()
                .filter(pool -> preTwoMonth.compareTo(pool.getMonthly()) == 0).findFirst()
                .map(KpiPool::getKpiScoreRatio).orElse(BigDecimal.ZERO);
        kpiPool.setLastOneKpiScoreRatio(lastMonthRatio);
        kpiPool.setLastTwoKpiScoreRatio(preTwoMonthRatio);
    }


    /**
     * 计算排名
     *
     * @param poolList
     */
    public void calcRank(List<KpiPool> poolList) {
        if (PublicUtil.isEmpty(poolList)) {
            return;
        }
        List<KpiPool> pools = poolList.stream()
                .filter(pool -> Boolean.TRUE.equals(pool.getInclusion()))
                .sorted(Comparator.comparing(KpiPool::getAverageKpiScoreRatio, BigDecimal::compareTo).reversed())
                .collect(Collectors.toList());

        int rank = 1;
        BigDecimal lastKpiScoreRatio = null;
        for (KpiPool pool : pools) {
            if (PublicUtil.isNotEmpty(lastKpiScoreRatio) && (lastKpiScoreRatio.compareTo(pool.getAverageKpiScoreRatio()) != 0)) {
                rank++;
            }
            pool.setRank(rank);
            lastKpiScoreRatio = pool.getAverageKpiScoreRatio();
        }

        //本月绩效排名
        List<KpiPool> pools2 = poolList.stream()
                .filter(pool -> Boolean.TRUE.equals(pool.getInclusion()))
                .sorted(Comparator.comparing(KpiPool::getKpiScoreRatio, BigDecimal::compareTo).reversed())
                .collect(Collectors.toList());

        int rank2 = 1;
        BigDecimal lastKpiScoreRatio2 = null;
        for (KpiPool pool : pools2) {
            if (PublicUtil.isNotEmpty(lastKpiScoreRatio2) && (lastKpiScoreRatio2.compareTo(pool.getKpiScoreRatio()) != 0)) {
                rank2++;
            }
            pool.setMonthRank(rank2);
            lastKpiScoreRatio2 = pool.getKpiScoreRatio();
        }
    }

    /**
     * 计算转正保护期、正式员工排名排名
     *
     * @param poolList
     */
    public void calcActualRank(KpiGroupCalculableRankBO bo, List<KpiPool> poolList, List<Long> kpiGroupIds) {
        if (Boolean.FALSE.equals(bo.getFinalCalc()) || PublicUtil.isEmpty(poolList)) {
            return;
        }
        LocalDate localDate = bo.getLocalDate();
        List<KpiGroupUser> turnPositiveUsers = kpiGroupUserService.list(Wrappers.<KpiGroupUser>lambdaQuery()
                .in(KpiGroupUser::getKpiGroupId, kpiGroupIds)
                .eq(KpiGroupUser::getIgnored, Boolean.TRUE)
                .eq(KpiGroupUser::getIgnoreCause, KpiIgnoreCauseEnum.TURN_POSITIVE_AFTER)
                .eq(KpiGroupUser::getDataDate, localDate)
                .eq(KpiGroupUser::getYn, Boolean.TRUE)
        );
        Set<Long> turnPositiveUserIds = turnPositiveUsers.stream().map(KpiGroupUser::getUserId).collect(Collectors.toSet());
        //转正保护期员工一起排名
        List<KpiPool> pools = poolList.stream()
                .filter(pool -> {
                    return Boolean.TRUE.equals(pool.getInclusion()) || (turnPositiveUserIds.contains(pool.getUserId()));
                })
                .sorted(Comparator.comparing(KpiPool::getAverageKpiScoreRatio, BigDecimal::compareTo).reversed())
                .collect(Collectors.toList());

        int rank = 1;
        BigDecimal lastKpiScoreRatio = null;
        for (KpiPool pool : pools) {
            if (PublicUtil.isNotEmpty(lastKpiScoreRatio) && (lastKpiScoreRatio.compareTo(pool.getAverageKpiScoreRatio()) != 0)) {
                rank++;
            }
            pool.setAssessRank(rank);
            lastKpiScoreRatio = pool.getAverageKpiScoreRatio();
        }
    }

    /**
     * 生成排序key
     *
     * @param key
     * @return
     */
    private String getShortKey(@NonNull String key) {
        return String.format("%s:%s", getPrefixShortKey(), key);
    }


    /**
     * 组装id对应等级
     *
     * @param levelIdMap
     * @param level
     * @param ids
     */
    private void assembleLevelIdMap(Map<String, StarLevelEnum> levelIdMap, StarLevelEnum level, Set<String> ids) {
        if (CollectionUtils.isNotEmpty(ids)) {
            for (String s : ids) {
                levelIdMap.put(s, level);
            }
        }
    }

    /**
     * 失效用户所有绩效池
     * 不参与滚动计算平均三个月绩效得分率,不纳入D级次数计算。场景:
     * 1, 用户申请重新计算绩效考核
     * 2. 调岗
     * 3. 待岗
     *
     * @param userId
     */
    @Transactional(rollbackFor = Exception.class)
    public void invalidKpiPool(KpiGroup originKpiGroup, Long userId, LocalDate anticipatedDate) {
        KpiGroupUser groupUser = kpiGroupUserService.getOne(Wrappers.<KpiGroupUser>lambdaQuery()
                .eq(KpiGroupUser::getKgc, originKpiGroup.getKgc())
                .eq(KpiGroupUser::getUserId, userId)
                .eq(KpiGroupUser::getDataDate, LocalDate.now())
                .eq(KpiGroupUser::getYn, Boolean.TRUE)
        );
        if (PublicUtil.isNotEmpty(groupUser)) {
            groupUser.setIgnored(Boolean.TRUE);
            if (PublicUtil.isNotEmpty(anticipatedDate)) {
                groupUser.setAnticipatedDate(anticipatedDate);
            }
            groupUser.setIgnoreCause(KpiIgnoreCauseEnum.TRANSFER_NEW_POSITION_AFTER);
            groupUser.setIgnoreCauseDesc(KpiIgnoreCauseEnum.TRANSFER_NEW_POSITION_AFTER.getName());
            kpiGroupUserService.updateById(groupUser);
        }

        kpiPoolService.update(Wrappers.<KpiPool>lambdaUpdate()
                .set(KpiPool::getInclusion, Boolean.FALSE)
                .set(KpiPool::getRank, null)
                .eq(KpiPool::getUserId, userId)
                .eq(KpiPool::getMonthly, YearMonth.now())
                .eq(KpiPool::getInclusion, Boolean.TRUE)
        );
    }

    /**
     * 失效用户所有绩效得分率。场景:
     * 1, 用户申请重新计算绩效考核
     * 2. 调岗
     * 3. 待岗
     *
     * @param userId
     */
    @Transactional(rollbackFor = Exception.class)
    public void adjustmentKpiPool(Long userId, StarLevelEnum starLevelEnum, YearMonth yearMonth) {
        Boolean result = kpiPoolService.update(Wrappers.<KpiPool>lambdaUpdate()
                .set(KpiPool::getActualStar, starLevelEnum)
                .eq(KpiPool::getUserId, userId)
                .eq(KpiPool::getMonthly, yearMonth)
        );
        BV.isTrue(result, "绩效池是否纳入绩效计算修改失败");
    }

    /**
     * 查询薪酬池详情
     *
     * @param poolId 薪酬池id
     * @return 薪酬池详情
     */
    public KpiPoolDetailVO queryPoolDetail(final Long poolId, YearMonth yearMonth) {
        KpiPool pool = kpiPoolService.getById(poolId);
//        boolean flag = Objects.nonNull(pool) && Boolean.TRUE.equals(pool.getYn());
//        BV.isTrue(flag, () -> "该人员绩效数据不存在");
        if (PublicUtil.isEmpty(pool)) {
            return null;
        }
        if (PublicUtil.isNotEmpty(yearMonth) && (!yearMonth.equals(pool.getMonthly()))) {
            List<KpiPool> list = userSalaryPool(pool.getUserId(), yearMonth);
//            BV.isNotEmpty(list, () -> "人员薪酬数据不存在");
            if (PublicUtil.isEmpty(list)) {
                return null;
            }
            pool = list.get(0);
        }
        return getPoolDetail(pool);
    }

    /**
     * 查询薪酬池详情
     *
     * @param userId    用户id
     * @param yearMonth 月度
     * @return 薪酬池详情
     */
    public KpiPoolDetailVO queryUserPoolDetail(final Long userId, final YearMonth yearMonth) {
        List<KpiPool> list = userSalaryPool(userId, yearMonth);
//        BV.isNotEmpty(list, () -> "人员薪酬数据不存在");
        if (PublicUtil.isEmpty(list)) {
            return null;
        }
        KpiPool kpiPool = list.get(0);
        return getPoolDetail(kpiPool);
    }

    /**
     * 绩效池详情构建
     *
     * @param kpiPool
     * @return
     */
    private KpiPoolDetailVO getPoolDetail(KpiPool kpiPool) {
        Long userId = kpiPool.getUserId();
        Long kpiPoolId = kpiPool.getId();
        Long kpiGroupId = kpiPool.getKpiGroupId();
        KpiPoolDetailVO kpiPoolDetailVo = PublicUtil.copy(kpiPool, KpiPoolDetailVO.class);
        //奖惩绩效分
//        this.processRewardPoint(kpiPool, kpiPoolDetailVo);
        //近一年绩效情况
        List<KpiPool> kpiPools = kpiPoolService.list(Wrappers.<KpiPool>lambdaQuery()
                .ge(KpiPool::getMonthly, kpiPool.getMonthly().minusMonths(12L))
                .eq(KpiPool::getUserId, userId)
                .eq(KpiPool::getInclusion, Boolean.TRUE)
                .eq(KpiPool::getYn, Boolean.TRUE)
                .orderByDesc(KpiPool::getMonthly)
        );
        if (PublicUtil.isNotEmpty(kpiPools)) {
            List<KpiPoolDetailVO> kpis = PublicUtil.copyList(kpiPools, KpiPoolDetailVO.class);
            kpis.stream().forEach(KpiPoolDetailVO::convertToPercent);
            kpiPoolDetailVo.setKpis(kpis);
        }
        buildPoolData(kpiPool, kpiPoolDetailVo);
        LocalDate dataDate = LocalDate.from(kpiPoolDetailVo.getEndTime());

        kpiPoolDetailVo.setTotalScore(this.getKpiGroupIndicatorTotalScore(kpiGroupId));
        kpiPoolDetailVo.setKpiScoreRatio(kpiPoolDetailVo.getKpiScoreRatio().multiply(Constant.ONE_HUNDRED));
        this.setRewardPunish(kpiPool, kpiPoolDetailVo);
        this.setIndicatorVos(kpiPoolId, kpiGroupId, dataDate, kpiPoolDetailVo);
        this.setAssess(kpiPoolDetailVo);
        return kpiPoolDetailVo;
    }

    public void setRewardPunish(KpiPool pool, KpiPoolDetailVO kpiPoolDetailVO) {
        List<KpiRewardPoint> rewardPoints = kpiRewardPointService.list(Wrappers.<KpiRewardPoint>lambdaQuery()
                .eq(KpiRewardPoint::getUserId, pool.getUserId())
                .eq(KpiRewardPoint::getPostId, pool.getPostId())
                .eq(KpiRewardPoint::getShopId, pool.getShopId())
                .eq(KpiRewardPoint::getMonthly, pool.getMonthly())
                .le(KpiRewardPoint::getCreateTime, kpiPoolDetailVO.getEndTime())
                .eq(KpiRewardPoint::getGroupId, pool.getGroupId())
        );

        //计算分数时将
        BigDecimal rewardScore = BigDecimal.ZERO;
        BigDecimal punishScore = BigDecimal.ZERO;
        for (KpiRewardPoint point : rewardPoints) {
            if (BigDecimal.ZERO.compareTo(point.getScorePoint()) > 0) {
                punishScore = punishScore.add(point.getScorePoint());
            } else {
                rewardScore = rewardScore.add(point.getScorePoint());
            }
        }
        //奖励分正数、惩罚分负数,减去奖惩分数,得到原始分数
        BigDecimal originKpiScore = pool.getKpiScore().subtract(rewardScore).subtract(punishScore);
        if (BigDecimal.ZERO.compareTo(originKpiScore) > 0) {
            originKpiScore = BigDecimal.ZERO;
        }
        kpiPoolDetailVO.setRewardScore(rewardScore);
        kpiPoolDetailVO.setPunishScore(punishScore.abs());
        kpiPoolDetailVO.setRealKpiScore(pool.getKpiScore());
        kpiPoolDetailVO.setOriginKpiScore(originKpiScore);

        kpiPoolDetailVO.setRewards(new ArrayList<>());
        kpiPoolDetailVO.setPunishments(new ArrayList<>());
        rewardPoints.stream().forEach(point -> {
            KpiRewardPointVO pointVO = PublicUtil.copy(point, KpiRewardPointVO.class);
            pointVO.setExpectation(Boolean.FALSE);
            if (point.getScorePoint().compareTo(BigDecimal.ZERO) > 0) {
                kpiPoolDetailVO.getRewards().add(pointVO);
            }
            if (point.getScorePoint().compareTo(BigDecimal.ZERO) < 0) {
                pointVO.setScorePoint(pointVO.getScorePoint().abs());
                kpiPoolDetailVO.getPunishments().add(pointVO);
            }
        });
    }

    public void setIndicatorVos(Long kpiPoolId, Long kpiGroupId, LocalDate dataDate, KpiPoolDetailVO kpiPoolDetailVo) {
        DecimalFormat decimalFormat = new DecimalFormat("##########.##");
        List<KpiPoolIndicatorValueVO> indicatorValueVOS = kpiPoolIndicatorValueService.getStaffIndicatorValue(kpiPoolId, kpiGroupId, dataDate);
        for (KpiPoolIndicatorValueVO indicatorValueVO : indicatorValueVOS) {
            indicatorValueVO.setIndicatorScoreFormat(decimalFormat.format(indicatorValueVO.getIndicatorScore()));

            BigDecimal indicatorScoreRatio = indicatorValueVO.getIndicatorScore().divide(indicatorValueVO.getBaseScore(), 2, RoundingMode.DOWN);
            indicatorScoreRatio = indicatorScoreRatio.multiply(Constant.ONE_HUNDRED);
            indicatorValueVO.setIndicatorScoreRatio(decimalFormat.format(indicatorScoreRatio));
//            BigDecimal lossIndicatorScoreRatio = (Constant.ONE_HUNDRED.compareTo(indicatorScoreRatio) > 0) ?
//                    BigDecimal.ZERO : Constant.ONE_HUNDRED.subtract(indicatorScoreRatio);
//            indicatorValueVO.setLossIndicatorScoreRatio(decimalFormat.format(lossIndicatorScoreRatio));
        }
        kpiPoolDetailVo.setKpiValues(indicatorValueVOS);
    }

    public void setAssess(KpiPoolDetailVO kpiPoolDetailVo) {
        if (! LocalDate.now().minusDays(1L).equals(LocalDate.from(kpiPoolDetailVo.getEndTime()))) {
            return;
        }
        List<KpiAssessPenalty> penalties = kpiAssessPenaltyService.list(Wrappers.<KpiAssessPenalty>lambdaQuery()
                .eq(KpiAssessPenalty::getUserId, kpiPoolDetailVo.getUserId())
                .eq(KpiAssessPenalty::getDataDate, LocalDate.from(kpiPoolDetailVo.getEndTime()))
                .eq(KpiAssessPenalty::getExpectedPenalty, Boolean.TRUE)
                .eq(KpiAssessPenalty::getYn, Boolean.TRUE)
        );
        Map<KpiAssessTypeEnum, List<KpiAssessPenalty>> typeMap = penalties.stream().collect(Collectors.groupingBy(KpiAssessPenalty::getType));
        for (Map.Entry<KpiAssessTypeEnum, List<KpiAssessPenalty>> entry : typeMap.entrySet()) {
            BigDecimal score = entry.getValue().stream().map(KpiAssessPenalty::getScore).reduce(BigDecimal.ZERO, BigDecimal::add);
            if (BigDecimal.ZERO.compareTo(score) == 0) {
                continue;
            }
            KpiRewardPointVO point = new KpiRewardPointVO();
            point.setExpectation(Boolean.TRUE);
            point.setTypeName(entry.getKey().getName());
            point.setDataId(entry.getKey().getValue().toString());

            //奖励
            if (score.compareTo(BigDecimal.ZERO) > 0) {
                point.setScorePoint(score);
                kpiPoolDetailVo.getRewards().add(point);
            } else {
                point.setScorePoint(score.abs());
                kpiPoolDetailVo.getPunishments().add(point);
            }
        }
    }

    /**
     * 获取奖惩绩效分
     *
     * @param pool
     */
//    public void processRewardPoint(KpiPool pool, KpiPoolDetailVO poolDetailVO) {
//        List<KpiRewardPoint> list = kpiRewardPointService.list(Wrappers.<KpiRewardPoint>lambdaQuery()
//                .eq(KpiRewardPoint::getUserId, pool.getUserId())
//                .eq(KpiRewardPoint::getPostId, pool.getPostId())
//                .eq(KpiRewardPoint::getShopId, pool.getShopId())
//                .eq(KpiRewardPoint::getMonthly, pool.getMonthly())
//                .eq(KpiRewardPoint::getGroupId, pool.getGroupId())
//        );
//        BigDecimal rewardScore = BigDecimal.ZERO;
//        BigDecimal punishScore = BigDecimal.ZERO;
//        for (KpiRewardPoint point : list) {
//            if (BigDecimal.ZERO.compareTo(point.getScorePoint()) > 0) {
//                punishScore = punishScore.add(point.getScorePoint());
//            } else {
//                rewardScore = rewardScore.add(point.getScorePoint());
//            }
//        }
//        //奖励分正数、惩罚分负数,减去奖惩分数,得到原始分数
//        BigDecimal originKpiScore = poolDetailVO.getKpiScore().subtract(rewardScore).subtract(punishScore);
//        poolDetailVO.setRewardScore(rewardScore);
//        poolDetailVO.setPunishScore(punishScore.abs());
//        poolDetailVO.setOriginKpiScore(originKpiScore);
//    }

    /**
     * 获取绩效组指标总分
     *
     * @param kpiGroupId
     * @return
     */
    public BigDecimal getKpiGroupIndicatorTotalScore(Long kpiGroupId) {
        List<KpiGroupIndicator> indicators = kpiGroupIndicatorService.list(Wrappers.<KpiGroupIndicator>lambdaQuery()
                .eq(KpiGroupIndicator::getKpiGroupId, kpiGroupId)
                .eq(KpiGroupIndicator::getYn, Boolean.TRUE)
        );
        final BigDecimal totalScore = indicators.stream().map(indicator -> BigDecimal.valueOf(indicator.getBaseScore()))
                .reduce(BigDecimal.ZERO, BigDecimal::add);
        return totalScore;
    }

    /**
     * 获取绩效池详情最近日期
     *
     * @param kpiPool
     * @return
     */
    public void buildPoolData(KpiPool kpiPool, KpiPoolDetailVO kpiPoolDetailVo) {
        KpiGroupUser kpiGroupUser = kpiGroupUserService.getMonthLastData(kpiPool.getKpiGroupId(), kpiPool.getUserId(), kpiPool.getMonthly());
        if (PublicUtil.isEmpty(kpiGroupUser)) {
            log.error("员工绩效池:{},不存在绩效组人员", JSON.toJSONString(kpiPool));
            kpiPoolDetailVo.setEndTime(PublicUtil.getYesterdayOrEndOfMonthDay(kpiPool.getMonthly()).atTime(23, 59, 59));
            kpiPoolDetailVo.setStartTime(kpiPool.getMonthly().atDay(1).atTime(00, 00, 00));
            return;
        }
        //不纳入绩效计算 并且 绩效组人员不为空
        if (! kpiPool.getInclusion() && PublicUtil.isNotEmpty(kpiGroupUser)) {
            kpiPoolDetailVo.setIgnoreCause(kpiGroupUser.getIgnoreCause());
            kpiPoolDetailVo.setIgnoreCauseDesc(kpiGroupUser.getIgnoreCauseDesc());
        }
        kpiPoolDetailVo.setEndTime(kpiGroupUser.getDataDate().atTime(23, 59, 59));
        KpiGroupUser firstKpiGroupUser = kpiGroupUserService.getMonthFirstData(kpiPool.getKpiGroupId(), kpiPool.getUserId(), kpiPool.getMonthly());
        kpiPoolDetailVo.setStartTime(firstKpiGroupUser.getDataDate().atTime(00, 00, 00));
    }

    /**
     * 查询用户月度绩效池列表
     *
     * @param userId    用户id
     * @param yearMonth 月度
     * @return 返回结果
     */
    @Cacheable(cacheNames = "kpi", key = "':user:pool:'+ #yearMonth.toString() +':'+ #userId", unless = "#result.size() < 1")
    public List<KpiPool> userSalaryPool(final Long userId, final YearMonth yearMonth) {
        List<KpiPool> list = kpiPoolService.list(Wrappers.<KpiPool>lambdaQuery()
                .eq(KpiPool::getUserId, userId)
                .eq(KpiPool::getMonthly, yearMonth)
                .eq(KpiPool::getYn, Boolean.TRUE)
                .orderByDesc(KpiPool::getId)
        );
        if (CollectionUtils.isEmpty(list)) {
            return new ArrayList<>();
        }
        return list;
    }

//    /**
//     * 绩效项目阶梯详情
//     *
//     * @param kpiPoolId
//     * @param kpiGroupIndicatorId
//     * @param yearMonth
//     * @return
//     */
//    public KpiGroupIndicatorDetailVO getHitIndicatorLadder(Long kpiPoolId, Long kpiGroupIndicatorId, YearMonth yearMonth) {
//
//        KpiGroupIndicator kpiGroupIndicator = kpiGroupIndicatorService.getById(kpiGroupIndicatorId);
//        BV.notNull(kpiGroupIndicator, "指标不存在");
////        Indicators indicator = indicatorsService.queryByCode(kpiGroupIndicator.getIndicatorCode(), Boolean.TRUE);
////        BV.notNull(indicator, "指标不存在");
//        KpiGroup kpiGroup = kpiGroupService.getAllDataById(kpiGroupIndicator.getKpiGroupId());
//        BV.notNull(kpiGroup, "绩效组不存在");
//        KpiGroupIndicatorDetailVO detailVO = new KpiGroupIndicatorDetailVO();
//        LocalDate localDate = PublicUtil.getYesterdayOrEndOfMonthDay(yearMonth);
//
//        if (ScoreWayEnum.LADDER.equals(kpiGroupIndicator.getScoreWay())) {
//            KpiGroupIndicatorHitLog kpiIndicatorHitLog = kpiGroupIndicatorHitLogService.getOne(Wrappers.<KpiGroupIndicatorHitLog>lambdaQuery()
//                    .eq(KpiGroupIndicatorHitLog::getKpiGroupIndicatorId, kpiGroupIndicatorId)
//                    .eq(KpiGroupIndicatorHitLog::getDataDate, localDate)
//                    .eq(KpiGroupIndicatorHitLog::getYn, Boolean.TRUE)
//            );
//            BV.notNull(kpiIndicatorHitLog, "绩效命中记录不存在");
//            Long hitKpiIndicatorLaddersId = kpiIndicatorHitLog.getKpiGroupIndicatorLaddersId();
//
//            List<KpiGroupIndicatorLadders> settins = kpiGroupIndicatorLaddersService.list(Wrappers.<KpiGroupIndicatorLadders>lambdaQuery()
//                    .eq(KpiGroupIndicatorLadders::getKpiGroupIndicatorId, kpiGroupIndicatorId)
//                    .eq(KpiGroupIndicatorLadders::getYn, Boolean.TRUE)
//                    .orderByAsc(KpiGroupIndicatorLadders::getId)
//            );
//
//            detailVO.setLadders(settins.stream().map(indicatorLadders -> {
//                KpiGroupIndicatorLaddersVO indicatorLaddersVO = PublicUtil.copy(indicatorLadders, KpiGroupIndicatorLaddersVO.class);
//                indicatorLaddersVO.setHit((hitKpiIndicatorLaddersId.equals(indicatorLaddersVO.getId()) ? Boolean.TRUE : Boolean.FALSE));
//                indicatorLaddersVO.convertLadderToPercent();
//                return indicatorLaddersVO;
//            }).collect(Collectors.toList()));
//        }
//
//        detailVO.setKpiTime(localDate.atTime(23, 59, 59));
//        detailVO.setPostId(kpiGroup.getPostId());
//        detailVO.setPostName(kpiGroup.getPostName());
//        detailVO.setKpiGroupShopIds(kpiGroup.getShopIds());
//        detailVO.setKpiGroupShopNames(kpiGroup.getShopNames());
//
////        detailVO.setSysName(indicator.getSysName());
////        detailVO.setSysPrefix(indicator.getSysPrefix());
////        detailVO.setIndicatorCode(indicator.getIndicatorCode());
////        detailVO.setIndicatorName(indicator.getIndicatorName());
//        return detailVO;
//
//    }

    /**
     * debug用计算单个绩效组排名
     *
     * @param kpiGroupId 绩效组id
     * @param localDate  日期
     */
    @DisLock(key = "#localDate.toString()+':'+ #kpiGroupId", message = "请勿重复操作")
    public void cacheCalculableKpiGroupRank(Long kpiGroupId, LocalDate localDate) {
        final KpiGroup kpiGroup = kpiGroupService.getAllDataById(kpiGroupId);
        final String kgc = kpiGroup.getKgc();
        final Long groupId = kpiGroup.getGroupId();
        final KpiGroupRank groupRank = kpiGroupRankService.getOne(Wrappers.<KpiGroupRank>lambdaQuery()
                        .eq(KpiGroupRank::getGroupId, groupId)
                        .eq(KpiGroupRank::getYn, Boolean.TRUE)
                        .apply("FIND_IN_SET({0}, kgcs)", kgc),
                Boolean.FALSE
        );
        if (Objects.isNull(groupRank)) {
            KpiGroupCalculableRankBO rankBO = cacheCalculableKpiGroupRank(kpiGroup, localDate);
            calcuStarLevel(rankBO);
            return;
        }
        List<KpiGroup> kpiGroups = kpiGroupService.queryKgiGroupsByDay(localDate);
        BV.isNotEmpty(kpiGroups, () -> "没有需要计算排名的绩效组");
        Map<String, Long> kgcIdMap = kpiGroups.stream().collect(Collectors.toMap(KpiGroup::getKgc, KpiGroup::getId, (v1, v2) -> v1));
        List<String> kgcList = groupRank.getKgcs();
        Set<Long> kpiGroupIds = new HashSet<>();
        for (String kgcStr : kgcList) {
            Long id = kgcIdMap.getOrDefault(kgcStr, 0L);
            if (id > 0) {
                kpiGroupIds.add(kpiGroupId);
            }
        }
        BV.isNotEmpty(kpiGroupIds, () -> MessageFormatTransfer("绩效排名组[{0}]不包含任何绩效组", groupRank.getId()));
        KpiGroupCalculableRankBO bo = cacheCalculableKpiGroupRank(groupRank, kpiGroupIds, localDate);
        calcuStarLevel(bo);
    }

    /**
     * 缓存需要计算绩效排名
     *
     * @param localDate
     */
    public void cacheCalculableKpiGroupRank(LocalDate localDate) {
        List<String> rankBOS = new ArrayList<>();
        List<KpiGroupRank> kpiGroupRanks = kpiGroupRankService.list(Wrappers.<KpiGroupRank>lambdaQuery()
                .eq(KpiGroupRank::getStatus, SettingStatusEnum.EFFECTIVE)
                .eq(KpiGroupRank::getYn, Boolean.TRUE)
        );
        for (KpiGroupRank kpiGroupRank : kpiGroupRanks) {
            if (PublicUtil.isNotEmpty(kpiGroupRank.getKpiGroupIds())) {
                rankBOS.add(JSONObject.toJSONString(cacheCalculableKpiGroupRank(kpiGroupRank,
                        new HashSet<>(kpiGroupRank.getKpiGroupIds()), localDate)));
            }
        }
        if (PublicUtil.isNotEmpty(rankBOS)) {
            ListOperations<String, String> listOps = stringRedisTemplate.opsForList();
            listOps.rightPushAll(getCalcuStarKey(), rankBOS);
        }
    }

    /**
     * 获取星级配置
     *
     * @param bo
     * @param kpiGroups
     * @return
     */
    public KpiRankCalculableBO getStarConfig(KpiGroupCalculableRankBO bo, List<KpiGroup> kpiGroups) {
        KpiRankCalculableBO calculableBO = new KpiRankCalculableBO();
        if (bo.getCalculateSeparately()) {
            KpiGroup kpiGroup = kpiGroups.get(0);
            List<KpiStarLadders> kpiStarLadders = kpiStarLaddersService.list(Wrappers.<KpiStarLadders>lambdaQuery()
                    .eq(KpiStarLadders::getKpiGroupId, kpiGroup.getId())
                    .eq(KpiStarLadders::getYn, Boolean.TRUE)
            );
            BV.isNotEmpty(kpiStarLadders, () -> "星级阶梯配置不存在");
            if (PublicUtil.isNotEmpty(kpiGroup.getRevokedScoreRatio())) {
                calculableBO.setRevokedScoreRatio(kpiGroup.getRevokedScoreRatio());
            }
            calculableBO.setStarEvaluationType(kpiGroup.getStarEvaluationType());
            calculableBO.setStarLadders(PublicUtil.copyList(kpiStarLadders, KpiStarLadderBO.class));
        } else {
            KpiGroupRank kpiGroupRank = kpiGroupRankService.getById(bo.getKpiGroupRankId());
            List<KpiGroupRankStarLadders> kpiGroupRankStarLadders = kpiGroupRankStarLaddersService.list(Wrappers.<KpiGroupRankStarLadders>lambdaQuery()
                    .eq(KpiGroupRankStarLadders::getKpiGroupRankId, bo.getKpiGroupRankId())
                    .eq(KpiGroupRankStarLadders::getYn, Boolean.TRUE)
            );
            BV.isNotEmpty(kpiGroupRankStarLadders, () -> "排名星级阶梯配置不存在");
            if (PublicUtil.isNotEmpty(kpiGroupRank.getRevokedScoreRatio())) {
                calculableBO.setRevokedScoreRatio(kpiGroupRank.getRevokedScoreRatio());
            }
            calculableBO.setStarEvaluationType(kpiGroupRank.getStarEvaluationType());
            calculableBO.setStarLadders(PublicUtil.copyList(kpiGroupRankStarLadders, KpiStarLadderBO.class));
        }
        return calculableBO;
    }

    private KpiGroupCalculableRankBO cacheCalculableKpiGroupRank(KpiGroupRank kpiGroupRank, Set<Long> kpiGroupIds,
                                                                 LocalDate date) {
        return KpiGroupCalculableRankBO.builder()
                .kpiGroupIds(new ArrayList<>(kpiGroupIds))
                .groupId(kpiGroupRank.getGroupId())
                .localDate(date)
                .revokedScoreRatio(kpiGroupRank.getRevokedScoreRatio())
                .calculateSeparately(Boolean.FALSE)
                .kpiGroupRankId(kpiGroupRank.getId())
                .build();
    }

    private KpiGroupCalculableRankBO cacheCalculableKpiGroupRank(KpiGroup kpiGroup, LocalDate date) {
        return KpiGroupCalculableRankBO.builder()
                .kpiGroupIds(Collections.singletonList(kpiGroup.getId()))
                .groupId(kpiGroup.getGroupId())
                .revokedScoreRatio(kpiGroup.getRevokedScoreRatio())
                .localDate(date)
                .calculateSeparately(Boolean.TRUE)
                .build();

    }

    /**
     * 绩效报表-绩效得分率排名详情
     * @param dto
     * @return
     */
    public List<KpiPoolVO> queryKpiRankPool(KpiGroupRankConfigQueryDTO dto) {
        List<KpiPool> list = kpiPoolService.list(Wrappers.<KpiPool>lambdaQuery()
                .in(KpiPool::getKpiGroupId, dto.getKpiGroupIds())
                .eq(KpiPool::getMonthly, dto.getYearMonth())
                .eq(KpiPool::getYn, Boolean.TRUE)
                .last("ORDER BY ISNULL(rank), rank ASC")
        );
        if (CollectionUtils.isEmpty(list)) {
            return Collections.emptyList();
        }
        List<KpiPoolVO> kpiPoolVOS = PublicUtil.copyList(list, KpiPoolVO.class);
        for (KpiPoolVO kpiPoolVO : kpiPoolVOS) {
            //处理得分率 乘以 100
            kpiPoolVO.setKpiScoreRatio(Optional.ofNullable(kpiPoolVO.getKpiScoreRatio()).orElse(BigDecimal.ZERO).multiply(Constant.ONE_HUNDRED));
            kpiPoolVO.setLastOneKpiScoreRatio(Optional.ofNullable(kpiPoolVO.getLastOneKpiScoreRatio()).orElse(BigDecimal.ZERO).multiply(Constant.ONE_HUNDRED));
            kpiPoolVO.setLastTwoKpiScoreRatio(Optional.ofNullable(kpiPoolVO.getLastTwoKpiScoreRatio()).orElse(BigDecimal.ZERO).multiply(Constant.ONE_HUNDRED));
            kpiPoolVO.setAverageKpiScoreRatio(Optional.ofNullable(kpiPoolVO.getAverageKpiScoreRatio()).orElse(BigDecimal.ZERO).multiply(Constant.ONE_HUNDRED));
        }
        return kpiPoolVOS;
    }
}