KpiGroupBizService.java 52 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 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114
package cn.fw.morax.service.biz.kpi;

import cn.fw.common.data.mybatis.pagination.PageData;
import cn.fw.common.exception.BusinessException;
import cn.fw.common.page.AppPage;
import cn.fw.common.web.annotation.DisLock;
import cn.fw.common.web.auth.LoginAuthBean;
import cn.fw.morax.common.constant.Constant;
import cn.fw.morax.common.pojo.event.ApprovalResultEvent;
import cn.fw.morax.common.pojo.event.KpiGroupChangeEvent;
import cn.fw.morax.common.utils.DateUtil;
import cn.fw.morax.common.utils.EventBusUtil;
import cn.fw.morax.common.utils.PublicUtil;
import cn.fw.morax.domain.db.ApprovalRecord;
import cn.fw.morax.domain.db.SettingDraft;
import cn.fw.morax.domain.db.kpi.*;
import cn.fw.morax.domain.dto.kpi.*;
import cn.fw.morax.domain.dto.query.KpiGroupQueryDTO;
import cn.fw.morax.domain.dto.query.KpiGroupRepeatQueryDTO;
import cn.fw.morax.domain.enums.*;
import cn.fw.morax.domain.vo.kpi.*;
import cn.fw.morax.service.biz.ApprovalBizService;
import cn.fw.morax.service.biz.CommonService;
import cn.fw.morax.service.data.ApprovalRecordService;
import cn.fw.morax.service.data.SettingDraftService;
import cn.fw.morax.service.data.kpi.*;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

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

import static cn.fw.common.businessvalidator.Validator.BV;

@RequiredArgsConstructor
@Service
@Slf4j
public class KpiGroupBizService {

    private final KpiGroupIndicatorLaddersService kpiGroupIndicatorLaddersService;
    private final KpiGroupIndicatorService kpiGroupIndicatorService;
    private final KpiGroupUserBizService kpiGroupUserBizService;
    private final KpiStarLaddersService kpiStarLaddersService;
    private final KpiGroupDataService kpiGroupDataService;
    private final ApprovalBizService approvalBizService;
    private final ApprovalRecordService approvalRecordService;
    private final CommonService commonService;
    private final IndicatorsService indicatorsService;
    private final SettingDraftService settingDraftService;
    private final KpiGroupService kpiGroupService;
    private final KpiPoolService kpiPoolService;
    private final KpiGroupIndicatorPreconditionService kpiGroupIndicatorPreconditionService;
    private final KpiGroupIndicatorParamService kpiGroupIndicatorParamService;
    private final KpiGroupIndicatorPreconditionLaddersService kpiGroupIndicatorCondLaddersService;
    private final KpiGroupRankStarLaddersService kpiGroupRankStarLaddersService;
    private final KpiGroupRankService kpiGroupRankService;

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

    /**
     * 分页查询
     * @param dto
     * @return
     */
    public AppPage<KpiGroupVO> kpiGroupPage(KpiGroupQueryDTO dto) {
        PageData<KpiGroup> pageData = kpiGroupService.page(new PageData<>(dto.getCurrent(), dto.getPageSize()),
                Wrappers.<KpiGroup>lambdaQuery()
                        .eq(KpiGroup::getGroupId, dto.getGroupId())
                        .eq(PublicUtil.isNotEmpty(dto.getPostId()), KpiGroup::getPostId, dto.getPostId())
                        .eq(PublicUtil.isNotEmpty(dto.getStatus()), KpiGroup::getStatus, dto.getStatus())
                        .eq(KpiGroup::getYn, Boolean.TRUE)
                        .last("ORDER BY FIELD(`status`,3,1,2,4)")
        );

        Map<Long, String> approvalRecordMap = new HashMap<>();
        if (PublicUtil.isNotEmpty(pageData.getRecords())) {
            List<Long> kpiGroupIds = pageData.getRecords().stream().map(KpiGroup::getId).collect(Collectors.toList());
            List<ApprovalRecord> approvalRecords = approvalRecordService.list(Wrappers.<ApprovalRecord>lambdaQuery()
                    .in(ApprovalRecord::getDataId, kpiGroupIds)
                    .eq(ApprovalRecord::getApprovalType, ApprovalTypeEnum.KPI)
                    .eq(ApprovalRecord::getYn, Boolean.TRUE));

            approvalRecordMap = approvalRecords.stream().collect(Collectors.toMap(ApprovalRecord::getDataId, ApprovalRecord::getApprovalNo, (v1, v2) -> v1));
        }
        Map<Long, String> finalApprovalRecordMap = approvalRecordMap;
        return PublicUtil.toPage(pageData, kpiGroup -> {
            KpiGroupVO kpiGroupVo = PublicUtil.copy(kpiGroup, KpiGroupVO.class);
            kpiGroupVo.setApprovalNo(finalApprovalRecordMap.getOrDefault(kpiGroup.getId(), ""));
            kpiGroupVo.setBeginTime(kpiGroup.getBeginTime());
            kpiGroupVo.setOverTime(kpiGroup.getOverTime());
            return kpiGroupVo;
        });
    }

    /**
     * 禁用绩效组
     *
     * @param kpiGroupId
     */
    public void disableKpiGroup(Long kpiGroupId) {
        KpiGroup kpiGroup = kpiGroupService.getById(kpiGroupId);
        BV.notNull(kpiGroup, "绩效配置不存在,请重试");
        BV.isTrue(SettingStatusEnum.EFFECTIVE.equals(kpiGroup.getStatus()), "生效中才能禁用,请重试");

        kpiGroup.setStatus(SettingStatusEnum.DRAFT);
        kpiGroup.setUpdateTime(new Date());
        kpiGroupService.updateById(kpiGroup);

    }

    /**
     * 绩效组排名组合详情
     *
     * @param id
     * @return
     */
    public KpiGroupRankVO kpiGroupRankDetail(Long id) {
        KpiGroupRank kpiGroupRank = kpiGroupRankService.getById(id);
        KpiGroupRankVO kpiGroupRankVO = PublicUtil.copy(kpiGroupRank, KpiGroupRankVO.class);
        kpiGroupRankVO.setKpiGroups(new ArrayList<>());
        for (Long kpiGroupId : kpiGroupRankVO.getKpiGroupIds()) {
            KpiGroupVO kpiGroupVO = this.kpiGroupDetail(kpiGroupId);
            kpiGroupRankVO.getKpiGroups().add(kpiGroupVO);
        }
        List<KpiGroupRankStarLadders> starLadders = kpiGroupRankStarLaddersService.list(Wrappers.<KpiGroupRankStarLadders>lambdaQuery()
                .eq(KpiGroupRankStarLadders::getKpiGroupRankId, id)
                .eq(KpiGroupRankStarLadders::getYn, Boolean.TRUE)
        );
        List<KpiGroupRankStarLaddersVO> starLaddersVOS = PublicUtil.copyList(starLadders, KpiGroupRankStarLaddersVO.class);
        for (KpiGroupRankStarLaddersVO starLaddersVO : starLaddersVOS) {
            starLaddersVO.setUpper(starLaddersVO.getUpper().multiply(Constant.ONE_HUNDRED));
            starLaddersVO.setLower(starLaddersVO.getLower().multiply(Constant.ONE_HUNDRED));
        }
        kpiGroupRankVO.setStarLadders(starLaddersVOS);
        if (PublicUtil.isNotEmpty(kpiGroupRankVO.getRevokedScoreRatio())) {
            kpiGroupRankVO.setRevokedScoreRatio(kpiGroupRankVO.getRevokedScoreRatio().multiply(Constant.ONE_HUNDRED));
        }
        return kpiGroupRankVO;
    }


