SalaryReportTask.java 49.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
package cn.fw.morax.server.task;

import cn.fw.common.cache.locker.DistributedLocker;
import cn.fw.morax.common.constant.Constant;
import cn.fw.morax.common.constant.TimeTaskConstant;
import cn.fw.morax.common.utils.DateUtil;
import cn.fw.morax.common.utils.PublicUtil;
import cn.fw.morax.domain.bo.salary.SalaryGroupProjectBO;
import cn.fw.morax.domain.db.kpi.IndicatorUserValue;
import cn.fw.morax.domain.db.salary.*;
import cn.fw.morax.domain.enums.*;
import cn.fw.morax.domain.vo.salary.SalaryGroupProjectParamVO;
import cn.fw.morax.rpc.ehr.EhrRpcService;
import cn.fw.morax.rpc.ehr.dto.ManagerDTO;
import cn.fw.morax.rpc.ehr.dto.ManagerStaffRoleDTO;
import cn.fw.morax.rpc.ehr.dto.ManagerStaffShopDTO;
import cn.fw.morax.rpc.ehr.dto.StaffBaseInfoDTO;
import cn.fw.morax.rpc.oop.OopRpcService;
import cn.fw.morax.service.biz.CommonService;
import cn.fw.morax.service.biz.kpi.KpiPoolCommonService;
import cn.fw.morax.service.biz.salary.SalarySettingCommonService;
import cn.fw.morax.service.data.kpi.IndicatorUserValueService;
import cn.fw.morax.service.data.kpi.KpiPoolService;
import cn.fw.morax.service.data.salary.*;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.google.common.collect.Maps;
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.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.YearMonth;
import java.time.temporal.TemporalAdjusters;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Lock;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.ToDoubleFunction;
import java.util.stream.Collectors;

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

    private final DistributedLocker distributedLocker;
    private final SalaryGroupService salaryGroupService;
    private final SalaryPoolService salaryPoolService;
    private final KpiPoolService kpiPoolService;
    private final KpiPoolCommonService kpiPoolCommonService;
    private final ReportSalaryService reportSalaryService;
    private final TransactionDefinition transactionDefinition;
    private final ReportSalaryDimService reportSalaryDimService;
    private final ReportSalaryCodeService reportSalaryCodeService;
    private final IndicatorUserValueService indicatorUserValueService;
    private final SalaryGroupProjectService salaryGroupProjectService;
    private final PlatformTransactionManager platformTransactionManager;
    private final ReportSalaryDimExtraService reportSalaryDimExtraService;
    private final ReportSalaryDimValueService reportSalaryDimValueService;
    private final SalaryGroupProjectHitLogService salaryGroupProjectHitLogService;
    private final SalaryGeneralSettinService salaryGeneralSettinService;
    private final SalaryGroupProjectSettinService salaryGroupProjectSettinService;
    private final SalarySettingCommonService salarySettingCommonService;
    private final SalaryGroupProjectParamService salaryGroupProjectParamService;
    private final SalaryGroupProjectTargetHitLogService salaryGroupProjectTargetHitLogService;
    private final CommonService commonService;
    private final EhrRpcService ehrRpcService;
    private final OopRpcService oopRpcService;
    private final SalaryPoolDetailService salaryPoolDetailService;


    @Value("${special-indicator-code.car-series}")
    @Getter
    private String carSeries;
    @Value("${special-indicator-code.base-salary}")
    @Getter
    private String baseSalaryCode;
    @Value("${spring.cache.custom.global-prefix}:salary:group:report")
    @Getter
    private String salaryGroupReportDistKey;

    /**
     * 薪酬报表定时任务
     *
     */
    @Scheduled(cron = TimeTaskConstant.SALARY_REPORT)
    @Transactional(rollbackFor = Exception.class)
    public void salaryReportTask() {
        this.salaryReport(LocalDate.now().minusDays(1));
    }

    /**
     * 薪酬报表最终定时任务(
     * 人员质量评测每月2号计算上月、计算完成后会操作上月薪酬分,所以再次抽取上月报表)
     */
    @Scheduled(cron = TimeTaskConstant.SALARY_MONTH_FINAL_REPORT)
    @Transactional(rollbackFor = Exception.class)
    public void salaryLastMonthReportTask() {
        LocalDate lastMonthEndDay = LocalDate.now().minusMonths(1).with(TemporalAdjusters.lastDayOfMonth());
        YearMonth monthly = YearMonth.now().minusMonths(1);
        oopRpcService.allGroups().stream().forEach(group -> {
            final Long groupId = group.getId();
            Boolean hasEndAppeal = salarySettingCommonService.lastDayHasClosureForReport(groupId, monthly);
            if (hasEndAppeal) {
                this.salaryReport(lastMonthEndDay);
            }
        });
    }

    /**
     * 薪酬报表定时任务
     *
     * @param date
     */
    public void salaryReport(LocalDate date) {
        Lock lock = distributedLocker.lock(getSalaryGroupReportDistKey());
        if (! ((RLock) lock).isLocked()) {
            return;
        }
        TransactionStatus transactionStatus = platformTransactionManager.getTransaction(transactionDefinition);
        try {
            log.info("定时任务【薪酬报表数据抽取-新】开始执行");
            //清理数据,每天留一条当月最新数据,每个月留一条月最后一天的数据
            cleanData(date);
            //查询所有需要处理的薪酬组
            List<SalaryGroup> salaryGroups = salaryGroupService.getAllEffectGroups(DateUtil.localDate2Date(date));
            for (SalaryGroup salaryGroup : salaryGroups) {
                //抽取排名组数据
                createReport(salaryGroup, salaryGroup.getGroupId(), date);
            }
            platformTransactionManager.commit(transactionStatus);
        } catch (Exception e){
            platformTransactionManager.rollback(transactionStatus);
            log.error(e.getMessage(), e);
        } finally {
            lock.unlock();
        }
    }


    /**
     * 薪酬排名组报表数据抽取
     * @param salaryGroup
     * @param groupId
     * @param date
     */
    private void createReport(SalaryGroup salaryGroup, Long groupId, LocalDate date) {
        final Long salaryGroupId = salaryGroup.getId();
        List<SalaryPool> pools = salaryPoolService.list(Wrappers.<SalaryPool>lambdaQuery()
                .eq(SalaryPool::getSalaryGroupId, salaryGroupId)
                .eq(SalaryPool::getMonthly, YearMonth.from(date))
                .eq(SalaryPool::getYn, Boolean.TRUE)
        );
        if (PublicUtil.isEmpty(pools)) {
            return;
        }
        //保存 报表薪酬排名组 信息
        final Long reportSalaryId = saveReportSalary(salaryGroup, groupId, date);

        //薪酬排名组下归属的所有薪酬组的对应指标集合
        List<SalaryGroupProjectBO> salaryGroupProjects = getProjectBO(salaryGroupId);

        //一个薪酬排名组对应多个薪酬组,也对应薪酬组下的所有指标集合
        saveReportSalaryCodes(date, reportSalaryId, salaryGroupProjects);
        List<ReportSalaryDim> userDims = new ArrayList();
        //人员维度
        List<ReportSalaryDimValue> userSalaryValues = calcUser(salaryGroupProjects, userDims, date, pools, reportSalaryId);
        //门店维度
        calcShop(salaryGroupProjects, pools, reportSalaryId, userSalaryValues, userDims, date);
        //管理层维度
        calcManager(salaryGroupProjects, pools, reportSalaryId, userSalaryValues, userDims, date);
    }

    private List<ReportSalaryCode> saveReportSalaryCodes(LocalDate date, Long reportSalaryId, List<SalaryGroupProjectBO> salaryGroupProjects) {
        LinkedList<ReportSalaryCode> reportSalaryCodes = new LinkedList<>();
        AtomicInteger order = new AtomicInteger();
        for (SalaryGroupProjectBO salaryGroupProject : salaryGroupProjects) {
            reportSalaryCodes.add(createProjectCode(salaryGroupProject, order));
            if (IndicatorCodeTypeEnum.COMBINE_INDICATOR.equals(salaryGroupProject.getCodeType())) {
                List<SalaryGroupProjectParamVO> salaryGroupProjectParamVos = salaryGroupProjectParamService.
                        getSalaryGroupProjectParamVO(salaryGroupProject.getId());
                if (salaryGroupProject.getCalMethod().equals(SalaryCalMethodEnum.CAR_SERIES)) {
                    continue;
                }
                reportSalaryCodes.addAll(createParamCodes(salaryGroupProject, salaryGroupProjectParamVos, order));
            }
        }

        if (PublicUtil.isNotEmpty(reportSalaryCodes)) {
            reportSalaryCodes.forEach(reportSalaryCode -> {
                reportSalaryCode.setReportSalaryId(reportSalaryId);
                reportSalaryCode.setDataDate(date);
            });
            reportSalaryCodeService.saveBatch(reportSalaryCodes);
        }
        return reportSalaryCodes;
    }



    private List<ReportSalaryDimValue> calcUser(List<SalaryGroupProjectBO> salaryGroupProjects,
                                                  List<ReportSalaryDim> userDims,
                                                  LocalDate date,
                                                  List<SalaryPool> pools,
                                                  Long reportSalaryId) {
        MultiKeyMap<Long, BigDecimal> userSalaryMap = this.getUserIndicatorHitMap(salaryGroupProjects, date, pools);
        Map<Long, List<SalaryPoolDetail>> salaryPoolDetailMap = this.getSalaryPoolDetailMap(date, pools);
        List<ReportSalaryDimValue> reportSalaryValues = new ArrayList<>();
        //人的维度为基础,计算各个指标信息对应的数据
        for (SalaryPool pool : pools) {
            List<SalaryPoolDetail> salaryPoolIdDetails = Optional.ofNullable(salaryPoolDetailMap.get(pool.getId())).orElse(Collections.emptyList());
            ReportSalaryDim reportSalaryDim = saveStaffDim(pool, date, reportSalaryId,salaryPoolIdDetails);
            userDims.add(reportSalaryDim);
            final Long userId = pool.getUserId();
            final Long reportSalaryDimId = reportSalaryDim.getId();
            //薪酬排名组下的所有指标集合
            for (SalaryGroupProjectBO salaryGroupProject : salaryGroupProjects) {
                if (! pool.getSalaryGroupId().equals(salaryGroupProject.getSalaryGroupId())) {
                    continue;
                }
                final Long salaryGroupProjectId = salaryGroupProject.getId();
                reportSalaryValues.add(this.convertDB(salaryGroupProject, reportSalaryDimId, date, userSalaryMap.get(userId, salaryGroupProjectId)));
                List<SalaryGroupProjectParamVO> salaryGroupProjectParamVos = salaryGroupProjectParamService.getSalaryGroupProjectParamVO(salaryGroupProject.getId());

                if (salaryGroupProject.getCalMethod().equals(SalaryCalMethodEnum.CAR_SERIES)) {
                    continue;
                }

                Set<String> paramCodes = new HashSet<>();
                for (SalaryGroupProjectParamVO salaryGroupProjectParam : salaryGroupProjectParamVos) {
                    //一个薪酬项目中,指标只能出现一次
                    if (! paramCodes.add(salaryGroupProjectParam.getIndicatorCode())) {
                        continue;
                    }
                    if (TargetTypeEnum.NO.equals(salaryGroupProjectParam.getTargetType())) {
                        //无目标
                        Map<Long, BigDecimal> userValueMap = queryUserOriginValue(salaryGroupProjectParam.getIndicatorCode(), userId, date);
                        BigDecimal value = userValueMap.getOrDefault(userId, BigDecimal.ZERO);
                        reportSalaryValues.add(this.convertNoTargetDB(salaryGroupProject, salaryGroupProjectParam, date, reportSalaryDimId, value));
                    } else {
                        //有目标
                        Map<Long, SalaryGroupProjectTargetHitLog> targetHitLogMap = queryUserTargetValue(salaryGroupProjectParam.getId(), userId, date);
                        SalaryGroupProjectTargetHitLog hitLog = targetHitLogMap.get(userId);
                        BigDecimal value = Optional.ofNullable(hitLog).map(SalaryGroupProjectTargetHitLog::getReachValue).orElse(BigDecimal.ZERO);
                        reportSalaryValues.add(this.convertTargetDB(salaryGroupProject, salaryGroupProjectParam, date, reportSalaryDimId, value));
                    }
                }
            }
        }
        if (PublicUtil.isNotEmpty(reportSalaryValues)){
            reportSalaryDimValueService.saveBatch(reportSalaryValues);
        }
        return reportSalaryValues;
    }

    public void calcShop(List<SalaryGroupProjectBO> salaryGroupProjects,
                          List<SalaryPool> pools,
                          Long reportSalaryId,
                          List<ReportSalaryDimValue> userSalaryValues,
                          List<ReportSalaryDim> userDims,
                          LocalDate date) {
        Map<Long, String> shopMap = pools.stream().collect(Collectors.toMap(SalaryPool::getShopId, SalaryPool::getShopName, (v1, v2) -> v1));
        List<ReportSalaryDimValue> reportSalaryDimValues = new ArrayList<>();
        for (Long shopId : shopMap.keySet()) {
            List<ReportSalaryDimValue> childReportSalaryDimValues = new ArrayList<>();
            Set<Long> shopDimReportIds = userDims.stream()
                    .filter(user -> shopId.equals(user.getShopId()))
                    .map(ReportSalaryDim::getId).collect(Collectors.toSet());
            if (PublicUtil.isEmpty(shopDimReportIds)) {
                continue;
            }
            final Long shopReportSalaryDimId = this.saveShopDimDB(shopId, shopMap, date, reportSalaryId, userDims, shopDimReportIds);

            for (SalaryGroupProjectBO salaryGroupProject : salaryGroupProjects) {
                BigDecimal value = calcAverageValue(userSalaryValues, shopDimReportIds, salaryGroupProject.getId().toString());
                childReportSalaryDimValues.add(this.convertProjectValueDB(salaryGroupProject, value));
                Set<String> paramCodes = new HashSet<>();
                List<SalaryGroupProjectParamVO> salaryGroupProjectParamVos = salaryGroupProjectParamService.getSalaryGroupProjectParamVO(salaryGroupProject.getId());
                for (SalaryGroupProjectParamVO salaryGroupProjectParam : salaryGroupProjectParamVos) {
                    if (! paramCodes.add(salaryGroupProjectParam.getIndicatorCode())) {
                        continue;
                    }
                    BigDecimal paramValue = calcAverageValue(userSalaryValues, shopDimReportIds, salaryGroupProjectParam.getIndicatorCode());
                    childReportSalaryDimValues.add(this.convertShopValueDBPcode(salaryGroupProjectParam, paramValue, salaryGroupProject));
                }
            }

            childReportSalaryDimValues.forEach(reportSalaryDimValue -> {
                reportSalaryDimValue.setDataDate(date);
                reportSalaryDimValue.setReportSalaryDimId(shopReportSalaryDimId);
            });
            reportSalaryDimValues.addAll(childReportSalaryDimValues);
        }
        if (PublicUtil.isNotEmpty(reportSalaryDimValues)){
            reportSalaryDimValueService.saveBatch(reportSalaryDimValues);
        }
    }

    public void calcManager(List<SalaryGroupProjectBO> salaryGroupProjects,
                          List<SalaryPool> pools,
                          Long reportSalaryId,
                          List<ReportSalaryDimValue> userSalaryValues,
                          List<ReportSalaryDim> userDims,
                          LocalDate date) {
        List<Long> shopIds = pools.stream().map(SalaryPool::getShopId).collect(Collectors.toList());
        List<ManagerDTO> managerDTOS = ehrRpcService.getRealTimeShopManager(new ArrayList<>(shopIds));
        log.info("查询门店实时管理者:{},{}", JSON.toJSONString(shopIds), JSON.toJSONString(managerDTOS));
        if (PublicUtil.isEmpty(managerDTOS)) {
            return;
        }
        Map<Long, StaffBaseInfoDTO> managerMap = staffInfoMap(managerDTOS);
        List<ReportSalaryDimValue> reportSalaryDimValues = new ArrayList<>();
        for (ManagerDTO manager : managerDTOS) {
            List<ReportSalaryDimValue> childReportSalaryDimValues = new ArrayList<>();
            if (PublicUtil.isEmpty(manager.getManageStaffList())) {
                continue;
            }
            List<Long> manageStaffIds = manager.getManageStaffList().stream().map(StaffBaseInfoDTO::getId).distinct().collect(Collectors.toList());
            Set<Long> managerStaffDimReportIds = userDims.stream()
                    .filter(user -> manageStaffIds.contains(user.getUserId()))
                    .map(ReportSalaryDim::getId).collect(Collectors.toSet());
            if (PublicUtil.isEmpty(managerStaffDimReportIds)) {
                continue;
            }
            //BigDecimal kpiScoreRatio = calcAverageKpiScoreRatio(userDims, managerStaffDimReportIds);
            //BigDecimal averageSalary = calcAverageTotalSalary(userDims, managerStaffDimReportIds);
            final Long reportSalaryDimId = this.saveManagerDimDB(manager, date, reportSalaryId, managerMap,manageStaffIds,managerStaffDimReportIds,userDims);
            for (SalaryGroupProjectBO salaryGroupProject : salaryGroupProjects) {
                BigDecimal value = calcAverageValue(userSalaryValues, managerStaffDimReportIds, salaryGroupProject.getId().toString());
                childReportSalaryDimValues.add(this.convertProjectValueDB(salaryGroupProject, value));
                List<SalaryGroupProjectParamVO> salaryGroupProjectParamVos = salaryGroupProjectParamService.getSalaryGroupProjectParamVO(salaryGroupProject.getId());
                for (SalaryGroupProjectParamVO salaryGroupProjectParam : salaryGroupProjectParamVos) {
                    BigDecimal paramValue = calcAverageValue(userSalaryValues, managerStaffDimReportIds, salaryGroupProjectParam.getIndicatorCode());
                    childReportSalaryDimValues.add(this.convertShopValueDBPcode(salaryGroupProjectParam, paramValue, salaryGroupProject));
                }
            }

            childReportSalaryDimValues.forEach(reportSalaryDimValue -> {
                reportSalaryDimValue.setDataDate(date);
                reportSalaryDimValue.setReportSalaryDimId(reportSalaryDimId);
            });
            reportSalaryDimValues.addAll(childReportSalaryDimValues);
        }
        if (PublicUtil.isNotEmpty(reportSalaryDimValues)) {
            reportSalaryDimValueService.saveBatch(reportSalaryDimValues);
        }
    }

    public Map<Long, StaffBaseInfoDTO> staffInfoMap(List<ManagerDTO> managerDTOS) {
        List<Long> staffIds = managerDTOS.stream().map(ManagerDTO::getStaffId).collect(Collectors.toList());
        List<StaffBaseInfoDTO> staffInfos = ehrRpcService.queryStaffBaseInfo(staffIds);
        return staffInfos.stream().collect(Collectors.toMap(StaffBaseInfoDTO::getId, Function.identity(), (v1, v2) -> v1));
    }

    /**
     * 抽象处理平均值计算
     * @param data
     * @param predicate
     * @param field
     * @return
     */
    private <T> BigDecimal calcAverage(final Collection<T> data,Predicate<T> predicate, final ToDoubleFunction<T> field) {
        if (CollectionUtils.isEmpty(data)) {
            return BigDecimal.ZERO;
        }
        Double averageRatioDouble = data.stream()
                .filter(predicate)
                .mapToDouble(field)
                .average()
                .orElse(0);
        return BigDecimal.valueOf(averageRatioDouble);
    }

    /**
     * 抽象处理平均值计算
     * @param data
     * @param field
     * @return
     * @param <T>
     */
    private <T> BigDecimal calcAverage(final Collection<T> data, final ToDoubleFunction<T> field) {
        if (CollectionUtils.isEmpty(data)) {
            return BigDecimal.ZERO;
        }
        Double averageRatioDouble = data.stream()
                .mapToDouble(field)
                .average()
                .orElse(0);
        return BigDecimal.valueOf(averageRatioDouble);
    }


    public BigDecimal calcAverageTotalSalary(List<ReportSalaryDim> dims, Set<Long> ReportDimIds) {
        Double averageRatioDouble = dims.stream()
                .filter(user -> ReportDimIds.contains(user.getId()))
                .mapToDouble(userValue -> Optional.ofNullable(userValue.getTotalReward()).orElse(BigDecimal.ZERO).doubleValue())
                .average()
                .orElse(0);
        return new BigDecimal(averageRatioDouble.toString());
    }

    public BigDecimal calcAverageKpiScoreRatio(List<ReportSalaryDim> dims, Set<Long> ReportDimIds) {
        Double averageRatioDouble = dims.stream()
                .filter(user -> ReportDimIds.contains(user.getId()))
                .mapToDouble(userValue -> Optional.ofNullable(userValue.getKpiScoreRatio()).orElse(BigDecimal.ZERO).doubleValue())
                .average()
                .orElse(0);
        return new BigDecimal(averageRatioDouble.toString());
    }

    public BigDecimal calcAverageValue(List<ReportSalaryDimValue> userSalaryValues, Set<Long> ReportDimIds, String code) {
        Double averageRatioDouble = userSalaryValues.stream()
                .filter(user -> ReportDimIds.contains(user.getReportSalaryDimId()) && code.equals(user.getCode()))
                .mapToDouble(userValue -> Optional.ofNullable(userValue.getValue()).orElse(BigDecimal.ZERO).doubleValue())
                .average()
                .orElse(0);
        return new BigDecimal(averageRatioDouble.toString());
    }

    public Long saveShopDimDB(Long shopId,
                              Map<Long, String> shopMap,
                              LocalDate date,
                              Long reportSalaryId,
                              List<ReportSalaryDim> userDims,
                              Set<Long> shopDimReportIds) {
        ReportSalaryDim reportSalaryDim = new ReportSalaryDim();
        reportSalaryDim.setDimension(ReportDimensionEnum.SHOP);
        reportSalaryDim.setReferId(shopId);
        reportSalaryDim.setShopId(shopId);
        reportSalaryDim.setShopName(shopMap.get(shopId));
        reportSalaryDim.setDataDate(date);
        reportSalaryDim.setReportSalaryId(reportSalaryId);
        //计算平均值薪酬的额外项
        extCalcAverage(userDims, shopDimReportIds, reportSalaryDim);
        reportSalaryDimService.save(reportSalaryDim);
        return reportSalaryDim.getId();
    }

    /**
     * 计算平均值薪酬的额外项
     * @param userDims
     * @param shopDimReportIds
     * @param reportSalaryDim
     */
    private void extCalcAverage(List<ReportSalaryDim> userDims, Set<Long> shopDimReportIds, ReportSalaryDim reportSalaryDim) {
        List<ReportSalaryDim> filterUserDims = userDims.stream().filter(e -> shopDimReportIds.contains(e.getId())).collect(Collectors.toList());
        //绩效得分率(N)
        reportSalaryDim.setKpiScoreRatio(calcAverage(filterUserDims, e -> Optional.ofNullable(e.getKpiScoreRatio()).orElse(BigDecimal.ZERO).doubleValue()));
        //收入-平均值
        reportSalaryDim.setActKpiMoney(calcAverage(filterUserDims, e -> Optional.ofNullable(e.getActKpiMoney()).orElse(BigDecimal.ZERO).doubleValue()));
        reportSalaryDim.setActAwardMoney(calcAverage(filterUserDims, e -> Optional.ofNullable(e.getActAwardMoney()).orElse(BigDecimal.ZERO).doubleValue()));
        reportSalaryDim.setActSubsidyMoney(calcAverage(filterUserDims, e -> Optional.ofNullable(e.getActSubsidyMoney()).orElse(BigDecimal.ZERO).doubleValue()));
        reportSalaryDim.setActProbationMoney(calcAverage(filterUserDims, e -> Optional.ofNullable(e.getActProbationMoney()).orElse(BigDecimal.ZERO).doubleValue()));
        reportSalaryDim.setActJobCompensateMoney(calcAverage(filterUserDims, e -> Optional.ofNullable(e.getActJobCompensateMoney()).orElse(BigDecimal.ZERO).doubleValue()));
        reportSalaryDim.setActEvalAwardMoney(calcAverage(filterUserDims, e -> Optional.ofNullable(e.getActEvalAwardMoney()).orElse(BigDecimal.ZERO).doubleValue()));
        //总收入合计平均值
        reportSalaryDim.setActRevenueTotalMoney(calcAverage(filterUserDims, e -> Optional.ofNullable(e.getActRevenueTotalMoney()).orElse(BigDecimal.ZERO).doubleValue()));
        //reportSalaryDim.setActRevenueTotalMoney(
        //        reportSalaryDim.getActKpiMoney()
        //                .add(reportSalaryDim.getActAwardMoney())
        //                .add(reportSalaryDim.getActSubsidyMoney())
        //                .add(reportSalaryDim.getActProbationMoney())
        //                .add(reportSalaryDim.getActJobCompensateMonry())
        //                .add(reportSalaryDim.getActEvalAwardMoney())
        //);
        //扣除-平均值
        reportSalaryDim.setActPenaltyMoney(calcAverage(filterUserDims, e -> Optional.ofNullable(e.getActPenaltyMoney()).orElse(BigDecimal.ZERO).doubleValue()));
        reportSalaryDim.setActNecessaryMoney(calcAverage(filterUserDims, e -> Optional.ofNullable(e.getActNecessaryMoney()).orElse(BigDecimal.ZERO).doubleValue()));
        reportSalaryDim.setActPersonTaxMoney(calcAverage(filterUserDims, e -> Optional.ofNullable(e.getActPersonTaxMoney()).orElse(BigDecimal.ZERO).doubleValue()));
        reportSalaryDim.setActAccumulationFundMoney(calcAverage(filterUserDims, e -> Optional.ofNullable(e.getActAccumulationFundMoney()).orElse(BigDecimal.ZERO).doubleValue()));
        //总扣除合计平均值
        reportSalaryDim.setActDeductTotalMoney(calcAverage(filterUserDims, e -> Optional.ofNullable(e.getActDeductTotalMoney()).orElse(BigDecimal.ZERO).doubleValue()));
        //reportSalaryDim.setActDeductTotalMoney(
        //        reportSalaryDim.getActPenaltyMoney()
        //                .add(reportSalaryDim.getActNecessaryMoney())
        //                .add(reportSalaryDim.getActPersonTaxMoney())
        //                .add(reportSalaryDim.getActAccumulationFundMoney())
        //);
        //总薪酬平均值 = 总收入合计 - 总扣除合计 or 直接取平均值
        reportSalaryDim.setTotalReward(calcAverage(filterUserDims, e -> Optional.ofNullable(e.getTotalReward()).orElse(BigDecimal.ZERO).doubleValue()));
        //reportSalaryDim.setTotalReward(
        //        reportSalaryDim.getActRevenueTotalMoney()
        //                .subtract(reportSalaryDim.getActDeductTotalMoney()));
    }

    /**
     * 计算人员的
     * 增加 薪资类型相关项目处理 ++
     * @param salaryPoolDetails
     * @param reportSalaryDim
     */
    private void extCaleUserMoney(List<SalaryPoolDetail> salaryPoolDetails, ReportSalaryDim reportSalaryDim) {
        //额外计算项++
        Map<SalaryTypeEnum, List<SalaryPoolDetail>> salaryTypeEnumListMap = salaryPoolDetails
                .stream()
                .collect(Collectors.groupingBy(SalaryPoolDetail::getType));
        //收入
        reportSalaryDim.setActKpiMoney(getSalaryTypeEnumMoney(salaryTypeEnumListMap,SalaryTypeEnum.ROYALTIES));
        reportSalaryDim.setActAwardMoney(getSalaryTypeEnumMoney(salaryTypeEnumListMap,SalaryTypeEnum.AWARD));
        reportSalaryDim.setActSubsidyMoney(getSalaryTypeEnumMoney(salaryTypeEnumListMap,SalaryTypeEnum.SUBSIDY));
        reportSalaryDim.setActProbationMoney(getSalaryTypeEnumMoney(salaryTypeEnumListMap,SalaryTypeEnum.PROBATION));
        reportSalaryDim.setActJobCompensateMoney(BigDecimal.ZERO);
        reportSalaryDim.setActEvalAwardMoney(BigDecimal.ZERO);
        //总收入合计
        reportSalaryDim.setActRevenueTotalMoney(
                reportSalaryDim.getActKpiMoney()
                        .add(reportSalaryDim.getActAwardMoney())
                        .add(reportSalaryDim.getActSubsidyMoney())
                        .add(reportSalaryDim.getActProbationMoney())
                        .add(reportSalaryDim.getActJobCompensateMoney())
                        .add(reportSalaryDim.getActEvalAwardMoney())
        );
        //扣除
        reportSalaryDim.setActPenaltyMoney(getSalaryTypeEnumMoney(salaryTypeEnumListMap,SalaryTypeEnum.PENALTY));
        reportSalaryDim.setActNecessaryMoney(getSalaryTypeEnumMoney(salaryTypeEnumListMap,SalaryTypeEnum.NECESSARY));
        reportSalaryDim.setActPersonTaxMoney(getSalaryTypeEnumMoney(salaryTypeEnumListMap,SalaryTypeEnum.PERSON_TAX));
        reportSalaryDim.setActAccumulationFundMoney(BigDecimal.ZERO);
        //总扣除合计
        reportSalaryDim.setActDeductTotalMoney(
                reportSalaryDim.getActPenaltyMoney()
                        .add(reportSalaryDim.getActNecessaryMoney())
                        .add(reportSalaryDim.getActPersonTaxMoney())
                        .add(reportSalaryDim.getActAccumulationFundMoney())
        );
        //总薪酬 = 总收入合计 - 总扣除合计
        reportSalaryDim.setTotalReward(
                reportSalaryDim.getActRevenueTotalMoney()
                        .subtract(reportSalaryDim.getActDeductTotalMoney()));
    }


    public Long saveManagerDimDB(ManagerDTO manager,
                                 LocalDate date,
                                 Long reportSalaryId,
                                 Map<Long, StaffBaseInfoDTO> managerMap,
                                 List<Long> manageStaffIds,
                                 Set<Long> managerStaffDimReportIds,
                                 List<ReportSalaryDim> userDims) {
        ReportSalaryDim reportSalaryDim = new ReportSalaryDim();
        reportSalaryDim.setDimension(ReportDimensionEnum.MANAGER);
        reportSalaryDim.setUserId(manager.getStaffId());
        reportSalaryDim.setUserName(manager.getStaffName());
        //计算平均值薪酬的额外项
        extCalcAverage(userDims, managerStaffDimReportIds, reportSalaryDim);
        reportSalaryDim.setDataDate(date);
        reportSalaryDim.setReportSalaryId(reportSalaryId);
        if (managerMap.containsKey(manager.getStaffId())) {
            StaffBaseInfoDTO staffInfo = managerMap.get(manager.getStaffId());
            reportSalaryDim.setShopId(staffInfo.getShopId());
            reportSalaryDim.setShopName(staffInfo.getShopName());
            reportSalaryDim.setPostId(staffInfo.getPostId());
            reportSalaryDim.setPostName(staffInfo.getPostName());
        }

        List<String> roleCodes = manager.getScopeList().stream()
                .flatMap(managerStaffVo -> managerStaffVo.getRoleList().stream())
                .map(ManagerStaffRoleDTO::getRoleCode)
                .distinct()
                .collect(Collectors.toList());
        List<String> roleNames = manager.getScopeList().stream()
                .flatMap(managerStaffVo -> managerStaffVo.getRoleList().stream())
                .map(ManagerStaffRoleDTO::getRoleName)
                .distinct()
                .collect(Collectors.toList());
        List<Long> shopIds = manager.getScopeList().stream()
                .flatMap(managerStaffVo -> managerStaffVo.getShopList().stream())
                .map(ManagerStaffShopDTO::getShopId)
                .distinct()
                .collect(Collectors.toList());

        reportSalaryDimService.save(reportSalaryDim);
        ReportSalaryDimExtra reportSalaryDimExtra = new ReportSalaryDimExtra();
        reportSalaryDimExtra.setReportSalaryDimId(reportSalaryDim.getId());
        ReportSalaryDimExtra dimExtra = ReportSalaryDimExtra.builder()
                .reportSalaryDimId(reportSalaryDim.getId())
                .roleCodes(roleCodes)
                .roleNames(roleNames)
                .shopIds(shopIds)
                .staffIds(manageStaffIds)
                .build();
        reportSalaryDimExtraService.save(dimExtra);
        return reportSalaryDim.getId();
    }

    public ReportSalaryDimValue convertProjectValueDB(SalaryGroupProjectBO salaryGroupProject, BigDecimal value) {
        ReportSalaryDimValue reportSalaryValue = new ReportSalaryDimValue();
        reportSalaryValue.setCode(salaryGroupProject.getId().toString());
        reportSalaryValue.setCodeType(salaryGroupProject.getCodeType());
        reportSalaryValue.setValue(value);
        reportSalaryValue.setSalaryGroupProjectId(salaryGroupProject.getId());
        return reportSalaryValue;
    }

    public ReportSalaryDimValue convertShopValueDBPcode(SalaryGroupProjectParamVO salaryGroupProjectParam, BigDecimal value,SalaryGroupProjectBO salaryGroupProject) {
        ReportSalaryDimValue reportSalaryValue = new ReportSalaryDimValue();
        reportSalaryValue.setCode(salaryGroupProjectParam.getIndicatorCode());
        reportSalaryValue.setCodeType(IndicatorCodeTypeEnum.INDICATOR);
        reportSalaryValue.setValue(value);
        reportSalaryValue.setSalaryGroupProjectId(salaryGroupProjectParam.getSalaryGroupProjectId());
        reportSalaryValue.setParentCode(salaryGroupProject.getId().toString());
        return reportSalaryValue;
    }


    public ReportSalaryDimValue convertDB(SalaryGroupProjectBO salaryGroupProject, Long reportSalaryDimId, LocalDate date, BigDecimal salaryValue) {
        ReportSalaryDimValue reportSalaryValue = new ReportSalaryDimValue();
        reportSalaryValue.setCode(salaryGroupProject.getId().toString());
        reportSalaryValue.setCodeType(salaryGroupProject.getCodeType());
        if (PublicUtil.isEmpty(salaryValue)) {
            reportSalaryValue.setValue(BigDecimal.ZERO);
        } else {
            reportSalaryValue.setValue(salaryValue);
        }
        reportSalaryValue.setDataDate(date);
        reportSalaryValue.setReportSalaryDimId(reportSalaryDimId);
        reportSalaryValue.setSalaryGroupProjectId(salaryGroupProject.getId());
        return reportSalaryValue;
    }

    public ReportSalaryDimValue convertNoTargetDB(SalaryGroupProjectBO salaryGroupProject,
                                            SalaryGroupProjectParamVO salaryGroupProjectParam,
                                            LocalDate date,
                                            Long reportSalaryDimId,
                                            BigDecimal value) {
        ReportSalaryDimValue reportSalaryValue = new ReportSalaryDimValue();
        reportSalaryValue.setCode(salaryGroupProjectParam.getIndicatorCode());
        reportSalaryValue.setCodeType(IndicatorCodeTypeEnum.INDICATOR);
        reportSalaryValue.setParentCode(salaryGroupProject.getId().toString());
        reportSalaryValue.setValue(value);
        //百分数处理
        if (DataTypeEnum.RATIO.equals(salaryGroupProjectParam.getDataType())){
            reportSalaryValue.setValue(value.multiply(Constant.ONE_HUNDRED));
        }
        reportSalaryValue.setDataDate(date);
        reportSalaryValue.setReportSalaryDimId(reportSalaryDimId);
        reportSalaryValue.setSalaryGroupProjectId(salaryGroupProject.getId());
        return reportSalaryValue;
    }
    public ReportSalaryDimValue convertTargetDB(SalaryGroupProjectBO salaryGroupProject,
                                            SalaryGroupProjectParamVO salaryGroupProjectParam,
                                            LocalDate date,
                                            Long reportSalaryDimId,
                                            BigDecimal value) {
        ReportSalaryDimValue reportSalaryValue = new ReportSalaryDimValue();
        reportSalaryValue.setCode(salaryGroupProjectParam.getIndicatorCode());
        reportSalaryValue.setCodeType(IndicatorCodeTypeEnum.INDICATOR);
        reportSalaryValue.setParentCode(salaryGroupProject.getId().toString());
        //有目标 乘以 100
        reportSalaryValue.setValue(value.multiply(Constant.ONE_HUNDRED));
        reportSalaryValue.setDataDate(date);
        reportSalaryValue.setReportSalaryDimId(reportSalaryDimId);
        reportSalaryValue.setSalaryGroupProjectId(salaryGroupProject.getId());
        return reportSalaryValue;
    }

    public MultiKeyMap<Long, BigDecimal> getUserIndicatorHitMap(List<SalaryGroupProjectBO> salaryGroupProjects, LocalDate date, List<SalaryPool> pools) {
        List<SalaryGroupProjectHitLog> indicatorHitLogs = salaryGroupProjectHitLogService.list(Wrappers.<SalaryGroupProjectHitLog>lambdaQuery()
                .in(SalaryGroupProjectHitLog::getSalaryGroupProjectId, salaryGroupProjects.stream().map(SalaryGroupProjectBO::getId).collect(Collectors.toList()))
                .in(SalaryGroupProjectHitLog::getUserId, pools.stream().map(SalaryPool::getUserId).collect(Collectors.toList()))
                .eq(SalaryGroupProjectHitLog::getDataDate, date)
                .eq(SalaryGroupProjectHitLog::getYn, Boolean.TRUE)
        );
        MultiKeyMap<Long, BigDecimal> userGroupIndicatorHitMap = new MultiKeyMap<>();
        for (SalaryGroupProjectHitLog hitLog : indicatorHitLogs) {
            userGroupIndicatorHitMap.put(hitLog.getUserId(), hitLog.getSalaryGroupProjectId(), hitLog.getSalaryValue());
        }
        return userGroupIndicatorHitMap;
    }

    /**
     * 这个薪酬详情每天6:00 会计算完成,cn.fw.morax.server.task.SalaryCalcTask#cacheCalculableKpiGroup()
     * @param date
     * @param pools
     * @return <薪酬池id: 薪酬池详情list>
     */
    private Map<Long, List<SalaryPoolDetail>> getSalaryPoolDetailMap(LocalDate date, List<SalaryPool> pools) {
        if (CollectionUtils.isEmpty(pools)){
            return Collections.emptyMap();
        }
        List<SalaryPoolDetail> salaryPoolDetailList = salaryPoolDetailService.list(Wrappers.<SalaryPoolDetail>lambdaQuery()
                .in(SalaryPoolDetail::getSalaryPoolId, pools.stream().map(SalaryPool::getId).collect(Collectors.toSet()))
                .eq(SalaryPoolDetail::getSalaryDate, date)
                .eq(SalaryPoolDetail::getYn, Boolean.TRUE));
        if (CollectionUtils.isEmpty(salaryPoolDetailList)){
            return Collections.emptyMap();
        }
        return salaryPoolDetailList.stream().collect(Collectors.groupingBy(SalaryPoolDetail::getSalaryPoolId));
    }

    public Map<Long, SalaryGroupProjectTargetHitLog> queryUserTargetValue(Long referId, Long userId, LocalDate dataDate) {
        List<SalaryGroupProjectTargetHitLog> targetHitLogs = salaryGroupProjectTargetHitLogService.list(Wrappers.<SalaryGroupProjectTargetHitLog>lambdaQuery()
                .eq(SalaryGroupProjectTargetHitLog::getReferId, referId)
                .eq(SalaryGroupProjectTargetHitLog::getTargetType, IndicatorTypeEnum.EXAMINE)
                .eq(SalaryGroupProjectTargetHitLog::getDataDate, dataDate)
                .eq(SalaryGroupProjectTargetHitLog::getUserId, userId)
                .eq(SalaryGroupProjectTargetHitLog::getYn, Boolean.TRUE)
        );
        return targetHitLogs.stream()
                .collect(Collectors.toMap(SalaryGroupProjectTargetHitLog::getUserId, Function.identity(), (v1, v2) -> v1));
    }



    public Map<Long, BigDecimal> queryUserOriginValue(String code, Long userId, LocalDate dataDate) {
        Map<Long, BigDecimal> referValueMap = Maps.newHashMapWithExpectedSize(1);
        //无目标
        LambdaQueryWrapper<IndicatorUserValue> queryWrapper = Wrappers.<IndicatorUserValue>lambdaQuery();
        queryWrapper.eq(IndicatorUserValue::getUserId, userId);
        List<IndicatorUserValue> indicatorUserValues = indicatorUserValueService.list(queryWrapper
                .eq(IndicatorUserValue::getIndicatorCode, code)
                .eq(IndicatorUserValue::getDataDate, dataDate)
                .eq(IndicatorUserValue::getDimensionType, DimensionTypeEnum.STAFF)
                .eq(IndicatorUserValue::getYn, Boolean.TRUE)
        );
        for (IndicatorUserValue userValue : indicatorUserValues) {
            BigDecimal indicatorValue = commonService.queryIndicatorValue(code, userValue);
            referValueMap.put(userValue.getUserId(), indicatorValue);
            //如果原始值是百分比,乘以100,由于业务系统这个可能不准还是配置指标里面的data_type
            //if (IndicatorValueTypeEnum.RATIO.equals(userValue.getValueType())){
            //    referValueMap.put(userValue.getUserId(), indicatorValue.multiply(Constant.ONE_HUNDRED));
            //}
        }
        return referValueMap;
    }

    public ReportSalaryCode createProjectCode(SalaryGroupProjectBO salaryGroupProject,AtomicInteger order) {
        ReportSalaryCode reportSalaryCode = new ReportSalaryCode();
        reportSalaryCode.setSalaryGroupProjectId(salaryGroupProject.getId());
        reportSalaryCode.setCode(salaryGroupProject.getId().toString());
        reportSalaryCode.setCodeType(salaryGroupProject.getCodeType());
        reportSalaryCode.setIndicatorName(salaryGroupProject.getName());
        reportSalaryCode.setOrderNum(order.incrementAndGet());
        return reportSalaryCode;
    }

    public List<ReportSalaryCode> createParamCodes(SalaryGroupProjectBO salaryGroupProject,
                                                   List<SalaryGroupProjectParamVO> salaryGroupProjectParamVos,
                                                   AtomicInteger order) {
        List<ReportSalaryCode> saveReportSalaryCodes = new ArrayList<>(salaryGroupProjectParamVos.size());
        for (SalaryGroupProjectParamVO salaryGroupProjectParam : salaryGroupProjectParamVos) {
            ReportSalaryCode reportSalaryCode = new ReportSalaryCode();
            reportSalaryCode.setSalaryGroupProjectId(salaryGroupProjectParam.getSalaryGroupProjectId());
            reportSalaryCode.setCode(salaryGroupProjectParam.getIndicatorCode());
            reportSalaryCode.setCodeType(IndicatorCodeTypeEnum.INDICATOR);
            reportSalaryCode.setIndicatorName(salaryGroupProjectParam.getIndicatorName());
            reportSalaryCode.setParentCode(salaryGroupProject.getId().toString());
            reportSalaryCode.setOrderNum(order.incrementAndGet());
            saveReportSalaryCodes.add(reportSalaryCode);
        }
        return saveReportSalaryCodes;
    }

    private Long saveReportSalary(SalaryGroup salaryGroup, Long groupId, LocalDate date) {

        ReportSalary reportSalary = new ReportSalary();
        reportSalary.setSalaryGroupId(salaryGroup.getId());
        reportSalary.setSalaryName(salaryGroup.getName());
        //门店id
        reportSalary.setShopIds(salaryGroup.getShopIds());
        reportSalary.setMonthly(YearMonth.from(date));
        reportSalary.setDataDate(date);
        reportSalary.setGroupId(groupId);
        reportSalaryService.save(reportSalary);
        return reportSalary.getId();
    }

    private void cleanData(LocalDate endDate) {
        List<ReportSalary> reportSalaries = reportSalaryService.list(Wrappers.<ReportSalary>lambdaQuery()
//                .eq(ReportSalary::getSalaryGroupId, salaryGroup.getId())
                //.ge(ReportSalary::getDataDate, startDate.with(TemporalAdjusters.firstDayOfMonth()))
                //取当前日期对应月的第一天
                .ge(ReportSalary::getDataDate, endDate.with(TemporalAdjusters.firstDayOfMonth()))
                .le(ReportSalary::getDataDate, endDate)
        );
        if (PublicUtil.isEmpty(reportSalaries)){
            return;
        }
        this.cleanData(reportSalaries);
    }

    /**
     * 清理排名组下报表数据
     * @param reportSalaries
     */
    public void cleanData(List<ReportSalary> reportSalaries) {
        if (CollectionUtils.isEmpty(reportSalaries)){
            return;
        }
        //薪酬排名组ids
        List<Long> reportSalaryIds = reportSalaries.stream().map(ReportSalary::getId).collect(Collectors.toList());
        reportSalaryService.removeByIds(reportSalaryIds);
        reportSalaryCodeService.remove(Wrappers.<ReportSalaryCode>lambdaUpdate()
                .in(ReportSalaryCode::getReportSalaryId, reportSalaryIds)
        );
        //维度的删除要先查询
        List<ReportSalaryDim> reportSalaryDims = reportSalaryDimService.list(Wrappers.<ReportSalaryDim>lambdaQuery()
                .in(ReportSalaryDim::getReportSalaryId, reportSalaryIds)
        );
        if (CollectionUtils.isEmpty(reportSalaryDims)){
            return;
        }
        List<Long> reportSalaryDimIds = reportSalaryDims.stream().map(ReportSalaryDim::getId).collect(Collectors.toList());
        reportSalaryDimService.removeByIds(reportSalaryDimIds);
        reportSalaryDimExtraService.remove(Wrappers.<ReportSalaryDimExtra>lambdaUpdate()
                .in(ReportSalaryDimExtra::getReportSalaryDimId, reportSalaryDimIds)
        );
        reportSalaryDimValueService.remove(Wrappers.<ReportSalaryDimValue>lambdaUpdate()
                .in(ReportSalaryDimValue::getReportSalaryDimId, reportSalaryDimIds)
        );
    }

    public LinkedList<SalaryGroupProjectBO> getProjectBO(Long salaryGroupId) {
        List<SalaryGroupProject> salaryGroupProjects = salaryGroupProjectService.list(Wrappers.<SalaryGroupProject>lambdaQuery()
                .eq(SalaryGroupProject::getSalaryGroupId, salaryGroupId)
                .eq(SalaryGroupProject::getYn, Boolean.TRUE)
                .orderByAsc(SalaryGroupProject::getId)
        );
        if (PublicUtil.isEmpty(salaryGroupProjects)) {
            return new LinkedList<>();
        }
        LinkedList<SalaryGroupProjectBO> projects = new LinkedList();
        for (SalaryGroupProject project : salaryGroupProjects) {
            SalaryGroupProjectBO projectBO = PublicUtil.copy(project, SalaryGroupProjectBO.class);
            switch (projectBO.getCalMethod()) {
                case STAR: {
                    projectBO.setCode(project.getId().toString());
                    List<SalaryGroupProjectParamVO> params = salaryGroupProjectParamService.getSalaryGroupProjectParamVO(projectBO.getId());
                    IndicatorCodeTypeEnum codeType = IndicatorCodeTypeEnum.INDICATOR;
                    //有基本工资指标就不下钻
                    if (PublicUtil.isNotEmpty(params)) {
                        Boolean hasBaseSalary = params.stream().filter(param -> getBaseSalaryCode().equals(param.getIndicatorCode())).findAny().isPresent();
                        if (! hasBaseSalary) {
                            codeType = IndicatorCodeTypeEnum.COMBINE_INDICATOR;
                        }
                    }
                    projectBO.setCodeType(codeType);
                    break;
                }
                case FIXATION:
                case CAR_SERIES: {
                    projectBO.setCode(project.getCommissionCode());
                    projectBO.setCodeType(IndicatorCodeTypeEnum.COMBINE_INDICATOR);
                    break;
                }
                case LADDER: {
                    projectBO.setCode(project.getLadderCode());
                    projectBO.setCodeType(IndicatorCodeTypeEnum.COMBINE_INDICATOR);
                    break;
                }
            }
            //基本工资不能下钻
            if (getBaseSalaryCode().equals(projectBO.getCode())) {
                projectBO.setCodeType(IndicatorCodeTypeEnum.INDICATOR);
            }
            projects.add(projectBO);
        }
        return projects;
    }

    public ReportSalaryDim saveStaffDim(SalaryPool pool, LocalDate date, Long reportSalaryRankId,List<SalaryPoolDetail> salaryPoolDetails){
        ReportSalaryDim reportSalaryDim = new ReportSalaryDim();
        reportSalaryDim.setDimension(ReportDimensionEnum.STAFF);
        reportSalaryDim.setReferId(pool.getUserId());
        reportSalaryDim.setSalaryPoolId(pool.getId());
        reportSalaryDim.setUserId(pool.getUserId());
        reportSalaryDim.setUserName(pool.getUserName());
        reportSalaryDim.setPostId(pool.getPostId());
        reportSalaryDim.setPostName(pool.getPostName());
        reportSalaryDim.setShopId(pool.getShopId());
        reportSalaryDim.setShopName(pool.getShopName());
        reportSalaryDim.setDataDate(date);
        reportSalaryDim.setReportSalaryId(reportSalaryRankId);
        reportSalaryDim.setStarLevel(pool.getStarLevel());
//        KpiPool kpiPool = kpiPoolCommonService.queryPool(pool);
//        if (PublicUtil.isNotEmpty(kpiPool)) {
//            BigDecimal kpiScoreRatio = Optional.ofNullable(kpiPool.getKpiScoreRatio()).orElse(BigDecimal.ZERO);
//            reportSalaryDim.setKpiScoreRatio(kpiScoreRatio.multiply(Constant.ONE_HUNDRED));
//        }
        //薪资类型相关项目处理
        extCaleUserMoney(salaryPoolDetails, reportSalaryDim);
        reportSalaryDimService.save(reportSalaryDim);
        return reportSalaryDim;
    }

    /**
     * 获取 SalaryTypeEnum 对应的薪酬总值
     * @param salaryTypeEnumListMap
     * @param salaryTypeEnum
     * @return
     */
    private BigDecimal getSalaryTypeEnumMoney(Map<SalaryTypeEnum, List<SalaryPoolDetail>> salaryTypeEnumListMap,SalaryTypeEnum salaryTypeEnum){
        if (CollectionUtils.isEmpty(salaryTypeEnumListMap)){
            return BigDecimal.ZERO;
        }
        List<SalaryPoolDetail> list = salaryTypeEnumListMap.get(salaryTypeEnum);
        if (CollectionUtils.isEmpty(list)){
            return BigDecimal.ZERO;
        }
        return list.stream().filter(Objects::nonNull).map(SalaryPoolDetail::getSalaryAmount).reduce(BigDecimal.ZERO, BigDecimal::add);
    }

}