    /**
     * 绩效组详情
     * @param kpiGroupId
     * @return
     */
    public KpiGroupVO kpiGroupDetail(Long kpiGroupId) {
        KpiGroup kpiGroup = kpiGroupService.getById(kpiGroupId);
        BV.notNull(kpiGroup, "绩效配置不存在,请重试");
        KpiGroupVO kpiGroupVo = KpiGroupVO.convertKpiGroup(kpiGroup);

        //星级数据
        List<KpiStarLadders> starLadders = kpiStarLaddersService.list(Wrappers.<KpiStarLadders>lambdaQuery()
                .eq(KpiStarLadders::getKpiGroupId, kpiGroupVo.getId())
                .eq(KpiStarLadders::getYn, Boolean.TRUE)
        );
        List<KpiStarLaddersVO> starLaddersVos = PublicUtil.copyList(starLadders, KpiStarLaddersVO.class);
        starLaddersVos.stream().forEach(KpiStarLaddersVO::processPercent);
        kpiGroupVo.setStarLadders(starLaddersVos);

        //指标数据
        this.setIndicatorVo(kpiGroupVo);
        return kpiGroupVo;
    }

    /**
     * 设置指标
     *
     * @param kpiGroupVo
     */
    public void setIndicatorVo(KpiGroupVO kpiGroupVo) {
        Long kpiGroupId = kpiGroupVo.getId();
        List<KpiGroupIndicator> indicators = kpiGroupIndicatorService.list(Wrappers.<KpiGroupIndicator>lambdaQuery()
                .eq(KpiGroupIndicator::getKpiGroupId, kpiGroupId)
                .eq(KpiGroupIndicator::getYn, Boolean.TRUE)
        );

        Map<Long, List<KpiGroupIndicatorParamVO>> paramMap = kpiGroupIndicatorParamService.getKpiGroupParamMap(kpiGroupId);
        Map<Long, List<KpiGroupIndicatorPreconditionVO>> condMap = kpiGroupIndicatorPreconditionService.getKpiGroupIndicatorCondVO(kpiGroupId);


        List<KpiGroupIndicatorVO> kpiGroupIndicatorVOS = PublicUtil.copyList(indicators, KpiGroupIndicatorVO.class);
        for (KpiGroupIndicatorVO indicatorVO : kpiGroupIndicatorVOS) {
            Long kpiGroupIndicatorId = indicatorVO.getId();

            //参数-台阶得分
            List<KpiGroupIndicatorParamVO> indicatorParamVOS = paramMap.getOrDefault(kpiGroupIndicatorId, new ArrayList<>());
            Map<ParamTypeEnum, List<KpiGroupIndicatorParamVO>> paramTypeMap = indicatorParamVOS.stream()
                    .collect(Collectors.groupingBy(KpiGroupIndicatorParamVO::getParamType));
            indicatorVO.setCommissionParams(paramTypeMap.getOrDefault(ParamTypeEnum.COMMISSION, new ArrayList<>()));
            indicatorVO.setLadderParams(paramTypeMap.getOrDefault(ParamTypeEnum.LADDER, new ArrayList<>()));

            //前置条件
            List<KpiGroupIndicatorPreconditionVO> preconditionVOS = condMap.getOrDefault(kpiGroupIndicatorId, new ArrayList<>());
            for (KpiGroupIndicatorPreconditionVO cond : preconditionVOS) {

                List<KpiGroupIndicatorPreconditionLaddersVO> condLaddersVOS = kpiGroupIndicatorCondLaddersService.getVOS(
                        cond.getId(), cond.getTargetType(), cond.getDataType());
                cond.setCondLadders(condLaddersVOS);
            }
            Collections.sort(preconditionVOS, Comparator.comparingInt(KpiGroupIndicatorPreconditionVO::getSort));
            indicatorVO.setConds(preconditionVOS);

            //设置目标对象
            setTargetVos(indicatorVO);
        }

        //设置台阶得分阶梯
        List<KpiGroupIndicatorLadders> kpiGroupIndicatorLadders = kpiGroupIndicatorLaddersService.list(Wrappers.<KpiGroupIndicatorLadders>lambdaQuery()
                .in(KpiGroupIndicatorLadders::getKpiGroupIndicatorId,
                        kpiGroupIndicatorVOS.stream().map(KpiGroupIndicatorVO::getId).collect(Collectors.toList()))
                .eq(KpiGroupIndicatorLadders::getYn, Boolean.TRUE)
                .orderByAsc(KpiGroupIndicatorLadders::getId)
        );
        Map<Long, List<KpiGroupIndicatorLadders>> indicatorLaddersMap = kpiGroupIndicatorLadders.stream().collect(Collectors.groupingBy(KpiGroupIndicatorLadders::getKpiGroupIndicatorId));
        for (KpiGroupIndicatorVO indicatorVo : kpiGroupIndicatorVOS) {
            if (indicatorLaddersMap.containsKey(indicatorVo.getId())) {
                List<KpiGroupIndicatorLaddersVO> laddersVos = PublicUtil.copyList(indicatorLaddersMap.get(indicatorVo.getId()), KpiGroupIndicatorLaddersVO.class);
                for (KpiGroupIndicatorLaddersVO laddersVO : laddersVos) {
                    laddersVO.convertLadderToPercent(indicatorVo.getLaddersType());
                }
                indicatorVo.setIndicatorLadders(laddersVos);
            }
        }
        kpiGroupVo.setIndicators(kpiGroupIndicatorVOS);
    }

    /**
     * 装换为目标对象
     *
     * @return
     */
    public void setTargetVos(KpiGroupIndicatorVO indicatorVO) {

        List<KpiGroupIndicatorParamVO> ladderParams = Optional.ofNullable(indicatorVO.getLadderParams()).orElse(new ArrayList<>());
        List<KpiGroupIndicatorParamVO> commissionParams = Optional.ofNullable(indicatorVO.getCommissionParams()).orElse(new ArrayList<>());
        List<KpiGroupIndicatorPreconditionVO> conds =Optional.ofNullable(indicatorVO.getConds()).orElse(new ArrayList<>());

        List<KpiGroupIndicatorTargetVO> targetVOS = new ArrayList<>();
        for (KpiGroupIndicatorParamVO paramVO : ladderParams) {
            if (PublicUtil.isNotEmpty(paramVO.getTargetType())) {
                KpiGroupIndicatorTargetVO targetVO = PublicUtil.copy(paramVO, KpiGroupIndicatorTargetVO.class);
                targetVOS.add(targetVO);
            }
        }

        for (KpiGroupIndicatorParamVO paramVO : commissionParams) {
            if (PublicUtil.isNotEmpty(paramVO.getTargetType())) {
                KpiGroupIndicatorTargetVO targetVO = PublicUtil.copy(paramVO, KpiGroupIndicatorTargetVO.class);
                targetVOS.add(targetVO);
            }
        }

        for (KpiGroupIndicatorPreconditionVO preconditionVO : conds) {
            if (PublicUtil.isNotEmpty(preconditionVO.getTargetType())) {
                KpiGroupIndicatorTargetVO targetVO = PublicUtil.copy(preconditionVO, KpiGroupIndicatorTargetVO.class);
                targetVOS.add(targetVO);
            }
        }

        indicatorVO.setTargets(targetVOS);
    }

    /**
     * 装换为目标对象
     *
     * @return
     */
    public void setTargetVos(KpiGroupDTO kpiGroupDTO) {

        for (KpiGroupIndicatorDTO indicatorDTO : kpiGroupDTO.getIndicators()) {
            List<KpiGroupIndicatorParamDTO> ladderParams = Optional.ofNullable(indicatorDTO.getLadderParams()).orElse(new ArrayList<>());
            List<KpiGroupIndicatorParamDTO> commissionParams = Optional.ofNullable(indicatorDTO.getCommissionParams()).orElse(new ArrayList<>());
            List<KpiGroupIndicatorPreconditionDTO> conds = Optional.ofNullable(indicatorDTO.getConds()).orElse(new ArrayList<>());

            List<KpiGroupIndicatorTargetVO> targetVOS = new ArrayList<>();
            for (KpiGroupIndicatorParamDTO paramDTO : ladderParams) {
                if (PublicUtil.isNotEmpty(paramDTO.getTargetType()) && (! TargetTypeEnum.NO.equals(paramDTO.getTargetType()))) {
                    KpiGroupIndicatorTargetVO targetVO = PublicUtil.copy(paramDTO, KpiGroupIndicatorTargetVO.class);
                    targetVOS.add(targetVO);
                }
            }

            for (KpiGroupIndicatorParamDTO paramDTO : commissionParams) {
                if (PublicUtil.isNotEmpty(paramDTO.getTargetType()) && (! TargetTypeEnum.NO.equals(paramDTO.getTargetType()))) {
                    KpiGroupIndicatorTargetVO targetVO = PublicUtil.copy(paramDTO, KpiGroupIndicatorTargetVO.class);
                    targetVOS.add(targetVO);
                }
            }

            for (KpiGroupIndicatorPreconditionDTO preconditionDTO : conds) {
                if (PublicUtil.isNotEmpty(preconditionDTO.getTargetType()) && (! TargetTypeEnum.NO.equals(preconditionDTO.getTargetType()))) {
                    KpiGroupIndicatorTargetVO targetVO = PublicUtil.copy(preconditionDTO, KpiGroupIndicatorTargetVO.class);
                    targetVOS.add(targetVO);
                }
            }

            indicatorDTO.setTargets(targetVOS);
        }
    }

    /**
     * 绩效组保存
     * @param dto
     */
    @Transactional(rollbackFor = Exception.class)
    @DisLock(prefix = "#this.getSavePrefix()", key = "#dto.getPostId()", message = "保存中,请勿重复操作")
    public KpiGroupSavePromptVO saveKpi(KpiGroupDTO dto, LoginAuthBean user, Boolean submit) {
        //初始化数据
//        this.initKpi(dto);
        //检查数据
        this.checkKpi(dto);
        this.checkNameRepetition(dto.getId(), dto.getName(), dto.getDraftId());
        this.checkKpiLadders(dto.getIndicators());
        this.checkStarLadders(dto.getStarLadders(), dto.getStarEvaluationType());
        KpiGroupSavePromptVO promptVo = this.checkShopKpiRepeat(dto);
        if (promptVo.getPrompt()) {
            return promptVo;
        }
        setTargetVos(dto);
        SettingDraft settingDraft = getSettingDraft(dto, submit);
        settingDraftService.saveOrUpdate(settingDraft);
        if (! submit) {
            return new KpiGroupSavePromptVO(false);
        }
        Integer staffNum = kpiGroupUserBizService.queryShopPostCurStaffNum(dto.getPostId(), dto.getShopIds());
        approvalBizService.applyApproveKpiDraft(dto, settingDraft, user, staffNum);
        return new KpiGroupSavePromptVO(false);
    }

    /**
     * 绩效组保存
     * @param dto
     */
    @Transactional(rollbackFor = Exception.class)
    @DisLock(prefix = "#this.getSavePrefix()", key = "#dto.getName()", message = "保存中,请勿重复操作")
    public KpiGroupSavePromptVO saveKpiGroupRankDraft(KpiGroupRankDTO dto, LoginAuthBean user, Boolean submit) {
        checkNameRepetition(dto.getId(), dto.getName());
        checkRankStarLadders(dto.getStarLadders(), dto.getStarEvaluationType());
        this.initKpi(dto);
        for (KpiGroupDTO kpiGroupDTO : dto.getKpiGroups()) {
            //检查数据
            this.checkKpi(kpiGroupDTO);
            this.checkNameRepetition(kpiGroupDTO.getId(), kpiGroupDTO.getName(), kpiGroupDTO.getDraftId());
            this.checkKpiLadders(kpiGroupDTO.getIndicators());
//            KpiGroupSavePromptVO promptVo = this.checkShopKpiRepeat(kpiGroupDTO);
//            if (promptVo.getPrompt()) {
//                return promptVo;
//            }
            setTargetVos(kpiGroupDTO);
        }

        SettingDraft settingDraft = getSettingDraft(dto, submit);
        settingDraftService.saveOrUpdate(settingDraft);
        if (! submit) {
            return new KpiGroupSavePromptVO(false);
        }
        approvalBizService.applyApproveKpiRankDraft(dto, settingDraft, user);
        return new KpiGroupSavePromptVO(false);
    }


    /**
     * 获取草稿
     *
     * @param dto
     * @return
     */
    public SettingDraft getSettingDraft(KpiGroupRankDTO dto, Boolean submit) {
        SettingDraft settingDraft = null;
        if (PublicUtil.isEmpty(dto.getDraftId())) {
            settingDraft = new SettingDraft();
            settingDraft.setGroupId(dto.getGroupId());
            settingDraft.setYn(Boolean.TRUE);
            settingDraft.setType(SettingDraftTypeEnum.KPI_GROUP_RANK);
        } else {
            settingDraft = settingDraftService.getById(dto.getDraftId());
            BV.notNull(settingDraft, "草稿配置不存在,请重试");
        }

        List<Long> postIds = dto.getKpiGroups().stream().map(KpiGroupDTO::getPostId).distinct().collect(Collectors.toList());
        List<Long> shopIds = dto.getKpiGroups().stream().flatMap(kpiGroup -> kpiGroup.getShopIds().stream()).distinct().collect(Collectors.toList());
        settingDraft.setPostIds(postIds);
        settingDraft.setShopIds(shopIds);
        List<KpiGroupRankBaseInfoDTO> baseInfoDTOs = dto.getKpiGroups().stream().map(kpiGroup -> {
            return new KpiGroupRankBaseInfoDTO(kpiGroup);
        }).collect(Collectors.toList());
        settingDraft.setBaseInfo(JSON.toJSONString(baseInfoDTOs));
        settingDraft.setStatus(submit ? SettingDraftStatusEnum.RELEASE_APPROVAL : SettingDraftStatusEnum.NO_RELEASE);
        settingDraft.setName(dto.getName());
        settingDraft.setContent(JSONObject.toJSONString(dto));
        return settingDraft;
    }

    /**
     * 获取草稿
     *
     * @param dto
     * @return
     */
    public SettingDraft getSettingDraft(KpiGroupDTO dto, Boolean submit) {
        SettingDraft settingDraft = null;
        if (PublicUtil.isEmpty(dto.getDraftId())) {
            settingDraft = new SettingDraft();
            settingDraft.setGroupId(dto.getGroupId());
            settingDraft.setYn(Boolean.TRUE);
            settingDraft.setType(SettingDraftTypeEnum.KPI);
            settingDraft.setPostId(dto.getPostId());
            settingDraft.setShopIds(dto.getShopIds());
        } else {
            settingDraft = settingDraftService.getById(dto.getDraftId());
            BV.notNull(settingDraft, "草稿配置不存在,请重试");
        }
        settingDraft.setStatus(submit ? SettingDraftStatusEnum.RELEASE_APPROVAL : SettingDraftStatusEnum.NO_RELEASE);
        settingDraft.setName(dto.getName());
        settingDraft.setContent(JSONObject.toJSONString(dto));
        return settingDraft;
    }


    /**
     * 检查绩效组排名名称是否重复
     *
     * @param id
     * @param name
     */
    public void checkNameRepetition(Long id, String name) {
        int count = kpiGroupRankService.count(Wrappers.<KpiGroupRank>lambdaQuery()
                .eq(KpiGroupRank::getName, name)
                .ne(PublicUtil.isNotEmpty(id), KpiGroupRank::getId, id)
                .eq(KpiGroupRank::getYn, Boolean.TRUE)
        );
        BV.isTrue(count <= 0, "绩效组排名名称重复,请重新输入");
    }

    /**
     * 检查绩效组配置状态
     *
     * @param dto
     */
    public void checkKpi(KpiGroupDTO dto) {
        Long postId = dto.getPostId();
        List<Long> shopIds = dto.getShopIds();
//        List<KpiGroup> effectKpis = kpiGroupService.getRepeatKpis(postId, shopIds, dto.getId(), dto.getBeginTime());
//        if (PublicUtil.isNotEmpty(effectKpis)) {
//            Optional<KpiGroup> optional = effectKpis.stream()
//                    .filter(kpi -> ! kpi.getStatus().equals(SettingStatusEnum.INEFFECTIVE)).findFirst();
//            if (optional.isPresent()) {
//                KpiGroup kpiGroup = optional.get();
//                List<String> shopNames = new ArrayList<>(kpiGroup.getShopNames());
//                shopNames.retainAll(dto.getShopNames());
//                throw new BusinessException("绩效组门店【" + String.join(",", shopNames) + "】存在" +
//                        kpiGroup.getStatus().getName() + "配置");
//            }
//        }
        List<SettingDraft> settingDrafts = settingDraftService.getRepeatApprovals(postId, shopIds, SettingDraftTypeEnum.KPI,
                SettingDraftStatusEnum.RELEASE_APPROVAL, dto.getBeginTime());
        if (PublicUtil.isNotEmpty(settingDrafts)) {
            throw new BusinessException("绩效组门店存在正在生效中配置");
        }

        for (KpiGroupIndicatorDTO indicator : dto.getIndicators()) {
            if (IndicatorCodeTypeEnum.COMBINE_INDICATOR.equals(indicator.getCodeType())){
                if (PublicUtil.isEmpty(indicator.getCode())){
                    throw new BusinessException("指标库["+indicator.getName()+"]台阶参数选择为组合指标时,必须传入对应的组合指标编码!");
                }
            }
            if (PublicUtil.isNotEmpty(indicator.getLadderParams())) {
                BigDecimal proportion = indicator.getLadderParams().stream()
                        .map(KpiGroupIndicatorParamDTO::getProportion)
                        .reduce(BigDecimal.ZERO, BigDecimal::add);
                BV.isTrue(Constant.ONE_HUNDRED.compareTo(proportion) == 0, "【" + indicator.getName() + "】台阶占比总和必须为100");

                for (KpiGroupIndicatorParamDTO commissionParam : indicator.getLadderParams()) {
                    if (! TargetTypeEnum.NO.equals(commissionParam.getTargetType()) &&
                            (PublicUtil.isEmpty(commissionParam.getTargetType()) || PublicUtil.isEmpty(commissionParam.getTargetValue()))) {
                        commissionParam.setTargetType(TargetTypeEnum.NO);
                    }
                }
            }

            if (PublicUtil.isNotEmpty(indicator.getCommissionParams())) {
                BigDecimal proportion = indicator.getCommissionParams().stream()
                        .map(KpiGroupIndicatorParamDTO::getProportion)
                        .reduce(BigDecimal.ZERO, BigDecimal::add);
                BV.isTrue(Constant.ONE_HUNDRED.compareTo(proportion) == 0, "【" + indicator.getName() + "】提成占比总和必须为100");

                for (KpiGroupIndicatorParamDTO commissionParam : indicator.getCommissionParams()) {
                    if (! TargetTypeEnum.NO.equals(commissionParam.getTargetType()) &&
                            (PublicUtil.isEmpty(commissionParam.getTargetType()) || PublicUtil.isEmpty(commissionParam.getTargetValue()))) {
                        commissionParam.setTargetType(TargetTypeEnum.NO);
                    }
                }
            }


            if (PublicUtil.isNotEmpty(indicator.getConds())) {
                for (KpiGroupIndicatorPreconditionDTO preconditionDTO : indicator.getConds()) {
                    if (! TargetTypeEnum.NO.equals(preconditionDTO.getTargetType()) &&
                            (PublicUtil.isEmpty(preconditionDTO.getTargetType()) || PublicUtil.isEmpty(preconditionDTO.getTargetValue()))) {
                        preconditionDTO.setTargetType(TargetTypeEnum.NO);
                    }
                }
            }

        }

        //原来的绩效组配置不能在审批中
        if (PublicUtil.isEmpty(dto.getId())) {
            return;
        }
        KpiGroup kpiGroup = kpiGroupService.getById(dto.getId());
//        BV.notNull(kpiGroup, "绩效配置不存在,请重试");
        if (PublicUtil.isNotEmpty(kpiGroup)) {
            BV.isFalse((SettingStatusEnum.APPROVING.equals(kpiGroup.getStatus())), "审批中的绩效组配置不能编辑");
            dto.setKgc(kpiGroup.getKgc());
        }
    }

    /**
     * 检查绩效组排名名称是否重复
     *
     * @param id
     * @param name
     */
    public void checkNameRepetition(Long id, String name, Long draftId) {
        int count = kpiGroupService.count(Wrappers.<KpiGroup>lambdaQuery()
                .eq(KpiGroup::getName, name)
                .ne(PublicUtil.isNotEmpty(id), KpiGroup::getId, id)
                .eq(KpiGroup::getYn, Boolean.TRUE)
                .eq(KpiGroup::getStatus, SettingStatusEnum.EFFECTIVE)
        );
//        BV.isTrue(count <= 0, "绩效组名称重复,请重新输入");
//        if (count > 0) {
//            log.info("绩效组名称重复,name:{},id:{}: ", name, Optional.ofNullable(id).orElse(0L).toString());
//            throw new BusinessException("绩效组名称重复,请重新输入");
//        }

        List<SettingDraft> drafts = commonService.getEditDraftByName(name, SettingDraftTypeEnum.KPI, draftId);
        BV.isTrue(drafts.size() <= 0, "绩效组名称在草稿中存在,请重新输入");
    }

    /**
     * 检查指标修改的权限
     * @param dto
     */
    private void initKpi(KpiGroupRankDTO dto) {
        LocalDate currentTime = LocalDate.now();
        dto.setBeginTime((EffectMonthEnum.CURRENT_MONTH.equals(dto.getBeginTimeType()) ? currentTime : PublicUtil.getNextMonthFirstDay()));
    }

    /**
     * 检查绩效组配置是否重复
     * 同月
     * 之前没有这些门店配置,不提示
     * 有这些门店配置
     *      1)门店和之前相同不提示
     *      2)门店比之前少,之前ABC门店,现A门店,提示BC门店缺失绩效组配置
     *      3)门店比之前多,配置1 ABC门店, 配置2 DE门店,新增ABCD门店,提示E门店缺失绩效配置
     * @param kpiGroupDTO
     */
    private KpiGroupSavePromptVO checkShopKpiRepeat(KpiGroupDTO kpiGroupDTO) {
        //强制提交,退出检查
//        if (kpiGroupDTO.getForce()) {
//            return new KpiGroupSavePromptVO(false);
//        }

        YearMonth yearMonth = YearMonth.now();
        YearMonth beginTime = YearMonth.from(kpiGroupDTO.getBeginTime());
        StringBuilder msgBuilder = new StringBuilder();
        if (yearMonth.equals(beginTime)) {
            KpiGroupRepeatQueryDTO effectRepeatDTO = KpiGroupRepeatQueryDTO.convertDto(kpiGroupDTO, SettingStatusEnum.EFFECTIVE);
            List<KpiGroup> effectKpiGroups = kpiGroupService.queryRepeatKpiGroup(effectRepeatDTO);
            if (PublicUtil.isNotEmpty(effectKpiGroups)) {
                msgBuilder.append("审批通过后").append(yearMonth.getMonth().getValue()).append("月份已生效绩效组配置会被移除,门店【");
                HashSet<String> shopNames = effectKpiGroups.stream().map(KpiGroup::getShopNames).collect(HashSet::new, HashSet::addAll, HashSet::addAll);
                msgBuilder.append(String.join(",", shopNames));
                msgBuilder.append("】。");
            }
        }
        KpiGroupRepeatQueryDTO beEffectRepeatDTO = KpiGroupRepeatQueryDTO.convertDto(kpiGroupDTO, SettingStatusEnum.BE_EFFECTIVE);
        List<KpiGroup> beKpiGroups = kpiGroupService.queryRepeatKpiGroup(beEffectRepeatDTO);
        if (PublicUtil.isNotEmpty(beKpiGroups)) {
            if (msgBuilder.length() == 0) {
                msgBuilder.append("审批通过后");
            }
            Map<LocalDate, List<KpiGroup>> monthKpiMap = beKpiGroups.stream().collect(Collectors.groupingBy(KpiGroup::getBeginTime));
            for (Map.Entry<LocalDate, List<KpiGroup>> monthKpi : monthKpiMap.entrySet()) {
                msgBuilder.append(monthKpi.getKey().getMonth().getValue()).append("月份待生效绩效组配置会被移除,门店【");
                HashSet<String> shopNames = monthKpi.getValue().stream().map(KpiGroup::getShopNames).collect(HashSet::new, HashSet::addAll, HashSet::addAll);
                msgBuilder.append(String.join(",", shopNames));
            }
            msgBuilder.append("】。");
        }
        if (msgBuilder.length() == 0) {
            return new KpiGroupSavePromptVO(false);
        }
        return new KpiGroupSavePromptVO(true, msgBuilder.toString());
    }

    /**
     * 检查阶梯分值
     * @param indicators
     */
    private void checkKpiLadders(List<KpiGroupIndicatorDTO> indicators) {
        Integer baseScore = null;
        List<KpiGroupIndicatorLaddersDTO> indicatorLadders = null;
        for (KpiGroupIndicatorDTO indicatorDto : indicators) {
            if (ScoreWayEnum.NORMAL.equals(indicatorDto.getScoreWay())) {
                continue;
            }
            BV.isTrue(PublicUtil.isNotEmpty(indicatorDto.getLadderParams()), "阶梯得分计算,台阶参数不能为空");
            BV.isTrue(PublicUtil.isNotEmpty(indicatorDto.getIndicatorLadders()), "阶梯得分计算,台阶不能为空");
            baseScore = indicatorDto.getBaseScore();
            indicatorLadders = indicatorDto.getIndicatorLadders();
            Collections.sort(indicatorLadders);

            //阶梯值校验  标准分不能超过指标基础分,阶梯值必须连续
            for (KpiGroupIndicatorLaddersDTO laddersDtos : indicatorLadders) {
                //阶梯标准分不能超过绩效分值
                if (laddersDtos.getStandardScore().compareTo(baseScore) > 0) {
                    throw new BusinessException("【" + indicatorDto.getName() + "】的阶梯标准分不能超过绩效分值");
                }
            }
            //校验阶梯
            CommonService.checkLadders(indicatorLadders, indicatorDto.getName());

            //校验条件
            if (PublicUtil.isNotEmpty(indicatorDto.getConds())) {
                for (KpiGroupIndicatorPreconditionDTO condDTO : indicatorDto.getConds()) {
                    BV.isTrue(PublicUtil.isNotEmpty(condDTO.getCondLadders()), "得分条件台阶不能为空");
                    CommonService.checkLadders(condDTO.getCondLadders(), indicatorDto.getName());
                }
            }

            //赋空值
            if (PublicUtil.isEmpty(indicatorDto.getLadderParams())) {
                indicatorDto.setLadderParams(new ArrayList<>());
            }
            if (PublicUtil.isEmpty(indicatorDto.getCommissionParams())) {
                indicatorDto.setCommissionParams(new ArrayList<>());
            }
            if (PublicUtil.isEmpty(indicatorDto.getConds())) {
                indicatorDto.setConds(new ArrayList<>());
            }

        }
    }


    /**
     * 检查星级阶梯分值
     * 1. 赋初始值
     * 2. 校验连续性、上限下限大小、所有星级都已经配置
     * @param laddersDTOS
     */
    private void checkRankStarLadders(List<KpiGroupRankStarLaddersDTO> laddersDTOS, StarEvaluationEnum starEvaluationType) {
        Set<StarLevelEnum> levelEnumSet = Arrays.stream(StarLevelEnum.values()).collect(Collectors.toSet());
        Collections.sort(laddersDTOS, new Comparator<KpiGroupRankStarLaddersDTO>() {
            @Override
            public int compare(KpiGroupRankStarLaddersDTO o1, KpiGroupRankStarLaddersDTO o2) {
                if (starEvaluationType.equals(StarEvaluationEnum.SCORING_RATE)) {
                    return o2.getLevel().getValue() - o1.getLevel().getValue();
                } else {
                    return o1.getLevel().getValue() - o2.getLevel().getValue();
                }
            }
        });
        //校验阶梯
        CommonService.checkLadders(laddersDTOS);
        //阶梯值校验  标准分不能超过指标基础分,阶梯值必须连续
        for (KpiGroupRankStarLaddersDTO dto : laddersDTOS) {
            if (! levelEnumSet.remove(dto.getLevel())) {
                throw new BusinessException("【" + dto.getLevel().getName() + "】级的阶梯配置重复");
            }
        }
        if (levelEnumSet.size() != 0) {
            List<String> levels = levelEnumSet.stream().map(level -> {
                return level.getName() + "级";
            }).collect(Collectors.toList());
            throw new BusinessException("【" + String.join(",", levels) + "】阶梯未配置");
        }
    }

    /**
     * 检查星级阶梯分值
     * 1. 赋初始值
     * 2. 校验连续性、上限下限大小、所有星级都已经配置
     * @param laddersDTOS
     */
    private void checkStarLadders(List<KpiStarLaddersDTO> laddersDTOS, StarEvaluationEnum starEvaluationType) {
        Set<StarLevelEnum> levelEnumSet = Arrays.stream(StarLevelEnum.values()).collect(Collectors.toSet());
        Collections.sort(laddersDTOS, new Comparator<KpiStarLaddersDTO>() {
            @Override
            public int compare(KpiStarLaddersDTO o1, KpiStarLaddersDTO o2) {
                if (starEvaluationType.equals(StarEvaluationEnum.SCORING_RATE)) {
                    return o2.getLevel().getValue() - o1.getLevel().getValue();
                } else {
                    return o1.getLevel().getValue() - o2.getLevel().getValue();
                }
            }
        });
        //校验阶梯
        CommonService.checkLadders(laddersDTOS);
        //阶梯值校验  标准分不能超过指标基础分,阶梯值必须连续
        for (KpiStarLaddersDTO dto : laddersDTOS) {
            if (! levelEnumSet.remove(dto.getLevel())) {
                throw new BusinessException("【" + dto.getLevel().getName() + "】级的阶梯配置重复");
            }
        }
        if (levelEnumSet.size() != 0) {
            List<String> levels = levelEnumSet.stream().map(level -> {
                return level.getName() + "级";
            }).collect(Collectors.toList());
            throw new BusinessException("【" + String.join(",", levels) + "】阶梯未配置");
        }
    }

    /**
     * 审批kpiGroup
     * 生效时间 在 当前时间 之前,那么这个审批是无效的
     * 次月生效
     * 1. 将次月生效的重复绩效配置设置为失效,等待月定时器执行
     * 当月生效
     * 1. 将当月生效的重复绩效配置设置为失效,将之前配置设置为无效,将状态设置为生效中
     * @param approvalRecord
     * @param result
     */
    @Transactional(rollbackFor = Exception.class)
    public void approvalKpiGroupDraft(ApprovalRecord approvalRecord, ApprovalResultEvent result) {
        log.info("收到绩效组配置变更审批信息:{}", JSON.toJSONString(approvalRecord));

        SettingDraft settingDraft = settingDraftService.getById(approvalRecord.getDataId());
        BV.isTrue(PublicUtil.isNotEmpty(settingDraft), "考评草稿数据不存在");

        SettingDraftStatusEnum draftStatus = (result.getAgree()) ? SettingDraftStatusEnum.RELEASE_APPROVAL_AGREE :
                SettingDraftStatusEnum.RELEASE_APPROVAL_REJECT;

        if (! result.getAgree()) {
            if (! SettingDraftStatusEnum.RELEASE_APPROVAL_CANCEL.equals(settingDraft.getStatus())) {
                settingDraftService.update(Wrappers.<SettingDraft>lambdaUpdate()
                        .set(SettingDraft::getStatus, draftStatus)
                        .set(SettingDraft::getUpdateTime, new Date())
                        .eq(SettingDraft::getId, settingDraft.getId())
                );
            }
            return;
        }

        KpiGroupDTO kpiGroupDTO = JSON.parseObject(settingDraft.getContent(), KpiGroupDTO.class);
        KpiGroup kpiGroup = kpiGroupDataService.saveKpiGroup(kpiGroupDTO);
        kpiGroupDataService.saveKpiIndicators(kpiGroupDTO.getIndicators(), kpiGroup);
        kpiGroupDataService.saveKpiStarLadders(kpiGroupDTO.getStarLadders(), kpiGroup);

        settingDraftService.update(Wrappers.<SettingDraft>lambdaUpdate()
                .set(SettingDraft::getUnionId, kpiGroup.getId())
                .set(SettingDraft::getStatus, draftStatus)
                .set(SettingDraft::getUpdateTime, new Date())
                .eq(SettingDraft::getId, settingDraft.getId())
        );

        //通知绩效组人员
        KpiGroupChangeEvent kpiGroupChangeEvent = PublicUtil.copy(kpiGroup, KpiGroupChangeEvent.class);
        EventBusUtil.asyncPost(kpiGroupChangeEvent);

        YearMonth yearMonth = YearMonth.now();
        YearMonth beginTime = YearMonth.from(kpiGroup.getBeginTime());
        kpiGroup.getBeginTime();
        if (yearMonth.isAfter(beginTime)) {
            log.info("审批通过时间在绩效组生效时间之后,等待定时器执行");
            return;
        }

        //处理重复绩效组配置数据
        this.processRepeatKpiGroup(kpiGroup);
    }

    /**
     * 审批kpiGroup
     * 生效时间 在 当前时间 之前,那么这个审批是无效的
     * 次月生效
     * 1. 将次月生效的重复绩效配置设置为失效,等待月定时器执行
     * 当月生效
     * 1. 将当月生效的重复绩效配置设置为失效,将之前配置设置为无效,将状态设置为生效中
     * @param approvalRecord
     */
    @Transactional(rollbackFor = Exception.class)
    public void saveKpiGroupRankDraft(ApprovalRecord approvalRecord, SettingDraft settingDraft) {
        log.info("收到绩效组配置变更审批信息:{}", JSON.toJSONString(approvalRecord));
        KpiGroupRankDTO kpiGroupRankDTO = JSON.parseObject(settingDraft.getContent(), KpiGroupRankDTO.class);
        EffectMonthEnum effectMonth = kpiGroupRankDTO.getBeginTimeType();
        List<Long> kpiGroupIds = new ArrayList<>();
        for (KpiGroupDTO kpiGroupDTO : kpiGroupRankDTO.getKpiGroups()) {
            kpiGroupDTO.setBeginTime(kpiGroupRankDTO.getBeginTime());
            kpiGroupDTO.setGroupId(kpiGroupRankDTO.getGroupId());
            KpiGroup kpiGroup = kpiGroupDataService.saveKpiGroup(kpiGroupDTO);
            kpiGroupIds.add(kpiGroup.getId());
            kpiGroupDataService.saveKpiIndicators(kpiGroupDTO.getIndicators(), kpiGroup);
            //通知绩效组人员
            KpiGroupChangeEvent kpiGroupChangeEvent = PublicUtil.copy(kpiGroup, KpiGroupChangeEvent.class);
            EventBusUtil.asyncPost(kpiGroupChangeEvent);
            if (effectMonth.equals(EffectMonthEnum.NEXT_MONTH)) {
                log.info("审批通过时间在绩效组生效时间之后,等待定时器执行");
                continue;
            }
            //处理重复绩效组配置数据
            this.processRepeatKpiGroup(kpiGroup);
        }
        if (PublicUtil.isNotEmpty(kpiGroupRankDTO.getId())) {
            kpiGroupRankService.update(Wrappers.<KpiGroupRank>lambdaUpdate()
                    .set(KpiGroupRank::getStatus, SettingStatusEnum.INEFFECTIVE)
                    .set(KpiGroupRank::getUpdateTime, new Date())
                    .eq(KpiGroupRank::getId, settingDraft.getId())
            );
        }
        KpiGroupRank kpiGroupRank = this.convertPO(kpiGroupRankDTO, kpiGroupIds);
        kpiGroupRankService.saveOrUpdate(kpiGroupRank);
        this.inEffectiveRank(kpiGroupRank.getGroupId());
        this.saveKpiGroupRankStarLadders(kpiGroupRankDTO, kpiGroupRank);
        settingDraftService.update(Wrappers.<SettingDraft>lambdaUpdate()
                .set(SettingDraft::getUnionId, kpiGroupRank.getId())
                .set(SettingDraft::getUpdateTime, new Date())
                .eq(SettingDraft::getId, settingDraft.getId())
        );
    }

    /**
     * 失效绩效组为空的排名组
     * @param groupId
     */
    @Transactional(rollbackFor = Exception.class)
    public void inEffectiveRank(Long groupId) {
        List<KpiGroupRank> kpiGroupRanks = kpiGroupRankService.list(Wrappers.<KpiGroupRank>lambdaQuery()
                .eq(KpiGroupRank::getStatus, SettingStatusEnum.EFFECTIVE)
                .eq(KpiGroupRank::getYn, Boolean.TRUE)
                .eq(KpiGroupRank::getGroupId, groupId)
        );
        for (KpiGroupRank kpiGroupRank : kpiGroupRanks) {
            int count = kpiGroupService.count(Wrappers.<KpiGroup>lambdaQuery()
                    .in(KpiGroup::getId, kpiGroupRank.getKpiGroupIds())
                    .eq(KpiGroup::getYn, Boolean.TRUE)
                    .eq(KpiGroup::getStatus, SettingStatusEnum.EFFECTIVE)
            );
            if (count <= 0) {
                kpiGroupRank.setEndTime(LocalDate.now().minusDays(1));
                kpiGroupRank.setStatus(SettingStatusEnum.INEFFECTIVE);
                kpiGroupRankService.updateById(kpiGroupRank);
            }
        }

    }

    /**
     * 保存绩效星级评定阶梯
     *
     * @param dto
     * @param kpiGroupRank
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public void saveKpiGroupRankStarLadders(KpiGroupRankDTO dto, KpiGroupRank kpiGroupRank) {
        if (PublicUtil.isNotEmpty(dto.getId())) {
            kpiGroupRankStarLaddersService.update(Wrappers.<KpiGroupRankStarLadders>lambdaUpdate()
                    .eq(KpiGroupRankStarLadders::getKpiGroupRankId, dto.getId())
                    .eq(KpiGroupRankStarLadders::getYn, Boolean.TRUE)
                    .set(KpiGroupRankStarLadders::getYn, Boolean.FALSE)
            );
        }
        List<KpiGroupRankStarLaddersDTO> starLaddersDtos = dto.getStarLadders();
        List<KpiGroupRankStarLadders> starLadders = Lists.newArrayListWithCapacity(starLaddersDtos.size());
        Long kpiGroupRankId = kpiGroupRank.getId();
        KpiGroupRankStarLadders starLadder = null;
        for (KpiGroupRankStarLaddersDTO starLaddersDto : starLaddersDtos) {
            starLadder = PublicUtil.copy(starLaddersDto, KpiGroupRankStarLadders.class);
            starLadder.setUpper(starLadder.getUpper().divide(Constant.ONE_HUNDRED, 2, RoundingMode.HALF_UP));
            starLadder.setLower(starLadder.getLower().divide(Constant.ONE_HUNDRED, 2, RoundingMode.HALF_UP));
            starLadder.setKpiGroupRankId(kpiGroupRankId);
            starLadders.add(starLadder);
        }
        kpiGroupRankStarLaddersService.saveBatch(starLadders);
    }

    /**
     * 转换对象
     *
     * @param dto
     * @return
     */
    public KpiGroupRank convertPO(KpiGroupRankDTO dto, List<Long> kpiGroupIds) {
        KpiGroupRank kpiGroupRank = new KpiGroupRank();
        kpiGroupRank.setStatus(SettingStatusEnum.EFFECTIVE);
        kpiGroupRank.setKpiGroupIds(kpiGroupIds);
        kpiGroupRank.setGroupId(dto.getGroupId());
        kpiGroupRank.setYn(Boolean.TRUE);
        kpiGroupRank.setName(dto.getName());
        kpiGroupRank.setStarEvaluationType(dto.getStarEvaluationType());
        if (EffectMonthEnum.CURRENT_MONTH.equals(dto.getBeginTimeType())) {
            kpiGroupRank.setBeginTime(LocalDate.now());
        }
        if (PublicUtil.isNotEmpty(dto.getRevokedScoreRatio())) {
            kpiGroupRank.setRevokedScoreRatio(dto.getRevokedScoreRatio().divide(Constant.ONE_HUNDRED, 2, RoundingMode.HALF_UP));
        }
        List<Long> postIds = dto.getKpiGroups().stream().map(KpiGroupDTO::getPostId).distinct().collect(Collectors.toList());
        List<Long> shopIds = dto.getKpiGroups().stream().flatMap(kpiGroup -> kpiGroup.getShopIds().stream()).distinct().collect(Collectors.toList());
        kpiGroupRank.setPostIds(postIds);
        kpiGroupRank.setShopIds(shopIds);
        return kpiGroupRank;
    }

    /**
     * 审批kpiGroup
     * 生效时间 在 当前时间 之前,那么这个审批是无效的
     * 次月生效
     * 1. 将次月生效的重复绩效配置设置为失效,等待月定时器执行
     * 当月生效
     * 1. 将当月生效的重复绩效配置设置为失效,将之前配置设置为无效,将状态设置为生效中
     * @param approvalRecord
     * @param result
     */
    @Transactional(rollbackFor = Exception.class)
    public void approvalKpiGroup(ApprovalRecord approvalRecord, ApprovalResultEvent result) {
        log.info("收到绩效组配置变更审批信息:{}", JSON.toJSONString(approvalRecord));
        KpiGroup kpiGroup = kpiGroupService.getById(approvalRecord.getDataId());
        if (! result.getAgree()) {
            kpiGroupService.update(Wrappers.<KpiGroup>lambdaUpdate()
                    .set(KpiGroup::getStatus, SettingStatusEnum.INEFFECTIVE)
                    .set(KpiGroup::getYn, Boolean.FALSE)
                    .eq(KpiGroup::getId, kpiGroup.getId())
            );
            return;
        }

        //通知绩效组人员
        KpiGroupChangeEvent kpiGroupChangeEvent = PublicUtil.copy(kpiGroup, KpiGroupChangeEvent.class);
        EventBusUtil.asyncPost(kpiGroupChangeEvent);

        YearMonth yearMonth = YearMonth.now();
        YearMonth beginTime = YearMonth.from(kpiGroup.getBeginTime());
        kpiGroup.getBeginTime();
        if (yearMonth.isAfter(beginTime)) {
            log.info("审批通过时间在绩效组生效时间之后,等待定时器执行");
            return;
        }

        //处理重复绩效组配置数据
        this.processRepeatKpiGroup(kpiGroup);
    }

    /**
     * 处理重复数据
     * 1. 次月之后生效,需要处理次月后重复的待生效数据
     * 2. 当月生效,   需要处理当月后重复的待生效数据,处理当前重复的生效数据
     * @param kpiGroup
     */
    public void processRepeatKpiGroup(KpiGroup kpiGroup){
        log.info("原kgc: {}",kpiGroup.getKgc());
        YearMonth yearMonth = YearMonth.now();
        YearMonth beginTime = YearMonth.from(kpiGroup.getBeginTime());
        //删除重复的待生效配置数据(时间在此绩效组配置之后、同岗位、同门店)
        KpiGroupRepeatQueryDTO beEffectRepeatDTO = KpiGroupRepeatQueryDTO.convertToBeEffectiveDTO(kpiGroup);
        List<KpiGroup> beKpiGroups = kpiGroupService.queryRepeatKpiGroup(beEffectRepeatDTO);
        kpiGroupDataService.delInEffective(beKpiGroups);

        SettingStatusEnum status = SettingStatusEnum.BE_EFFECTIVE;
        //当月生效,处理当前重复的生效数据
        if (yearMonth.equals(beginTime)) {
            status = SettingStatusEnum.EFFECTIVE;
            KpiGroupRepeatQueryDTO effectRepeatDTO = KpiGroupRepeatQueryDTO.convertToEffectiveDTO(kpiGroup);
            List<KpiGroup> effectKpiGroups = kpiGroupService.queryRepeatKpiGroup(effectRepeatDTO);
            kpiGroupDataService.modifyStatusByKpis(effectKpiGroups, SettingStatusEnum.INEFFECTIVE);
            log.info("effectKpiGroups : {}",JSON.toJSONString(effectKpiGroups));
            if (CollectionUtils.isEmpty(effectKpiGroups)){
                //如果没有查询到,说明岗位和门店匹配不上,该条审批是一条新的kgc,查询到了会把数据置为失效,改条审批进行覆盖原数据,共用一个kgc
                kpiGroup.setKgc(PublicUtil.getUUID());
            }
        }

        log.info("最终kgc: {}",kpiGroup.getKgc());
        kpiGroupDataService.modifyStatusById(kpiGroup, status);
    }

    /**
     * 所有集团生效的绩效组配置
     */
    public Map<Long, List<KpiGroup>> postEffectKpis(){
        Date queryDate = DateUtil.localDateTime2Date(LocalDateTime.now().minusDays(1L));
        List<KpiGroup> kpiGroups = kpiGroupService.getAllEffectGroups(queryDate);
        if (PublicUtil.isEmpty(kpiGroups)) {
            log.info("时间:{},没有正在生效中的绩效组配置", new SimpleDateFormat("yyyy-MM-dd").format(queryDate));
            return Maps.newHashMap();
        }
        return kpiGroups.stream().collect(Collectors.groupingBy(KpiGroup::getPostId));
    }

    /**
     * 删除绩效组
     *
     * @param id
     */
    public void delKpiGroup(Long id, LoginAuthBean currentUser) {
        KpiGroup kpiGroup = kpiGroupService.getById(id);
        BV.notNull(kpiGroup, "绩效配置不存在,请重试");
        BV.isTrue(SettingStatusEnum.DRAFT.equals(kpiGroup.getStatus()), "绩效配置不是草稿状态,不能删除");

        kpiGroup.setUpdateTime(new Date());
        kpiGroup.setUpdateBy(currentUser.getUserId());
        kpiGroup.setYn(Boolean.FALSE);
        kpiGroupService.updateById(kpiGroup);

        //删除草稿
        SettingDraft settingDraft = settingDraftService.getOne(Wrappers.<SettingDraft>lambdaQuery()
                        .eq(SettingDraft::getUnionId, id)
                        .eq(SettingDraft::getYn, Boolean.TRUE)
                , Boolean.FALSE);
        if (PublicUtil.isEmpty(settingDraft)) {
            return;
        }
        settingDraft.setUpdateTime(new Date());
        settingDraft.setYn(Boolean.FALSE);
        settingDraftService.updateById(settingDraft);
    }

    /**
     * 保存考评草稿
     * @param dto
     */
    public void saveKpiDraft(KpiGroupDTO dto, LoginAuthBean currentUser) {
        KpiGroup kpiGroup = null;
        SettingDraft settingDraft = null;
        if (PublicUtil.isNotEmpty(dto.getId())) {
            kpiGroup = kpiGroupService.getById(dto.getId());
            BV.isTrue(PublicUtil.isNotEmpty(kpiGroup), "考评数据不存在");
            kpiGroup = PublicUtil.copy(dto, KpiGroup.class);


            settingDraft = settingDraftService.getOne(Wrappers.<SettingDraft>lambdaQuery()
                            .eq(SettingDraft::getUnionId, dto.getId())
                            .eq(SettingDraft::getYn, Boolean.TRUE)
                    , Boolean.FALSE);
            BV.isTrue(PublicUtil.isNotEmpty(settingDraft), "考评草稿数据不存在");
        } else {
            kpiGroup = PublicUtil.copy(dto, KpiGroup.class);

            settingDraft = new SettingDraft();
            settingDraft.setGroupId(currentUser.getGroupId());
            settingDraft.setUnionId(-1L);
            settingDraft.setUnionId(kpiGroup.getId());
            settingDraft.setType(SettingDraftTypeEnum.EVAL);
        }
        kpiGroup.setStatus(SettingStatusEnum.DRAFT);
        kpiGroupService.saveOrUpdate(kpiGroup);

        settingDraft.setContent(JSON.toJSONString(dto));
        settingDraftService.saveOrUpdate(settingDraft);
    }

    /**
     * 禁用绩效组
     * @param id
     */
    public void disableGroup(Long id, LoginAuthBean currentUser) {
        KpiGroup kpiGroup = kpiGroupService.getById(id);
        BV.notNull(kpiGroup, "绩效配置不存在,请重试");

        Boolean statusCheck = SettingStatusEnum.BE_EFFECTIVE.equals(kpiGroup.getStatus()) ||
                SettingStatusEnum.EFFECTIVE.equals(kpiGroup.getStatus());
        BV.isTrue(statusCheck, "只有生效中、待生效绩效组能禁用");

        log.info("禁用绩效组,id:{},操作人:{}", id, currentUser);

        kpiGroupService.update(Wrappers.<KpiGroup>lambdaUpdate()
                .set(KpiGroup::getUpdateTime, new Date())
                .set(KpiGroup::getYn, Boolean.FALSE)
                .eq(KpiGroup::getId, kpiGroup.getId())
        );

        if (SettingStatusEnum.EFFECTIVE.equals(kpiGroup.getStatus())) {
            kpiPoolService.update(Wrappers.<KpiPool>lambdaUpdate()
                    .set(KpiPool::getYn, Boolean.FALSE)
                    .set(KpiPool::getUpdateTime, new Date())
                    .eq(KpiPool::getKpiGroupId, kpiGroup.getId())
                    .eq(KpiPool::getYn, Boolean.TRUE)
                    .eq(KpiPool::getMonthly, YearMonth.now())
            );
        }
    }

    public List<KpiGroupVO> reportGroupConfig(KpiGroupRankConfigQueryDTO dto) {
        List<KpiGroupVO> res = new ArrayList<>();
        for (Long kpiGroupId : dto.getKpiGroupIds()) {
            KpiGroupVO kpiGroupVO = kpiGroupDetail(kpiGroupId);
            res.add(kpiGroupVO);
        }
        return res;
    }
}