package com.hzs.bonus.bonus.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.hzs.bonus.achieve.service.ICuMemberRangeService;
import com.hzs.bonus.achieve.service.ICuMemberRetailRangeService;
import com.hzs.bonus.base.service.ICuMemberService;
import com.hzs.bonus.bonus.vo.BonusRecordDetailVO;
import com.hzs.bonus.detail.service.ICuMemberAwardsService;
import com.hzs.bonus.detail.service.ICuMemberGradeService;
import com.hzs.bonus.order.service.IBonusOrderService;
import com.hzs.common.core.constant.MagicNumberConstants;
import com.hzs.common.core.constant.RetailConstants;
import com.hzs.common.core.constant.TableNameConstants;
import com.hzs.common.core.constant.msg.BonusMsgConstants;
import com.hzs.common.core.enums.*;
import com.hzs.common.core.utils.ComputeUtil;
import com.hzs.common.core.utils.DateUtils;
import com.hzs.common.domain.bonus.BdBonusDeduct;
import com.hzs.common.domain.member.achieve.ext.CuMemberRangeExt;
import com.hzs.common.domain.member.achieve.ext.CuMemberRetailRangeExt;
import com.hzs.common.domain.member.bonus.*;
import com.hzs.common.domain.member.detail.CuMemberAwards;
import com.hzs.common.domain.member.detail.CuMemberGrade;
import com.hzs.common.domain.member.detail.CuMemberLevel;
import com.hzs.common.domain.member.detail.CuMemberServiceLog;
import com.hzs.common.domain.member.ext.BdWaresBonusExt;
import com.hzs.common.domain.sale.ext.SaOrderExt;
import com.hzs.common.domain.sale.ext.SaOrderItemsExt;
import com.hzs.common.domain.sale.ext.SaOrderWaresExt;
import com.hzs.common.domain.sale.order.SaOrder;
import com.hzs.common.domain.system.config.BdAwards;
import com.hzs.common.domain.system.config.BdGrade;
import com.hzs.common.domain.system.config.BdRangeAwards;
import com.hzs.member.detail.ICuMemberServiceLogServiceApi;
import com.hzs.system.config.dto.BonusConfigDTO;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 计算乐享极差收益
 */
@Component
public class BonusSettleRangeHandle extends BonusSettleHandle {

    @Autowired
    private ICuMemberRangeService iCuMemberRangeService;
    @Autowired
    private ICuMemberRetailRangeService iCuMemberRetailRangeService;
    @Autowired
    private ICuMemberAwardsService iCuMemberAwardsService;
    @Autowired
    private ICuMemberGradeService iCuMemberGradeService;
    @Autowired
    private ICuMemberService iCuMemberService;
    @Autowired
    private IBonusOrderService iBonusOrderService;

    @DubboReference
    ICuMemberServiceLogServiceApi iCuMemberServiceLogServiceApi;

    /**
     * 秒结：
     * 实时计算秒结数据（业绩、盒数、等级、奖衔、日奖）
     */
    List<CuMemberBonusRange> calculateCuMemberRetailRangeBonusBySecond(String settleDate, SaOrderExt saOrderExt, BonusConfigDTO bonusConfigDTO,
                                                                       String secondRangeTableName, int beforePeriod, int currentPeriod,
                                                                       Map<Long, CuMemberBonus> cuMemberBonusMap, List<CuMemberBonusDetail> cuMemberBonusDetailList) {
        // 会员级差表
        String rangeTableName = TableNameConstants.CU_MEMBER_RETAIL_RANGE + beforePeriod;
        // 更新极差秒接表，用昨天的结算表（血缘伞上）
        iCuMemberRetailRangeService.mergeMemberSecondRetailRangeByRange(rangeTableName, secondRangeTableName, saOrderExt.getPkMember());
        // 处理会员等级（查询会员最新手动升级记录，更新秒结表会员等级小于手动升级的会员等级）
        // TODO new 秒结只影响上面，更新等级应该只更新血缘上就可以，不需要全网更新 -- 是否需要修改？？？
        iCuMemberGradeService.updateCuMemberGradeSecond(secondRangeTableName, currentPeriod);

        // 按照血缘，查询该会员血缘伞上（昨天日结表累计值 + 今天秒结表新増值）
        List<CuMemberRetailRangeExt> memberRetailRangeExtList = iCuMemberRetailRangeService.queryCuMemberSecondRangeParent(rangeTableName, secondRangeTableName, saOrderExt.getPkMember());

        // 会员结算map（key：会员ID，value：结算扩展）
        Map<Long, CuMemberRetailRangeExt> memberRangeExtMap = new HashMap<>();

        // 团队升级等级map（key:等级值，value:等级对象）
        Map<Integer, BdGrade> retailTeamGradeMap = new TreeMap<>();
        // 等级map（key:等级值，value:等级对象）
        Map<Integer, BdGrade> gradeMap = new HashMap<>();
        // 等级列表
        List<BdGrade> retaiGradeList = bonusConfigDTO.getRetaiGradeList();
        for (BdGrade bdGrade : retaiGradeList) {
            if (bdGrade.getBoxTotal() > 0) {
                retailTeamGradeMap.put(bdGrade.getGradeValue(), bdGrade);
            }
            gradeMap.put(bdGrade.getGradeValue(), bdGrade);
        }

        // 奖衔map（key:奖衔值，value：奖衔对象）
        Map<Integer, BdAwards> retailAwardsMap = new HashMap<>();
        List<BdAwards> awardsList = bonusConfigDTO.getAwardsList();
        awardsList.forEach(bdAwards -> retailAwardsMap.put(bdAwards.getAwardsValue(), bdAwards));

        for (CuMemberRetailRangeExt cuMemberRetailRangeExt : memberRetailRangeExtList) {
            if (!memberRangeExtMap.containsKey(cuMemberRetailRangeExt.getPkMember())) {
                memberRangeExtMap.put(cuMemberRetailRangeExt.getPkMember(), cuMemberRetailRangeExt);
            }
        }

        // 当期的手动激活的记录列表
        Map<Long, Date> activateMap = this.getActivateMap(saOrderExt.getPayTime());

        // 计算自消费奖衔
        CuMemberRetailRangeExt sourceMemberRangeExt = memberRangeExtMap.get(saOrderExt.getPkMember());
        // 先算等级 注册、升级计算等级
        // 订单指定产品盒数
        int boxNum = 0;
        for (SaOrderWaresExt saOrderItems : saOrderExt.getOrderWaresExtList()) {
            if (RetailConstants.ALL_BOX_WARES_LIST.contains(saOrderItems.getWaresCode())) {
                boxNum += saOrderItems.getWaresQuantity();
                break;
            }
        }
        saOrderExt.setBoxNum(boxNum);

        // 订单业绩
        BigDecimal orderAchieve = saOrderExt.getOrderAchieve();
        // 注册、升级、复购、重消，盒数、业绩算个人累计数据（盒数、业绩）
        sourceMemberRangeExt.setNewBoxNum(sourceMemberRangeExt.getNewBoxNum() + boxNum);
        sourceMemberRangeExt.setConsumeBoxNum(sourceMemberRangeExt.getConsumeBoxNum() + boxNum);
        sourceMemberRangeExt.setNewConsumePv(ComputeUtil.computeAdd(sourceMemberRangeExt.getNewConsumePv(), orderAchieve));
        sourceMemberRangeExt.setConsumePv(ComputeUtil.computeAdd(sourceMemberRangeExt.getConsumePv(), orderAchieve));
        sourceMemberRangeExt.setMonthConsumePv(ComputeUtil.computeAdd(sourceMemberRangeExt.getMonthConsumePv(), orderAchieve));

        // 会员等级升级记录
        List<CuMemberGrade> cuMemberGradeList = new ArrayList<>();
        // 会员奖衔升级记录
        List<CuMemberAwards> cuMemberAwardsList = new ArrayList<>();
        // 计算自己等级、奖衔等
        calculateGradeAwards(currentPeriod, memberRangeExtMap, rangeTableName, saOrderExt, retailTeamGradeMap, retailAwardsMap, secondRangeTableName,
                cuMemberGradeList, cuMemberAwardsList, sourceMemberRangeExt, activateMap);
        // 计算团队业绩、盒数，计算等级、奖衔
        cuMemberAwardsList.addAll(calculateRetailRangeGradeAwards(currentPeriod, memberRangeExtMap, rangeTableName, saOrderExt, retailTeamGradeMap, retailAwardsMap,
                secondRangeTableName, boxNum, cuMemberGradeList, activateMap));

        // 奖金处理
        List<CuMemberBonusRange> cuMemberBonusRangeList = new ArrayList<>();
        if (EOrderType.RETAIL_REGISTER.getValue() == saOrderExt.getOrderType()
                || EOrderType.RETAIL_UPGRADE.getValue() == saOrderExt.getOrderType()
        ) {
            // 注册、升级订单，计算奖金： 直推级差收益 + 平级收益
            for (SaOrderWaresExt saOrderItems : saOrderExt.getOrderWaresExtList()) {
                if (RetailConstants.ALL_BOX_WARES_LIST.contains(saOrderItems.getWaresCode())) {
                    // 指定盒数商品
                    // 计算直推级差收益 + 平级收益
                    cuMemberBonusRangeList.addAll(calculateRetailRangeBonus(memberRangeExtMap, cuMemberBonusMap, gradeMap, bonusConfigDTO, currentPeriod, saOrderItems, saOrderExt));
                }
            }
        }

        // 查询区域配置
        Map<String, CuMemberRetailRangeExt> countyRangeExtMap = new HashMap<>();
        List<CuMemberRetailRangeExt> countyRangeExtList = iCuMemberRetailRangeService.batchQueryMemberRetailSecondRangeByCounty(rangeTableName, secondRangeTableName, saOrderExt.getRecCounty());
        countyRangeExtList.forEach(cuMemberRetailRangeExt ->
                countyRangeExtMap.put(cuMemberRetailRangeExt.getSystemType() + "_" + cuMemberRetailRangeExt.getRegionAddress(), cuMemberRetailRangeExt));
        // 计算区域奖
        CuMemberBonusDetail cuMemberBonusDetail = calculateRetailAreaBonus(countyRangeExtMap, bonusConfigDTO, currentPeriod, memberRangeExtMap, cuMemberBonusMap, saOrderExt);
        if (cuMemberBonusDetail != null) {
            cuMemberBonusDetailList.add(cuMemberBonusDetail);
        }

        // 回退会员等级
        iCuMemberGradeService.updateCuMemberGrade(secondRangeTableName, saOrderExt.getPkId());
        if (cuMemberGradeList.size() > 0) {
            // 插入会员等级升级记录
            iCuMemberGradeService.insertCuMemberGrade(cuMemberGradeList);
            // 更新会员表会员等级
            iCuMemberService.updateCuMemberGradeByList(cuMemberGradeList, currentPeriod);
        }
        if (cuMemberAwardsList.size() > 0) {
            // 插入会员奖衔升级记录
            iCuMemberAwardsService.saveBatchCuMemberAwards(cuMemberAwardsList);
            // 更新会员奖衔 -- 荣誉级别（旧级差奖衔、旧荣誉奖衔（分红奖衔）
            iCuMemberService.updateCuMemberRetailRangeByList(cuMemberAwardsList, currentPeriod);
        }

        // 更新秒表结会员数据
        if (memberRetailRangeExtList.size() > 0) {
            iCuMemberRetailRangeService.updateCuMemberSecondRange(secondRangeTableName, memberRangeExtMap);
        }
        return cuMemberBonusRangeList;
    }

    /**
     * 实时计算撤单数据（业绩、盒数、等级、奖衔、日奖）
     */
    void calculateCuMemberBackRetailIncome(SaOrderExt saOrderExt, BonusConfigDTO bonusConfigDTO,
                                           String secondRangeTableName, int beforePeriod, int currentPeriod) {
        // 当天的撤单
        List<CuMemberRetailRangeExt> memberRetailRangeExtList;
        String rangeTableName = TableNameConstants.CU_MEMBER_RETAIL_RANGE + beforePeriod;

        if (DateUtils.isSameDay(saOrderExt.getPayTime(), DateUtils.currentDate())) {
            // 当天撤单
            // 实时网体查询血缘伞上会员，更新秒结表等级、奖衔
            iCuMemberRetailRangeService.mergeMemberRetailGradeByMember(secondRangeTableName, saOrderExt.getPkMember());
            // 恢复秒结表奖衔
            iCuMemberAwardsService.mergeCuMemberBackAwards(secondRangeTableName, saOrderExt.getPkMember(), currentPeriod);
            // 查询 昨天日结 + 今天秒结 血缘伞上+直推
            memberRetailRangeExtList = iCuMemberRetailRangeService.queryCuMemberSecondRangeParent(rangeTableName, secondRangeTableName, saOrderExt.getPkMember());
        } else {
            // 非当天撤单
            rangeTableName = TableNameConstants.CU_MEMBER_RETAIL_RANGE + currentPeriod;
            List<SaOrderExt> retailOrderList = new ArrayList<>();
            retailOrderList.add(saOrderExt);
            // 实时网体查询血缘上会员，更新订单支付日结表等级、奖衔
            iCuMemberRetailRangeService.mergeMemberRetailGradeByMember(rangeTableName, saOrderExt.getPkMember());
            // 恢复日结表奖衔
            iCuMemberAwardsService.mergeCuMemberBackAwards(rangeTableName, saOrderExt.getPkMember(), beforePeriod);
            // 查询 订单下单日结 血缘上会员结算数据
            memberRetailRangeExtList = iCuMemberRetailRangeService.queryCuMemberRetailRangeParent(rangeTableName, retailOrderList);
        }

        // 会员结算map（key：会员ID，value：结算扩展）
        Map<Long, CuMemberRetailRangeExt> memberRangeExtMap = new HashMap<>();

        // 团队升级等级map（key:等级值，value:等级对象）
        Map<Integer, BdGrade> retailTeamGradeMap = new TreeMap<>();
        // 等级map（key:等级ID，value:等级对象）
        Map<Integer, BdGrade> gradeIdMap = new HashMap<>();
        // 等级列表
        List<BdGrade> retaiGradeList = bonusConfigDTO.getRetaiGradeList();
        // 等级
        for (BdGrade bdGrade : retaiGradeList) {
            if (bdGrade.getBoxTotal() > 0) {
                retailTeamGradeMap.put(bdGrade.getGradeValue(), bdGrade);
            }
            gradeIdMap.put(bdGrade.getPkId(), bdGrade);
        }

        // 奖衔map（key:奖衔值，value：奖衔对象）
        Map<Integer, BdAwards> retailAwardsMap = new HashMap<>();
        List<BdAwards> awardsList = bonusConfigDTO.getAwardsList();
        awardsList.forEach(bdAwards -> retailAwardsMap.put(bdAwards.getAwardsValue(), bdAwards));

        for (CuMemberRetailRangeExt cuMemberRetailRangeExt : memberRetailRangeExtList) {
            if (!memberRangeExtMap.containsKey(cuMemberRetailRangeExt.getPkMember())) {
                memberRangeExtMap.put(cuMemberRetailRangeExt.getPkMember(), cuMemberRetailRangeExt);
            }
        }

        // 计算自消费奖衔
        CuMemberRetailRangeExt sourceMemberRangeExt = memberRangeExtMap.get(saOrderExt.getPkMember());
        // 先算等级 注册、升级计算等级
        int boxNum = 0;
        for (SaOrderWaresExt saOrderItems : saOrderExt.getOrderWaresExtList()) {
            if (RetailConstants.ALL_BOX_WARES_LIST.contains(saOrderItems.getWaresCode())) {
                boxNum += saOrderItems.getWaresQuantity();
                break;
            }
        }
        saOrderExt.setBoxNum(boxNum);

        // 订单业绩
        BigDecimal orderAchieve = saOrderExt.getOrderAchieve();
        // 复购、重消，盒数、业绩算个人累计数据（盒数、业绩）
        sourceMemberRangeExt.setConsumeBoxNum(sourceMemberRangeExt.getConsumeBoxNum() - boxNum);
        sourceMemberRangeExt.setNewBoxNum(sourceMemberRangeExt.getNewBoxNum() - boxNum);
        sourceMemberRangeExt.setConsumePv(ComputeUtil.computeSubtract(sourceMemberRangeExt.getConsumePv(), orderAchieve));
        sourceMemberRangeExt.setMonthConsumePv(ComputeUtil.computeSubtract(sourceMemberRangeExt.getMonthConsumePv(), orderAchieve));
        sourceMemberRangeExt.setNewConsumePv(ComputeUtil.computeSubtract(sourceMemberRangeExt.getNewConsumePv(), orderAchieve));

        // 会员等级map
        Map<String, CuMemberGrade> cuMemberGradeMap = new HashMap<>();
        // 会员奖衔map
        Map<String, CuMemberAwards> cuMemberAwardsMap = new HashMap<>();
        // 计算自己等级、奖衔等
        calculateBackGrade(currentPeriod, memberRangeExtMap, rangeTableName, saOrderExt, retailTeamGradeMap, retailAwardsMap, secondRangeTableName, cuMemberGradeMap, cuMemberAwardsMap, sourceMemberRangeExt);
        // 计算团队业绩、盒数，计算等级、奖衔
        List<CuMemberRetailRangeExt> cuMemberRetailRangeExtList = calculateRetailBackRangeGradeAwards(currentPeriod, memberRangeExtMap, rangeTableName, saOrderExt, retailTeamGradeMap, retailAwardsMap, secondRangeTableName, boxNum, cuMemberGradeMap, cuMemberAwardsMap);
        cuMemberRetailRangeExtList.add(sourceMemberRangeExt);


        // 查询期间的等级和奖衔
        List<CuMemberGrade> memberGradeList = iCuMemberGradeService.queryCuMemberGrade(cuMemberRetailRangeExtList, currentPeriod);
        // 查询最大的手动奖衔
        List<CuMemberGrade> cuMemberGradeList1 = iCuMemberGradeService.queryCuMemberGradeByList(currentPeriod, memberRetailRangeExtList);
        if (cuMemberGradeList1.size() > 0) {
            Map<Long, CuMemberGrade> memberGradeMap = new HashMap<>();
            for (CuMemberGrade cuMemberGrade : cuMemberGradeList1) {
                cuMemberGradeMap.put(cuMemberGrade.getPkMember() + "_" + cuMemberGrade.getNewLevel(), cuMemberGrade);
                memberGradeMap.put(cuMemberGrade.getPkMember(), cuMemberGrade);
            }
            for (CuMemberRetailRangeExt cuMemberRetailRangeExt : memberRetailRangeExtList) {
                if (memberGradeMap.containsKey(cuMemberRetailRangeExt.getPkMember())) {
                    CuMemberGrade cuMemberGrade = memberGradeMap.get(cuMemberRetailRangeExt.getPkMember());
                    if (cuMemberRetailRangeExt.getPkGrade() < cuMemberGrade.getNewLevel()) {
                        cuMemberRetailRangeExt.setPkGrade(cuMemberGrade.getNewLevel());
                        BdGrade bdGrade = gradeIdMap.get(cuMemberGrade.getNewLevel());
                        cuMemberRetailRangeExt.setGradeValue(bdGrade.getGradeValue());
                    }
                    BdGrade bdGrade = gradeIdMap.get(cuMemberRetailRangeExt.getPkGrade());
                    if (bdGrade != null && bdGrade.getGradeValue() == EGrade.S_VIP.getValue() && cuMemberRetailRangeExt.getPkAwards() < 13) {
                        cuMemberRetailRangeExt.setPkAwards(13);
                    }
                }
            }
        }
        if (memberGradeList.size() > 0) {
            List<CuMemberGrade> cuMemberGradeList = new ArrayList<>();
            for (CuMemberGrade cuMemberGrade : memberGradeList) {
                String key = cuMemberGrade.getPkMember() + "_" + cuMemberGrade.getNewLevel();
                if (!cuMemberGradeMap.containsKey(key)) {
                    CuMemberRetailRangeExt cuMemberRetailRangeExt = memberRangeExtMap.get(cuMemberGrade.getPkMember());
                    if (cuMemberGrade.getOldLevel() < cuMemberRetailRangeExt.getPkGrade()) {
                        cuMemberRetailRangeExt.setPkGrade(cuMemberGrade.getOldLevel());
                    }
                    cuMemberGrade.setNewLevel(cuMemberGrade.getOldLevel());
                    cuMemberGradeList.add(cuMemberGrade);
                }
            }
            if (cuMemberGradeList.size() > 0) {
                iCuMemberGradeService.deleteCuMemberGrade(cuMemberGradeList, currentPeriod);
                iCuMemberService.updateCuMemberMinGradeByList(cuMemberGradeList, currentPeriod);
            }
        }
        List<CuMemberAwards> memberAwardsList = iCuMemberAwardsService.queryCuMemberAwards(cuMemberRetailRangeExtList, currentPeriod);
        if (memberAwardsList.size() > 0) {
            List<CuMemberAwards> cuMemberAwardsList = new ArrayList<>();
            for (CuMemberAwards cuMemberAwards : memberAwardsList) {
                String key = cuMemberAwards.getPkMember() + "_" + cuMemberAwards.getNewLevel();
                if (!cuMemberAwardsMap.containsKey(key)) {
                    CuMemberRetailRangeExt cuMemberRetailRangeExt = memberRangeExtMap.get(cuMemberAwards.getPkMember());
                    if (cuMemberAwards.getOldLevel() < cuMemberRetailRangeExt.getPkAwards()) {
                        cuMemberRetailRangeExt.setPkAwards(cuMemberAwards.getOldLevel());
                    }
                    if (cuMemberRetailRangeExt.getGradeValue() == EGrade.S_VIP.getValue() && cuMemberRetailRangeExt.getPkAwards() < 13) {
                        cuMemberRetailRangeExt.setPkAwards(13);
                        continue;
                    }
                    cuMemberAwards.setNewLevel(cuMemberAwards.getOldLevel());
                    cuMemberAwardsList.add(cuMemberAwards);
                }
            }
            // 处理等级、奖衔
            if (cuMemberAwardsList.size() > 0) {
                iCuMemberAwardsService.deleteCuMemberAwards(cuMemberAwardsList, currentPeriod);
                // 更新会员表,更新奖衔
                iCuMemberService.updateCuMemberMinAwardsByList(cuMemberAwardsList, currentPeriod);
            }
        }
        // 处理业绩
        if (memberRangeExtMap.size() > 0) {
            if (DateUtils.isSameDay(saOrderExt.getPayTime(), DateUtils.currentDate())) {
                iCuMemberRetailRangeService.updateCuMemberSecondRange(secondRangeTableName, memberRangeExtMap);
            } else {
                iCuMemberRetailRangeService.updateCuMemberRetailRange(rangeTableName, memberRangeExtMap);
            }
        }
    }

    private CuMemberGrade getCuMemberGrade(int currentPeriod, CuMemberRetailRangeExt sourceMemberRangeExt, BdGrade bdGrade) {
        CuMemberGrade cuMemberGrade = CuMemberGrade.builder()
                .pkMember(sourceMemberRangeExt.getPkMember())
                .period(currentPeriod)
                .oldLevel(sourceMemberRangeExt.getPkGrade())
                .newLevel(bdGrade.getPkId())
                .upType(EUpgradeType.AUTO_UPGRADE.getValue())
                .build();
        cuMemberGrade.setPkCreator(MagicNumberConstants.PK_ADMIN);
        cuMemberGrade.setPkCountry(sourceMemberRangeExt.getPkSettleCountry());
        return cuMemberGrade;
    }

    /**
     * 日结：
     * 计算新零售团队的奖金，极差、平级、福利、福利分红、区域
     */
    void calculateRetailBonusByDay(String settleDate, Map<Long, CuMemberBonus> cuMemberBonusMap, BonusConfigDTO bonusConfigDTO, BonusRecordDetailVO bonusRecordDetailVO,
                                   Integer period, Integer yesterdayPeriod, Boolean isSameMonth) {
        // 结算期间日期
        Date settleStartDate = DateUtils.parseStringToDate(settleDate);
        // 结算期间日期后一天
        Date settleEndDate = DateUtils.afterDate(1, ChronoUnit.DAYS, settleStartDate);

        List<SaOrderExt> retailOrderList = new ArrayList<>();
        // 新零售订单
        List<SaOrderExt> orderList = iBonusOrderService.queryRetailSaOrderByDay(settleStartDate, settleEndDate, null);
        for (SaOrderExt saOrderExt : orderList) {
            if (saOrderExt.getDelFlag() == EYesNo.YES.getIntValue()) {
                retailOrderList.add(saOrderExt);
            }
        }

        // 更新当月会员， 将昨天业绩更到到今天，更新当月会员考核结果，有消费的考核通过
        // 结算期间表
        String rangeTableName = TableNameConstants.CU_MEMBER_RETAIL_RANGE + period;
        // 结算期间前一天表
        String yesterdayRangeTableName = TableNameConstants.CU_MEMBER_RETAIL_RANGE + yesterdayPeriod;

        // 回退奖衔，将奖衔回退到结算前状态
        iCuMemberAwardsService.calculateCuMemberRetailRangeAwardsInit(settleDate, period, rangeTableName);
        // 更新网体
        iCuMemberRetailRangeService.mergeMemberRetailRangeByYesterday(settleEndDate, rangeTableName, yesterdayRangeTableName, isSameMonth);

        // 回退历史注水
        iCuMemberRetailRangeService.mergeCuMemberRetailBackBoxBySpecial(rangeTableName, yesterdayRangeTableName, period);
        // 更新注水
        iCuMemberRetailRangeService.mergeCuMemberRetailRangeBySpecial(rangeTableName, period);

        // 当期的手动激活的记录列表
        Map<Long, Date> activateMap = this.getActivateMap(settleStartDate);

        if (retailOrderList.size() > 0) {
            Map<Long, CuMemberLevel> memberLevelMap = new HashMap<>();
            List<CuMemberLevel> memberLevelList = iCuMemberGradeService.calculateCuMemberRetailGradeInit(period, settleStartDate, settleEndDate, rangeTableName);
            memberLevelList.forEach(cuMemberLevel -> memberLevelMap.put(cuMemberLevel.getPkOrder(), cuMemberLevel));

            // 按照血缘，查询该会员所有伞上会员
            List<CuMemberRetailRangeExt> memberRetailRangeExtList = iCuMemberRetailRangeService.queryCuMemberRetailRangeParent(rangeTableName, retailOrderList);

            // 会员结算map（key：会员ID，value：结算扩展）
            Map<Long, CuMemberRetailRangeExt> memberRangeExtMap = new HashMap<>();
            // 团队升级等级map（key:等级值，value:等级对象）
            Map<Integer, BdGrade> retailTeamGradeMap = new TreeMap<>();
            // 等级map（key:等级值，value:等级对象）
            Map<Integer, BdGrade> gradeMap = new HashMap<>();
            // 等级map（key:等级ID，value:等级对象）
            Map<Integer, BdGrade> gradeIdMap = new HashMap<>();
            // 等级列表
            List<BdGrade> retaiGradeList = bonusConfigDTO.getRetaiGradeList();
            for (BdGrade bdGrade : retaiGradeList) {
                if (bdGrade.getBoxTotal() > 0) {
                    retailTeamGradeMap.put(bdGrade.getGradeValue(), bdGrade);
                }
                gradeMap.put(bdGrade.getGradeValue(), bdGrade);
                gradeIdMap.put(bdGrade.getPkId(), bdGrade);
            }

            // 奖衔
            Map<Integer, BdAwards> retailAwardsMap = new HashMap<>();
            List<BdAwards> awardsList = bonusConfigDTO.getAwardsList();
            awardsList.forEach(bdAwards -> retailAwardsMap.put(bdAwards.getAwardsValue(), bdAwards));

            for (CuMemberRetailRangeExt cuMemberRetailRangeExt : memberRetailRangeExtList) {
                if (!memberRangeExtMap.containsKey(cuMemberRetailRangeExt.getPkMember())) {
                    memberRangeExtMap.put(cuMemberRetailRangeExt.getPkMember(), cuMemberRetailRangeExt);
                }
            }

            // 区域处理
            List<CuMemberRetailRangeExt> countyRangeExtList = iCuMemberRetailRangeService.batchQueryMemberRetailRangeByCounty(rangeTableName);
            // 区域会员map（key:系统+区ID ,value: 区域会员结算数据）
            Map<String, CuMemberRetailRangeExt> countyRangeExtMap = new HashMap<>();
            countyRangeExtList.forEach(cuMemberRetailRangeExt ->
                    countyRangeExtMap.put(cuMemberRetailRangeExt.getSystemType() + "_" + cuMemberRetailRangeExt.getRegionAddress(), cuMemberRetailRangeExt));

            // 会员等级升级记录
            List<CuMemberGrade> cuMemberGradeList = new ArrayList<>();
            // 会员奖衔升级记录
            List<CuMemberAwards> cuMemberAwardsList = new ArrayList<>();
            // 平级收益
            List<CuMemberBonusRange> cuMemberBonusRangeList = new ArrayList<>();
            // 会员奖金明细
            List<CuMemberBonusDetail> cuMemberBonusDetailList = new ArrayList<>();

            // 上面更新网体，按会员表是否激活进行处理
            for (SaOrderExt saOrderExt : retailOrderList) {
                CuMemberRetailRangeExt sourceMemberRangeExt = memberRangeExtMap.get(saOrderExt.getPkMember());
                if (EOrderType.RETAIL_REGISTER.getValue() == saOrderExt.getOrderType() ||
                        EOrderType.RETAIL_UPGRADE.getValue() == saOrderExt.getOrderType()) {
                    // 注册、升级才能算激活状态
                    sourceMemberRangeExt.setEnableStatus(EYesNo.YES.getIntValue());
                }
            }

            for (SaOrderExt saOrderExt : retailOrderList) {
                // 计算自消费奖衔
                CuMemberRetailRangeExt sourceMemberRangeExt = memberRangeExtMap.get(saOrderExt.getPkMember());

                // 订单指定产品盒数（计算等级使用）
                int boxNum = 0;
                for (SaOrderWaresExt saOrderItems : saOrderExt.getOrderWaresExtList()) {
                    if (RetailConstants.ALL_BOX_WARES_LIST.contains(saOrderItems.getWaresCode())) {
                        boxNum += saOrderItems.getWaresQuantity();
                        break;
                    }
                }
                // 个人累计消费pv
                BigDecimal orderAchieve = saOrderExt.getOrderAchieve();
                // 复购、重消，盒数、业绩算个人累计数据（盒数、业绩）
                sourceMemberRangeExt.setConsumeBoxNum(sourceMemberRangeExt.getConsumeBoxNum() + boxNum);
                sourceMemberRangeExt.setNewBoxNum(sourceMemberRangeExt.getNewBoxNum() + boxNum);
                sourceMemberRangeExt.setConsumePv(ComputeUtil.computeAdd(sourceMemberRangeExt.getConsumePv(), orderAchieve));
                sourceMemberRangeExt.setMonthConsumePv(ComputeUtil.computeAdd(sourceMemberRangeExt.getMonthConsumePv(), orderAchieve));
                sourceMemberRangeExt.setNewConsumePv(ComputeUtil.computeAdd(sourceMemberRangeExt.getNewConsumePv(), orderAchieve));
                // 计算自己等级、奖衔等
                calculateGradeAwards(period, memberRangeExtMap, rangeTableName, saOrderExt, retailTeamGradeMap, retailAwardsMap,
                        null, cuMemberGradeList, cuMemberAwardsList, sourceMemberRangeExt, activateMap);
                // 计算团队业绩、盒数，计算等级、奖衔
                cuMemberAwardsList.addAll(calculateRetailRangeGradeAwards(period, memberRangeExtMap, rangeTableName, saOrderExt,
                        retailTeamGradeMap, retailAwardsMap, null, boxNum, cuMemberGradeList, activateMap));

                // 计算奖金 直推级差 + 平级收益
                if ((EOrderType.RETAIL_REGISTER.getValue() == saOrderExt.getOrderType()
                        || EOrderType.RETAIL_UPGRADE.getValue() == saOrderExt.getOrderType())
                        && boxNum > 0
                ) {
                    // 注册或升级订单并且存在盒数产品，才有 直推级差收益 和 平级收益
                    for (SaOrderWaresExt saOrderItems : saOrderExt.getOrderWaresExtList()) {
                        // 直推级差 + 平级收益
                        cuMemberBonusRangeList.addAll(calculateRetailRangeBonus(memberRangeExtMap, cuMemberBonusMap, gradeMap, bonusConfigDTO, period, saOrderItems, saOrderExt));

                        // 计算完奖金算等级
                        if (EOrderType.RETAIL_REGISTER.getValue() == saOrderExt.getOrderType()
                                || EOrderType.RETAIL_UPGRADE.getValue() == saOrderExt.getOrderType()) {
                            // 订单存在升级记录
                            if (memberLevelMap.containsKey(saOrderExt.getPkId())) {
                                CuMemberLevel cuMemberLevel = memberLevelMap.get(saOrderExt.getPkId());
                                if (gradeIdMap.containsKey(cuMemberLevel.getNewLevel())) {
                                    BdGrade bdGrade = gradeIdMap.get(cuMemberLevel.getNewLevel());
                                    if (bdGrade.getGradeValue() > sourceMemberRangeExt.getGradeValue()) {
                                        sourceMemberRangeExt.setPkGrade(bdGrade.getPkId());
                                        sourceMemberRangeExt.setGradeValue(bdGrade.getGradeValue());
                                        sourceMemberRangeExt.setGradeName(bdGrade.getGradeName());
                                    }
                                }
                            }
                        }
                    }
                }

                // 计算区域奖
                CuMemberBonusDetail cuMemberBonusDetail = calculateRetailAreaBonus(countyRangeExtMap, bonusConfigDTO, period, memberRangeExtMap, cuMemberBonusMap, saOrderExt);
                if (cuMemberBonusDetail != null) {
                    cuMemberBonusDetailList.add(cuMemberBonusDetail);
                }
            }
            if (cuMemberBonusRangeList.size() > 0) {
                if (bonusRecordDetailVO.getCuMemberBonusRangeList() == null) {
                    bonusRecordDetailVO.setCuMemberBonusRangeList(cuMemberBonusRangeList);
                } else {
                    bonusRecordDetailVO.getCuMemberBonusRangeList().addAll(cuMemberBonusRangeList);
                }
            }
            if (cuMemberBonusDetailList.size() > 0) {
                if (bonusRecordDetailVO.getCuMemberBonusDetailList() == null) {
                    bonusRecordDetailVO.setCuMemberBonusDetailList(cuMemberBonusDetailList);
                } else {
                    bonusRecordDetailVO.getCuMemberBonusDetailList().addAll(cuMemberBonusDetailList);
                }
            }
            if (cuMemberAwardsList.size() > 0) {
                iCuMemberAwardsService.saveBatchCuMemberAwards(cuMemberAwardsList);
                // 更新会员表,更新奖衔
                iCuMemberService.updateCuMemberRetailRangeByPeriod(cuMemberAwardsList, period);
            }
            if (cuMemberGradeList.size() > 0) {
                iCuMemberGradeService.insertCuMemberGrade(cuMemberGradeList);
                iCuMemberService.updateCuMemberGradeByPeriod(cuMemberGradeList, period);
                // 根据cu_member_level更新cu_member
                iCuMemberService.updateCuMemberLevel(settleStartDate, settleEndDate);
            }
            // 更新网体
            iCuMemberRetailRangeService.updateCuMemberRetailRange(rangeTableName, memberRangeExtMap);
        }
    }

    /**
     * 查询会员验证大小区，区域算法2种条件，1 实际满足V5 1种是满足 30w 小区10w
     */
    CuMemberRetail queryValidateBoxOrAchieve(int currentPeriod, int beforePeriod, Long pkMember) {
        CuMemberRetail cuMemberRetail = new CuMemberRetail();
        String rangeTableName = TableNameConstants.CU_MEMBER_RETAIL_RANGE + beforePeriod;
        String secondRangeTableName = TableNameConstants.CU_MEMBER_RETAIL_S + currentPeriod;
        List<CuMemberRetailRangeExt> memberRetailRangeExtList = iCuMemberRetailRangeService.queryCuMemberSecondRange(rangeTableName, secondRangeTableName, pkMember);
        List<CuMemberRetailRangeExt> cuMemberRangeExtList = new ArrayList<>();
        CuMemberRetailRangeExt targetMemberRangeExt = null;
        for (CuMemberRetailRangeExt cuMemberRetailRangeExt : memberRetailRangeExtList) {
            if (cuMemberRetailRangeExt.getPkParent().equals(pkMember)) {
                cuMemberRangeExtList.add(cuMemberRetailRangeExt);
            } else {
                targetMemberRangeExt = cuMemberRetailRangeExt;
            }
        }
        if (targetMemberRangeExt == null) {
            return null;
        }
        // 计算大区盒数、小区盒数
        int bigBoxNum = targetMemberRangeExt.getConsumeBoxNum();
        for (CuMemberRetailRangeExt cuMemberRetailRangeExt : cuMemberRangeExtList) {
            int areaBoxNum = cuMemberRetailRangeExt.getTeamBoxNum() + cuMemberRetailRangeExt.getConsumeBoxNum()
                    - cuMemberRetailRangeExt.getBigBoxNum() - cuMemberRetailRangeExt.getSmallBoxNum();
            if (areaBoxNum > bigBoxNum) {
                bigBoxNum = areaBoxNum;
            }
        }
        // 实际盒数去掉注水
        int realBoxNum = targetMemberRangeExt.getTeamBoxNum() + targetMemberRangeExt.getConsumeBoxNum() -
                targetMemberRangeExt.getBigBoxNum() - targetMemberRangeExt.getSmallBoxNum();
        int smallBoxNum = realBoxNum - bigBoxNum;
        cuMemberRetail.setRealBoxNum(realBoxNum);
        cuMemberRetail.setBigBoxNum(bigBoxNum);
        cuMemberRetail.setSmallBoxNum(smallBoxNum);
        // 计算大小区业绩
        BigDecimal consumeBigPv = targetMemberRangeExt.getMonthConsumePv();
        for (CuMemberRetailRangeExt cuMemberRetailRangeExt : cuMemberRangeExtList) {
            BigDecimal consumePv = ComputeUtil.computeAdd(cuMemberRetailRangeExt.getMonthConsumePv(), cuMemberRetailRangeExt.getTeamMonthPv());
            if (ComputeUtil.compareGreaterThan(consumePv, consumeBigPv)) {
                consumeBigPv = consumePv;
            }
        }
        BigDecimal smallAreaPv = ComputeUtil.computeAdd(targetMemberRangeExt.getMonthConsumePv(), ComputeUtil.computeSubtract(targetMemberRangeExt.getTeamMonthPv(), consumeBigPv));
        cuMemberRetail.setTeamMonthPv(ComputeUtil.computeAdd(targetMemberRangeExt.getMonthConsumePv(), targetMemberRangeExt.getTeamMonthPv()));
        cuMemberRetail.setBigAreaPv(consumeBigPv);
        cuMemberRetail.setSmallAreaPv(smallAreaPv);
        cuMemberRetail.setValidateFlag(Boolean.FALSE);
        if ((cuMemberRetail.getRealBoxNum() >= 2400 && cuMemberRetail.getSmallBoxNum() >= 500) ||
                (ComputeUtil.compareValue(cuMemberRetail.getTeamMonthPv(), BigDecimal.valueOf(46875)) && ComputeUtil.compareValue(cuMemberRetail.getSmallAreaPv(), BigDecimal.valueOf(15625)))) {
            cuMemberRetail.setValidateFlag(Boolean.TRUE);
        }
        return cuMemberRetail;
    }

    void calculateRangeEvBonus(Map<Long, CuMemberBonus> cuMemberBonusMap, BonusConfigDTO bonusConfigDTO, Integer period, Map<Long, CuMemberRangeExt> memberRangeExtMap, List<CuMemberBonusPush> cuMemberBonusPushList, List<BdWaresBonusExt> bdWaresBonusExtList, SaOrderExt saOrderExt) {
        CuMemberRangeExt sourceMemberRangeExt = memberRangeExtMap.get(saOrderExt.getPkMember());
        if (ComputeUtil.compareValue(saOrderExt.getOrderAssAchieve(), BigDecimal.valueOf(15.625))) {
            // 1= 自己购买了11单 2= 上3代拿 100 200 300 上3代各拿100 上11代各拿1100
            int specialWaresState = 0;
            BdWaresBonusExt calWaresBonusExt = null;
            for (SaOrderItemsExt saOrderItemsExt : saOrderExt.getOrderItemsExtList()) {
                boolean flag = Boolean.FALSE;
                if (bdWaresBonusExtList != null && bdWaresBonusExtList.size() > 0) {
                    for (BdWaresBonusExt bdWaresBonusExt : bdWaresBonusExtList) {
                        if (bdWaresBonusExt.getPkWares().equals(saOrderItemsExt.getPkWares())) {
                            specialWaresState = 2;
                            flag = Boolean.TRUE;
                            calWaresBonusExt = bdWaresBonusExt;
                            break;
                        }
                    }
                }
                if (flag) {
                    break;
                }
            }
            if (specialWaresState > 0) {
                if (specialWaresState == 2) {
                    sourceMemberRangeExt.setBuyEffectiveNum(sourceMemberRangeExt.getBuyEffectiveNum() + calWaresBonusExt.getTotalAlgebra());
                    int algebra = 0;
                    for (BdWaresBonusItems bdWaresBonusItems : calWaresBonusExt.getBdWaresBonusItemsList()) {
                        CuMemberBonusPush cuMemberBonusPush = calculatePushBonusOne(sourceMemberRangeExt, memberRangeExtMap, bonusConfigDTO, period, cuMemberBonusMap, saOrderExt,
                                bdWaresBonusItems.getAlgebra() - algebra, bdWaresBonusItems.getAssAchieve(), cuMemberBonusPushList);
                        if (cuMemberBonusPush != null) {
                            sourceMemberRangeExt = memberRangeExtMap.get(cuMemberBonusPush.getPkBonus());
                            algebra = bdWaresBonusItems.getAlgebra();
                        }
                    }
                } else {
                    sourceMemberRangeExt.setBuyEffectiveNum(sourceMemberRangeExt.getBuyEffectiveNum() + 11);
                    sourceMemberRangeExt.setFirstAgent(sourceMemberRangeExt.getFirstAgent() + 1);
                    setPushBonus(cuMemberBonusMap, bonusConfigDTO, period, memberRangeExtMap, saOrderExt, sourceMemberRangeExt, 1, sourceMemberRangeExt.getFirstAgent());
                }
            } else {
                sourceMemberRangeExt.setBuyEffectiveNum(sourceMemberRangeExt.getBuyEffectiveNum() + 1);
//                    if (EYesNo.NO.getIntValue() == sourceMemberRangeExt.getProvideState()) {
//                        sourceMemberRangeExt.setProvideState(EYesNo.YES.getIntValue());
//                        targetMemberRangeExt.setEvEffectiveNum(targetMemberRangeExt.getEvEffectiveNum() + 1);
//                    }
                calculatePushBonusOne(sourceMemberRangeExt, memberRangeExtMap, bonusConfigDTO, period, cuMemberBonusMap, saOrderExt,
                        sourceMemberRangeExt.getBuyEffectiveNum(), saOrderExt.getOrderAssAchieve(), cuMemberBonusPushList);
            }
        }
    }

    private void setPushBonus(Map<Long, CuMemberBonus> cuMemberBonusMap, BonusConfigDTO bonusConfigDTO, Integer period, Map<Long, CuMemberRangeExt> memberRangeExtMap, SaOrderExt saOrderExt, CuMemberRangeExt sourceMemberRangeExt,
                              Integer round, Integer second) {
        // 死点没有奖金,自身没有购买没有奖金
        if (ECategory.NORMAL.getValue() != sourceMemberRangeExt.getCategory() || EAccountStatus.STOP_INCOME.getValue() == sourceMemberRangeExt.getAccountStatus() ||
                sourceMemberRangeExt.getBuyEffectiveNum() <= 0 || EAssessStatus.EXAMINE_PASS.getValue() != sourceMemberRangeExt.getAssessStatus()) {
            return;
        }
        if (validatePkBonusItems(bonusConfigDTO, sourceMemberRangeExt.getPkSettleCountry(), EBonusItems.HELP_EACH_INCOME.getValue())) {
            return;
        }
        CuMemberBonus cuMemberBonus = getCuMemberBonus(period, cuMemberBonusMap, sourceMemberRangeExt.getPkMember(),
                sourceMemberRangeExt.getIncomeStatus(), sourceMemberRangeExt.getPkSettleCountry(), sourceMemberRangeExt.getPkRate());
        // 直推奖金明细
        int pkBonusItem = getPkBonusItems(bonusConfigDTO, sourceMemberRangeExt.getPkSettleCountry(), EBonusItems.HELP_EACH_INCOME.getValue());
        CuMemberBonusPush cuMemberBonusPush = getCuMemberBonusPush(saOrderExt, sourceMemberRangeExt, cuMemberBonus, pkBonusItem);
        cuMemberBonusPush.setCalType(ECalType.VALUE.getValue());
        cuMemberBonusPush.setRound(round);
        cuMemberBonusPush.setSecond(second);
        cuMemberBonusPush.setCalAchieve(saOrderExt.getOrderAssAchieve());
        cuMemberBonusPush.setCalValue(BigDecimal.ONE);
        cuMemberBonusPush.setPretaxIncome(saOrderExt.getOrderAssAchieve());
        BdBonusDeduct bdBonusDeduct = setBonusDetailDeduct(bonusConfigDTO, cuMemberBonusPush, saOrderExt.getOrderAmount(), saOrderExt.getInExchangeRate());
        recommendRangeRemark(saOrderExt, cuMemberBonusPush, memberRangeExtMap, sourceMemberRangeExt);
        if (EBonusIncomeStatus.NORMAL.getValue() == cuMemberBonusPush.getIncomeStatus()) {
            cuMemberBonus.setRepurPushIncome(ComputeUtil.computeAdd(cuMemberBonus.getRepurPushIncome(), cuMemberBonusPush.getPretaxIncome()));
            setCloudTotal(bdBonusDeduct, cuMemberBonus, cuMemberBonusPush);
        }
    }

    private void packageRangeAwardsByType(List<BdRangeAwards> rangeAwardsList, Map<Integer, BdRangeAwards> consumeRangeAwardsMap, Map<Integer, BdRangeAwards> bloodRangeAwardsMap) {
        for (BdRangeAwards bdRangeAwards : rangeAwardsList) {
            if (ComputeUtil.compareValue(bdRangeAwards.getConsumePv())) {
                consumeRangeAwardsMap.put(bdRangeAwards.getAwardsValue(), bdRangeAwards);
            }
            if (ComputeUtil.compareValue(bdRangeAwards.getTeamConsumeCheck())) {
                bloodRangeAwardsMap.put(bdRangeAwards.getAwardsValue(), bdRangeAwards);
            }
        }
    }

    /**
     * 先计算奖衔,奖衔计算分为2种，先计算自己消费足够的，S1-S3，S4以上的另一种方式，自消费的只有购买人，其他的都是根据业绩，注意，有人可以直接是S4
     * 先验证团队业绩，小区业绩，验证小市场需要从上往下走 s1只能通过自消费，除了购买人其他人丛S2开始升级
     * 计算个人消费奖项
     */
    public List<CuMemberAwards> calculateConsumeRangeAwards(Integer period, Map<Long, List<CuMemberRangeExt>> parentRangeExtMap, Map<Long, CuMemberRangeExt> memberRangeExtMap, String rangeTableName,
                                                            CuMemberRangeExt sourceMemberRangeExt, SaOrderExt saOrderExt,
                                                            Map<Integer, BdRangeAwards> consumeRangeAwardsMap) {
        int rangeAwardsValue = 2;
        List<CuMemberAwards> cuMemberAwardsList = new ArrayList<>();
        while (consumeRangeAwardsMap.containsKey(sourceMemberRangeExt.getRangeAwardsValue() + rangeAwardsValue)) {
            // 验证pv是否满足
            BdRangeAwards bdRangeAwards = consumeRangeAwardsMap.get(sourceMemberRangeExt.getRangeAwardsValue() + rangeAwardsValue);
            if (ComputeUtil.compareValue(sourceMemberRangeExt.getTeamConsumePv(), bdRangeAwards.getTeamConsumeCheck()) &&
                    ComputeUtil.compareValue(sourceMemberRangeExt.getConsumePv(), bdRangeAwards.getConsumePv())) {
                // 去结算表种查询该会员下所有会员，会员团队业绩+消费业绩是业绩 计算小区业绩 团队业绩-小区业绩 验证小区、直推必有一种
                // 如果需要验证小区
                if (ComputeUtil.compareValue(bdRangeAwards.getCommunityCheck())) {
                    List<CuMemberRangeExt> cuMemberRangeExtList = iCuMemberRangeService.queryCuMemberRangeExtByParent(rangeTableName, sourceMemberRangeExt.getPkMember(), saOrderExt.getPayTime());
                    // 需要验证团队业绩，小区业绩
                    if (calculateAwards(parentRangeExtMap, memberRangeExtMap, sourceMemberRangeExt, bdRangeAwards, cuMemberRangeExtList, false)) {
                        break;
                    }
                }
                cuMemberAwardsList.add(getCuMemberAwards(sourceMemberRangeExt, period, saOrderExt, bdRangeAwards));
                sourceMemberRangeExt.setPkRangeAwards(bdRangeAwards.getPkId());
                sourceMemberRangeExt.setPkAwards(bdRangeAwards.getPkAwards());
                sourceMemberRangeExt.setRangeAwardsValue(bdRangeAwards.getAwardsValue());
                rangeAwardsValue += 2;
            } else {
                break;
            }
        }
        // 当月有消费，修改为考核通过
        if (sourceMemberRangeExt.getMonthMember() == EYesNo.YES.getIntValue() && ComputeUtil.compareValue(sourceMemberRangeExt.getMonthPv())) {
            sourceMemberRangeExt.setAssessStatus(EAssessStatus.EXAMINE_PASS.getValue());
        }
        sourceMemberRangeExt.setConsumeStatus(EYesNo.YES.getIntValue());
        return cuMemberAwardsList;
    }

    /**
     * 计算团队极差奖衔
     */
    public List<CuMemberAwards> calculateBloodRangeAwards(Integer period, Map<Long, List<CuMemberRangeExt>> parentRangeExtMap, Map<Long, CuMemberRangeExt> memberRangeExtMap, String rangeTableName, SaOrderExt saOrderExt,
                                                          Map<Integer, BdRangeAwards> bloodRangeAwardsMap, long pkParent, String secondRangeTableName) {
        // 计算血缘奖衔，一级一级升级，分为2段，s2、s3 一级，s3以上一级，先验证团队总业绩,
        // 小市场先验证目前小市场加新增是否满足，满足计算，不满足不计算，不满足小市场先累计，算小市场，每天最终计算完毕重新计算S1以上小市场
        List<CuMemberAwards> cuMemberAwardsList = new ArrayList<>();
        CuMemberRangeExt sourceMemberRangeExt = memberRangeExtMap.get(saOrderExt.getPkMember());
        while (true) {
            CuMemberRangeExt targetMemberRangeExt = memberRangeExtMap.get(pkParent);
            if (targetMemberRangeExt == null) {
                break;
            }
            // 无效会员不累计业绩,当月会员有消费，上月会员考核通过
            if (EYesNo.YES.getIntValue() == targetMemberRangeExt.getConsumeStatus()) {
                targetMemberRangeExt.setTeamConsumeAmount(ComputeUtil.computeAdd(targetMemberRangeExt.getTeamConsumeAmount(), saOrderExt.getOrderAmount()));
                targetMemberRangeExt.setTeamConsumePv(ComputeUtil.computeAdd(targetMemberRangeExt.getTeamConsumePv(), ComputeUtil.computeAdd(saOrderExt.getOrderAchieve(), saOrderExt.getOrderAssAchieve())));
                targetMemberRangeExt.setTeamMonthAmount(ComputeUtil.computeAdd(targetMemberRangeExt.getTeamMonthAmount(), saOrderExt.getOrderAmount()));
                targetMemberRangeExt.setTeamMonthPv(ComputeUtil.computeAdd(targetMemberRangeExt.getTeamMonthPv(), ComputeUtil.computeAdd(saOrderExt.getOrderAchieve(), saOrderExt.getOrderAssAchieve())));
                targetMemberRangeExt.setNewTeamPv(ComputeUtil.computeAdd(targetMemberRangeExt.getNewTeamPv(), ComputeUtil.computeAdd(saOrderExt.getOrderAchieve(), saOrderExt.getOrderAssAchieve())));

                sourceMemberRangeExt.setDeptTeamConsumeAmount(ComputeUtil.computeAdd(sourceMemberRangeExt.getDeptTeamConsumeAmount(), saOrderExt.getOrderAmount()));
                sourceMemberRangeExt.setDeptTeamConsumePv(ComputeUtil.computeAdd(sourceMemberRangeExt.getDeptTeamConsumePv(), ComputeUtil.computeAdd(saOrderExt.getOrderAchieve(), saOrderExt.getOrderAssAchieve())));
                sourceMemberRangeExt.setDeptTeamMonthAmount(ComputeUtil.computeAdd(sourceMemberRangeExt.getDeptTeamMonthAmount(), saOrderExt.getOrderAmount()));
                sourceMemberRangeExt.setDeptTeamMonthPv(ComputeUtil.computeAdd(sourceMemberRangeExt.getDeptTeamMonthPv(), ComputeUtil.computeAdd(saOrderExt.getOrderAchieve(), saOrderExt.getOrderAssAchieve())));
                sourceMemberRangeExt.setDeptNewTeamPv(ComputeUtil.computeAdd(sourceMemberRangeExt.getDeptNewTeamPv(), ComputeUtil.computeAdd(saOrderExt.getOrderAchieve(), saOrderExt.getOrderAssAchieve())));
            }
            if (targetMemberRangeExt.getAssessStatus() == EAssessStatus.EXAMINE_PASS.getValue()) {
                int rangeAwardsValue = 2;
                while (bloodRangeAwardsMap.containsKey(targetMemberRangeExt.getRangeAwardsValue() + rangeAwardsValue)) {
                    // 验证pv是否满足
                    BdRangeAwards bdRangeAwards = bloodRangeAwardsMap.get(targetMemberRangeExt.getRangeAwardsValue() + rangeAwardsValue);
                    if (ComputeUtil.compareValue(targetMemberRangeExt.getTeamConsumePv(), bdRangeAwards.getTeamConsumeCheck())) {
                        // 去结算表种查询该会员下所有会员，会员团队业绩+消费业绩是业绩 计算小区业绩 团队业绩-小区业绩 验证小区、直推必有一种
                        List<CuMemberRangeExt> cuMemberRangeExtList;
                        if (secondRangeTableName != null) {
                            cuMemberRangeExtList = iCuMemberRangeService.querySecondCuMemberRangeExtByParent(rangeTableName, secondRangeTableName, targetMemberRangeExt.getPkMember());
                        } else {
                            cuMemberRangeExtList = iCuMemberRangeService.queryCuMemberRangeExtByParent(rangeTableName, targetMemberRangeExt.getPkMember(), saOrderExt.getPayTime());
                        }
                        if (cuMemberRangeExtList.size() > 0) {
                            if (calculateAwards(parentRangeExtMap, memberRangeExtMap, targetMemberRangeExt, bdRangeAwards, cuMemberRangeExtList, true)) {
                                break;
                            }
                            // 验证血缘部门，需要有几个部门大于考核等级，数据库验证一次，
                            // 当日的实时奖衔，这个位置直接在会员表中计算就可以
                            if (bdRangeAwards.getPlaceNum() > 0) {
                                if (secondRangeTableName != null) {
                                    iCuMemberRangeService.mergeSecondCuMemberRangeExt(secondRangeTableName, parentRangeExtMap.get(targetMemberRangeExt.getPkMember()));
                                    // 验证
                                    Integer placeNum = iCuMemberRangeService.validateSecondCuMemberPlaceAwards(secondRangeTableName, cuMemberRangeExtList, bdRangeAwards.getCheckAwards());
                                    if (bdRangeAwards.getPlaceNum() > placeNum) {
                                        break;
                                    }
                                } else {
                                    // 更新网体，更新伞下
                                    iCuMemberRangeService.mergeCuMemberRangeExt(rangeTableName, parentRangeExtMap.get(targetMemberRangeExt.getPkMember()));
                                    // 验证
                                    Integer placeNum = iCuMemberRangeService.validateCuMemberPlaceAwards(rangeTableName, cuMemberRangeExtList, bdRangeAwards.getCheckAwards(), saOrderExt.getPayTime());
                                    if (bdRangeAwards.getPlaceNum() > placeNum) {
                                        break;
                                    }
                                }
                            }
                        }
                        cuMemberAwardsList.add(getCuMemberAwards(targetMemberRangeExt, period, saOrderExt, bdRangeAwards));
                        targetMemberRangeExt.setPkRangeAwards(bdRangeAwards.getPkId());
                        targetMemberRangeExt.setPkAwards(bdRangeAwards.getPkAwards());
                        targetMemberRangeExt.setRangeAwardsValue(bdRangeAwards.getAwardsValue());
                        rangeAwardsValue += 2;
                        continue;
                    }
                    break;
                }
            }
            pkParent = targetMemberRangeExt.getPkParent();
            sourceMemberRangeExt = targetMemberRangeExt;
        }
        return cuMemberAwardsList;
    }

    /**
     * 计算团队极差奖衔
     */
    public List<CuMemberAwards> calculateRetailRangeGradeAwards(Integer period, Map<Long, CuMemberRetailRangeExt> memberRangeExtMap, String rangeTableName, SaOrderExt saOrderExt,
                                                                Map<Integer, BdGrade> retailTeamGradeMap, Map<Integer, BdAwards> retailAwardsMap, String secondRangeTableName,
                                                                Integer boxNum, List<CuMemberGrade> cuMemberGradeList, Map<Long, Date> activateMap) {
        // 会员奖衔升级列表
        List<CuMemberAwards> cuMemberAwardsList = new ArrayList<>();
        // 订单会员
        CuMemberRetailRangeExt sourceMemberRangeExt = memberRangeExtMap.get(saOrderExt.getPkMember());
        // 订单会员的推荐人
        CuMemberRetailRangeExt targetMemberRangeExt = memberRangeExtMap.get(sourceMemberRangeExt.getPkParent());

        BigDecimal orderAchieve = saOrderExt.getOrderAchieve();
        BigDecimal orderAmount = saOrderExt.getOrderAmount();
        while (null != targetMemberRangeExt) {
            // 手动激活时间
            if (EYesNo.NO.getIntValue() == targetMemberRangeExt.getEnableStatus()
                    && activateMap.containsKey(targetMemberRangeExt.getPkMember())) {
                // 存在手动激活
                targetMemberRangeExt.setEnableStatus(EYesNo.YES.getIntValue());
            }

            // 激活的账号才能累计业绩和盒数（有注册、升级订单）
            if (targetMemberRangeExt.getEnableStatus() == EYesNo.YES.getIntValue()) {
                // 累计业绩
                targetMemberRangeExt.setTeamConsumeAmount(ComputeUtil.computeAdd(targetMemberRangeExt.getTeamConsumeAmount(), orderAmount));
                targetMemberRangeExt.setTeamConsumePv(ComputeUtil.computeAdd(targetMemberRangeExt.getTeamConsumePv(), orderAchieve));
                targetMemberRangeExt.setTeamMonthAmount(ComputeUtil.computeAdd(targetMemberRangeExt.getTeamMonthAmount(), orderAmount));
                targetMemberRangeExt.setTeamMonthPv(ComputeUtil.computeAdd(targetMemberRangeExt.getTeamMonthPv(), orderAchieve));
                targetMemberRangeExt.setTeamNewAmount(ComputeUtil.computeAdd(targetMemberRangeExt.getTeamNewAmount(), orderAmount));
                targetMemberRangeExt.setTeamNewPv(ComputeUtil.computeAdd(targetMemberRangeExt.getTeamNewPv(), orderAchieve));
                // 累计盒数
                targetMemberRangeExt.setTeamBoxNum(targetMemberRangeExt.getTeamBoxNum() + boxNum);
                targetMemberRangeExt.setMonthBoxNum(targetMemberRangeExt.getMonthBoxNum() + boxNum);
                targetMemberRangeExt.setTeamNewBoxNum(targetMemberRangeExt.getTeamNewBoxNum() + boxNum);
                // 计算等级
                calculateGradeAwards(period, memberRangeExtMap, rangeTableName, saOrderExt, retailTeamGradeMap, retailAwardsMap,
                        secondRangeTableName, cuMemberGradeList, cuMemberAwardsList, targetMemberRangeExt, activateMap);
            }
            targetMemberRangeExt = memberRangeExtMap.get(targetMemberRangeExt.getPkParent());
        }
        return cuMemberAwardsList;
    }

    private void calculateGradeAwards(Integer period, Map<Long, CuMemberRetailRangeExt> memberRangeExtMap, String rangeTableName,
                                      SaOrderExt saOrderExt, Map<Integer, BdGrade> retailTeamGradeMap, Map<Integer, BdAwards> retailAwardsMap,
                                      String secondRangeTableName, List<CuMemberGrade> cuMemberGradeList, List<CuMemberAwards> cuMemberAwardsList,
                                      CuMemberRetailRangeExt targetMemberRangeExt, Map<Long, Date> activateMap) {
        if (EYesNo.NO.getIntValue() == targetMemberRangeExt.getEnableStatus()
                && activateMap.containsKey(targetMemberRangeExt.getPkMember())) {
            // 存在手动激活
            targetMemberRangeExt.setEnableStatus(EYesNo.YES.getIntValue());
        }

        // 遍历团队等级map（V4,V5）
        for (Integer gradeValue : retailTeamGradeMap.keySet()) {
            BdGrade bdGrade = retailTeamGradeMap.get(gradeValue);

            // 如果等级值 大于 当前会员等级值 并且 等级要求累计盒数 小于等于 团队累计盒数 + 累计消费盒数，则可以进行升级
            if (bdGrade.getGradeValue() > targetMemberRangeExt.getGradeValue()
                    && bdGrade.getBoxTotal() <= (targetMemberRangeExt.getTeamBoxNum() + targetMemberRangeExt.getConsumeBoxNum())) {
                // 验证小区，计算小区累计盒数 查询伞下会员
                List<CuMemberRetailRangeExt> cuMemberRangeExtList;
                if (secondRangeTableName != null) {
                    // 秒结表关联昨日结算表，查询订单会员直推数据
                    cuMemberRangeExtList = iCuMemberRetailRangeService.queryCuMemberSecondRangeExtByParent(rangeTableName, secondRangeTableName, targetMemberRangeExt.getPkMember());
                } else {
                    // 昨日结算表，查询订单会员直推数据
                    cuMemberRangeExtList = iCuMemberRetailRangeService.queryCuMemberRetailRangeExtByParent(rangeTableName, targetMemberRangeExt.getPkMember());
                }

                // new 新逻辑确认：注水 2 个虚拟区，自己消费 1 个虚拟区，伞下直推，所有的最大
                // 大区盒数（默认为自己累计消费盒数）
                int bigBoxNum = targetMemberRangeExt.getConsumeBoxNum();
                if (targetMemberRangeExt.getBigBoxNum() > bigBoxNum) {
                    // 注水大区如果大则使用注水盒数为大区
                    bigBoxNum = targetMemberRangeExt.getBigBoxNum();
                }
                // 秒结补全直推数据，此处秒结和日结可以使用同一逻辑
                for (CuMemberRetailRangeExt cuMemberRetailRangeExt : cuMemberRangeExtList) {
                    if (memberRangeExtMap.containsKey(cuMemberRetailRangeExt.getPkMember())) {
                        cuMemberRetailRangeExt = memberRangeExtMap.get(cuMemberRetailRangeExt.getPkMember());
                    }
                    // 最新确认逻辑，计算大小区时，不需要去掉注水
                    // 伞下团队累计盒数 + 自己消费盒数
                    int areaBoxNum = cuMemberRetailRangeExt.getTeamBoxNum() + cuMemberRetailRangeExt.getConsumeBoxNum();
                    if (areaBoxNum > bigBoxNum) {
                        // 实际订单累计盒数 大于 累计消费盒数，实际订单累计盒数为大区
                        bigBoxNum = areaBoxNum;
                    }
                }

                // 小区盒数
                int smallBoxNum = targetMemberRangeExt.getTeamBoxNum() + targetMemberRangeExt.getConsumeBoxNum() - bigBoxNum;
                if (smallBoxNum >= bdGrade.getBoxSmallTotal()) {
                    // 小区盒数 大于等于 升级小区盒数
                    CuMemberGrade cuMemberGrade = getCuMemberGrade(period, targetMemberRangeExt, bdGrade);
                    cuMemberGradeList.add(cuMemberGrade);
                    targetMemberRangeExt.setPkGrade(bdGrade.getPkId());
                    targetMemberRangeExt.setGradeValue(bdGrade.getGradeValue());
                    targetMemberRangeExt.setGradeName(bdGrade.getGradeName());
                }
            }
        }
        // 计算奖衔（荣誉级别）
        while (true) {
            // 当前实时奖衔值 + 5，获取下一个奖衔值
            int awardsValue = targetMemberRangeExt.getAwardsValue() + 5;
            if (targetMemberRangeExt.getGradeValue().equals(EGrade.S_VIP.getValue()) && retailAwardsMap.containsKey(awardsValue)) {
                // 等级达到V5 并且 存在下个奖衔，判断是否能升奖衔
                BdAwards bdAwards = retailAwardsMap.get(awardsValue);
                // 先验证累计业绩
                // new 升级奖衔判断为当月累计业绩，累计业绩为团队业绩 + 个人消费业绩
                if (ComputeUtil.compareValue(ComputeUtil.computeAdd(targetMemberRangeExt.getTeamMonthPv(), targetMemberRangeExt.getMonthConsumePv()), bdAwards.getTotalCheck())) {
                    // 累计业绩足够，即可升奖衔
//                    BigDecimal consumeBigPv = BigDecimal.ZERO;
//                    if (ComputeUtil.compareValue(bdAwards.getCommunityCheck())) {
//                        // 验证小区，计算小区业绩
//                        List<CuMemberRetailRangeExt> cuMemberRangeExtList;
//                        if (secondRangeTableName != null) {
//                            cuMemberRangeExtList = iCuMemberRetailRangeService.queryCuMemberSecondRangeExtByParent(rangeTableName, secondRangeTableName, targetMemberRangeExt.getPkMember());
//                        } else {
//                            cuMemberRangeExtList = iCuMemberRetailRangeService.queryCuMemberRetailRangeExtByParent(rangeTableName, targetMemberRangeExt.getPkMember());
//                        }
//                        for (CuMemberRetailRangeExt cuMemberRetailRangeExt : cuMemberRangeExtList) {
//                            if (memberRangeExtMap.containsKey(cuMemberRetailRangeExt.getPkMember())) {
//                                cuMemberRetailRangeExt = memberRangeExtMap.get(cuMemberRetailRangeExt.getPkMember());
//                            }
//                            BigDecimal consumePv = ComputeUtil.computeAdd(cuMemberRetailRangeExt.getMonthConsumePv(), cuMemberRetailRangeExt.getTeamMonthPv());
//                            if (ComputeUtil.compareGreaterThan(consumePv, consumeBigPv)) {
//                                consumeBigPv = consumePv;
//                            }
//                        }
//                    }
//                    BigDecimal smallAreaPv = ComputeUtil.computeSubtract(ComputeUtil.computeAdd(targetMemberRangeExt.getTeamMonthPv(), targetMemberRangeExt.getMonthConsumePv()), consumeBigPv);
//                    if (ComputeUtil.compareValue(smallAreaPv, bdAwards.getCommunityCheck())) {
                    cuMemberAwardsList.add(getCuMemberRetailAwards(targetMemberRangeExt, period, saOrderExt, bdAwards, EAwardsType.RANGE_TYPE.getValue()));
                    targetMemberRangeExt.setPkAwards(bdAwards.getPkId());
                    targetMemberRangeExt.setAwardsValue(bdAwards.getAwardsValue());
                    targetMemberRangeExt.setAwardsName(bdAwards.getAwardsName());
                    continue;
//                    }
                }
            }
            break;
        }
        // 计算分红奖衔（秒结不走这个地方）
        while (true) {
            if (null == targetMemberRangeExt.getShareAwardsValue()) {
                break;
            }
            int awardsValue = targetMemberRangeExt.getShareAwardsValue() + 5;
            if (targetMemberRangeExt.getGradeValue().equals(EGrade.S_VIP.getValue()) && retailAwardsMap.containsKey(awardsValue)) {
                BdAwards bdAwards = retailAwardsMap.get(awardsValue);
                // 先验证累计业绩
                if (ComputeUtil.compareValue(ComputeUtil.computeAdd(targetMemberRangeExt.getTeamMonthPv(), targetMemberRangeExt.getMonthConsumePv()), bdAwards.getShareTotalCheck())) {
                    // 验证小区，计算小区业绩
                    List<CuMemberRetailRangeExt> cuMemberRangeExtList = iCuMemberRetailRangeService.queryCuMemberRetailRangeExtByParent(rangeTableName, targetMemberRangeExt.getPkMember());
                    BigDecimal consumeBigPv = targetMemberRangeExt.getMonthConsumePv();
//                    if (ComputeUtil.compareGreaterThan(targetMemberRangeExt.getBigTeamPv(), consumeBigPv)) {
//                        consumeBigPv = targetMemberRangeExt.getBigTeamPv();
//                    }
                    for (CuMemberRetailRangeExt cuMemberRetailRangeExt : cuMemberRangeExtList) {
                        if (memberRangeExtMap.containsKey(cuMemberRetailRangeExt.getPkMember())) {
                            cuMemberRetailRangeExt = memberRangeExtMap.get(cuMemberRetailRangeExt.getPkMember());
                        }
                        BigDecimal consumePv = ComputeUtil.computeAdd(cuMemberRetailRangeExt.getMonthConsumePv(), cuMemberRetailRangeExt.getTeamMonthPv());
                        if (ComputeUtil.compareGreaterThan(consumePv, consumeBigPv)) {
                            consumeBigPv = consumePv;
                        }
                    }
                    BigDecimal smallAreaPv = ComputeUtil.computeAdd(targetMemberRangeExt.getMonthConsumePv(), ComputeUtil.computeSubtract(targetMemberRangeExt.getTeamMonthPv(), consumeBigPv));
                    if (ComputeUtil.compareValue(smallAreaPv, bdAwards.getShareCommunityCheck())) {
                        if (bdAwards.getPlaceDeptNum() > 0) {
                            // 验证是否有多个区满足业绩
                            List<CuMemberRetailRangeExt> cuMemberRetailRangeExtList = iCuMemberRetailRangeService.queryCuMemberRetailRangeEnoughAchieve(rangeTableName, targetMemberRangeExt.getPkMember(), bdAwards.getShareCommunityCheck());
                            int enoughNum = 0;
                            for (CuMemberRetailRangeExt cuMemberRetailRangeExt : cuMemberRetailRangeExtList) {
                                if (memberRangeExtMap.containsKey(cuMemberRetailRangeExt.getPkMember())) {
                                    cuMemberRetailRangeExt = memberRangeExtMap.get(cuMemberRetailRangeExt.getPkMember());
                                }
                                if (ComputeUtil.compareValue(ComputeUtil.computeAdd(cuMemberRetailRangeExt.getMonthConsumePv(), cuMemberRetailRangeExt.getTeamMonthPv()), bdAwards.getShareCommunityCheck())) {
                                    enoughNum += 1;
                                }
                            }
                            if (bdAwards.getPlaceDeptNum() > enoughNum) {
                                break;
                            }
                        }
                        cuMemberAwardsList.add(getCuMemberRetailAwards(targetMemberRangeExt, period, saOrderExt, bdAwards, EAwardsType.SHARE_TYPE.getValue()));
                        targetMemberRangeExt.setShareAwardsValue(bdAwards.getAwardsValue());
                        targetMemberRangeExt.setPkShareAwards(bdAwards.getPkId());
                        continue;
                    }
                }
            }
            break;
        }
    }

    /**
     * 计算团队极差奖衔
     */
    public List<CuMemberRetailRangeExt> calculateRetailBackRangeGradeAwards(Integer period, Map<Long, CuMemberRetailRangeExt> memberRangeExtMap, String rangeTableName, SaOrderExt saOrderExt,
                                                                            Map<Integer, BdGrade> retailTeamGradeMap, Map<Integer, BdAwards> retailAwardsMap, String secondRangeTableName,
                                                                            Integer boxNum, Map<String, CuMemberGrade> cuMemberGradeMap, Map<String, CuMemberAwards> cuMemberAwardsMap) {
        List<CuMemberRetailRangeExt> cuMemberRetailRangeExtList = new ArrayList<>();
        // 订单会员
        CuMemberRetailRangeExt sourceMemberRangeExt = memberRangeExtMap.get(saOrderExt.getPkMember());
        // 订单会员的推荐人
        CuMemberRetailRangeExt targetMemberRangeExt = memberRangeExtMap.get(sourceMemberRangeExt.getPkParent());

        BigDecimal orderAchieve = saOrderExt.getOrderAchieve();
        BigDecimal orderAmount = saOrderExt.getOrderAmount();
        while (targetMemberRangeExt != null) {
            // 激活的账号才能累计业绩和盒数（有注册、升级订单）
            if (targetMemberRangeExt.getEnableStatus() == EYesNo.YES.getIntValue()) {
                // 累计业绩
                targetMemberRangeExt.setTeamConsumeAmount(ComputeUtil.computeSubtract(targetMemberRangeExt.getTeamConsumeAmount(), orderAmount));
                targetMemberRangeExt.setTeamConsumePv(ComputeUtil.computeSubtract(targetMemberRangeExt.getTeamConsumePv(), orderAchieve));
                targetMemberRangeExt.setTeamMonthAmount(ComputeUtil.computeSubtract(targetMemberRangeExt.getTeamMonthAmount(), orderAmount));
                targetMemberRangeExt.setTeamMonthPv(ComputeUtil.computeSubtract(targetMemberRangeExt.getTeamMonthPv(), orderAchieve));
                targetMemberRangeExt.setTeamNewAmount(ComputeUtil.computeSubtract(targetMemberRangeExt.getTeamNewAmount(), orderAmount));
                targetMemberRangeExt.setTeamNewPv(ComputeUtil.computeSubtract(targetMemberRangeExt.getTeamNewPv(), orderAchieve));
                // 累计盒数
                targetMemberRangeExt.setTeamBoxNum(targetMemberRangeExt.getTeamBoxNum() - boxNum);
                targetMemberRangeExt.setMonthBoxNum(targetMemberRangeExt.getMonthBoxNum() - boxNum);
                targetMemberRangeExt.setTeamNewBoxNum(targetMemberRangeExt.getTeamNewBoxNum() - boxNum);
                // 计算等级
                calculateBackGrade(period, memberRangeExtMap, rangeTableName, saOrderExt, retailTeamGradeMap, retailAwardsMap, secondRangeTableName, cuMemberGradeMap, cuMemberAwardsMap, targetMemberRangeExt);
                cuMemberRetailRangeExtList.add(targetMemberRangeExt);
            }
            // 计算等级
            targetMemberRangeExt = memberRangeExtMap.get(targetMemberRangeExt.getPkParent());
        }
        return cuMemberRetailRangeExtList;
    }

    private void calculateBackGrade(Integer period, Map<Long, CuMemberRetailRangeExt> memberRangeExtMap, String rangeTableName,
                                    SaOrderExt saOrderExt, Map<Integer, BdGrade> retailTeamGradeMap, Map<Integer, BdAwards> retailAwardsMap,
                                    String secondRangeTableName, Map<String, CuMemberGrade> cuMemberGradeMap, Map<String, CuMemberAwards> cuMemberAwardsMap,
                                    CuMemberRetailRangeExt targetMemberRangeExt) {
        // 遍历团队等级map（V4,V5）
        for (Integer gradeValue : retailTeamGradeMap.keySet()) {
            BdGrade bdGrade = retailTeamGradeMap.get(gradeValue);

            if (bdGrade.getBoxTotal() <= (targetMemberRangeExt.getTeamBoxNum() + targetMemberRangeExt.getConsumeBoxNum())) {
                // 验证小区，计算小区累计盒数 查询伞下会员
                List<CuMemberRetailRangeExt> cuMemberRangeExtList;
                if (secondRangeTableName != null) {
                    // 秒结表关联昨日结算表，查询订单会员直推数据
                    cuMemberRangeExtList = iCuMemberRetailRangeService.queryCuMemberSecondRangeExtByParent(rangeTableName, secondRangeTableName, targetMemberRangeExt.getPkMember());
                } else {
                    // 昨日结算表，查询订单会员直推数据
                    cuMemberRangeExtList = iCuMemberRetailRangeService.queryCuMemberRetailRangeExtByParent(rangeTableName, targetMemberRangeExt.getPkMember());
                }

                // new 新逻辑确认：注水 2 个虚拟区，自己消费 1 个虚拟区，伞下直推，所有的最大
                // 大区盒数（默认为自己累计消费盒数）
                int bigBoxNum = targetMemberRangeExt.getConsumeBoxNum();
                if (targetMemberRangeExt.getBigBoxNum() > bigBoxNum) {
                    // 注水大区如果大则使用注水盒数为大区
                    bigBoxNum = targetMemberRangeExt.getBigBoxNum();
                }
                // 秒结补全直推数据，此处秒结和日结可以使用同一逻辑
                for (CuMemberRetailRangeExt cuMemberRetailRangeExt : cuMemberRangeExtList) {
                    if (memberRangeExtMap.containsKey(cuMemberRetailRangeExt.getPkMember())) {
                        cuMemberRetailRangeExt = memberRangeExtMap.get(cuMemberRetailRangeExt.getPkMember());
                    }
                    // 最新确认逻辑，计算大小区时，不需要去掉注水
                    // 伞下团队累计盒数 + 自己消费盒数
                    int areaBoxNum = cuMemberRetailRangeExt.getTeamBoxNum() + cuMemberRetailRangeExt.getConsumeBoxNum();
                    if (areaBoxNum > bigBoxNum) {
                        // 实际订单累计盒数 大于 累计消费盒数，实际订单累计盒数为大区
                        bigBoxNum = areaBoxNum;
                    }
                }

                // 小区盒数
                int smallBoxNum = targetMemberRangeExt.getTeamBoxNum() + targetMemberRangeExt.getConsumeBoxNum() - bigBoxNum;
                if (smallBoxNum >= bdGrade.getBoxSmallTotal()) {
                    // 小区盒数 大于等于 升级小区盒数
                    CuMemberGrade cuMemberGrade = getCuMemberGrade(period, targetMemberRangeExt, bdGrade);
                    cuMemberGradeMap.put(cuMemberGrade.getPkMember() + "_" + cuMemberGrade.getNewLevel(), cuMemberGrade);
                    targetMemberRangeExt.setGradeValue(bdGrade.getGradeValue());
                    targetMemberRangeExt.setPkGrade(bdGrade.getPkId());
                    targetMemberRangeExt.setGradeName(bdGrade.getGradeName());
                }
            }
        }
        // 计算奖衔（荣誉级别）
        while (true) {
            int awardsValue = targetMemberRangeExt.getAwardsValue() + 5;
            if (targetMemberRangeExt.getGradeValue().equals(EGrade.S_VIP.getValue()) && retailAwardsMap.containsKey(awardsValue)) {
                // 等级达到V5 并且 存在下个奖衔，判断是否能升奖衔
                BdAwards bdAwards = retailAwardsMap.get(awardsValue);
                // 先验证累计业绩
                // new 升级奖衔判断为当月累计业绩，累计业绩为团队业绩 + 个人消费业绩
                if (ComputeUtil.compareValue(ComputeUtil.computeAdd(targetMemberRangeExt.getTeamMonthPv(), targetMemberRangeExt.getMonthConsumePv()), bdAwards.getTotalCheck())) {
                    // 累计业绩足够，即可升奖衔
//                    // 验证小区，计算小区业绩
//                    List<CuMemberRetailRangeExt> cuMemberRangeExtList;
//                    if (secondRangeTableName != null) {
//                        cuMemberRangeExtList = iCuMemberRetailRangeService.queryCuMemberSecondRangeExtByParent(rangeTableName, secondRangeTableName, targetMemberRangeExt.getPkMember());
//                    } else {
//                        cuMemberRangeExtList = iCuMemberRetailRangeService.queryCuMemberRetailRangeExtByParent(rangeTableName, targetMemberRangeExt.getPkMember());
//                    }
//                    BigDecimal consumeBigPv = BigDecimal.ZERO;
//                    for (CuMemberRetailRangeExt cuMemberRetailRangeExt : cuMemberRangeExtList) {
//                        if (memberRangeExtMap.containsKey(cuMemberRetailRangeExt.getPkMember())) {
//                            cuMemberRetailRangeExt = memberRangeExtMap.get(cuMemberRetailRangeExt.getPkMember());
//                        }
//                        BigDecimal consumePv = ComputeUtil.computeAdd(cuMemberRetailRangeExt.getMonthConsumePv(), cuMemberRetailRangeExt.getTeamMonthPv());
//                        if (ComputeUtil.compareGreaterThan(consumePv, consumeBigPv)) {
//                            consumeBigPv = consumePv;
//                        }
//                    }
//                    BigDecimal smallAreaPv = ComputeUtil.computeSubtract(targetMemberRangeExt.getTeamMonthPv(), consumeBigPv);
//                    if (ComputeUtil.compareValue(smallAreaPv, bdAwards.getCommunityCheck())) {
                    CuMemberAwards cuMemberRetailAwards = getCuMemberRetailAwards(targetMemberRangeExt, period, saOrderExt, bdAwards, EAwardsType.RANGE_TYPE.getValue());
                    cuMemberAwardsMap.put(cuMemberRetailAwards.getPkMember() + "_" + cuMemberRetailAwards.getNewLevel(), cuMemberRetailAwards);
                    targetMemberRangeExt.setPkAwards(bdAwards.getPkId());
                    targetMemberRangeExt.setAwardsValue(bdAwards.getAwardsValue());
                    targetMemberRangeExt.setAwardsName(bdAwards.getAwardsName());
                    continue;
//                    }
                }
            }
            break;
        }
    }

    /**
     * 计算奖衔，验证小区业绩和推荐数量是否满足
     */
    private boolean calculateAwards(Map<Long, List<CuMemberRangeExt>> parentRangeExtMap, Map<Long, CuMemberRangeExt> memberRangeExtMap, CuMemberRangeExt targetMemberRangeExt, BdRangeAwards bdRangeAwards, List<CuMemberRangeExt> cuMemberRangeExtList, Boolean isRecommend) {
        BigDecimal bigAreaPv = BigDecimal.ZERO;
        Integer recommendNum = 0;
        for (CuMemberRangeExt cuMemberRangeExt : cuMemberRangeExtList) {
            if (parentRangeExtMap.containsKey(cuMemberRangeExt.getPkParent())) {
                parentRangeExtMap.get(cuMemberRangeExt.getPkParent()).add(cuMemberRangeExt);
            } else {
                List<CuMemberRangeExt> memberRangeExtList = new ArrayList<>();
                memberRangeExtList.add(cuMemberRangeExt);
                parentRangeExtMap.put(cuMemberRangeExt.getPkParent(), memberRangeExtList);
            }
            if (memberRangeExtMap.containsKey(cuMemberRangeExt.getPkMember())) {
                cuMemberRangeExt = memberRangeExtMap.get(cuMemberRangeExt.getPkMember());
            }
            // 团队业绩+个人业绩
            BigDecimal validatePv = ComputeUtil.computeAdd(cuMemberRangeExt.getDeptTeamConsumePv(), cuMemberRangeExt.getConsumePv());
            if (ComputeUtil.compareValue(validatePv, bigAreaPv)) {
                bigAreaPv = validatePv;
            }
            // 有效的,等级满足的算推荐数量、验证部门数量的 需要走语句
            if (cuMemberRangeExt.getAssessStatus() == EAssessStatus.EXAMINE_PASS.getValue() && bdRangeAwards.getCheckAwards() <= cuMemberRangeExt.getPkRangeAwards()) {
                recommendNum += 1;
            }
        }
        // 小区业绩
        BigDecimal communityCheck = ComputeUtil.computeSubtract(targetMemberRangeExt.getTeamConsumePv(), bigAreaPv);
        // 验证小区,验证失败
        if (ComputeUtil.compareGreaterThan(bdRangeAwards.getCommunityCheck(), communityCheck)) {
            return true;
        }
        // 验证推荐
        return isRecommend && bdRangeAwards.getRecommendNum() > recommendNum;
    }

//    /*
//     *  计算幸运奖，先计算有效代数，所有有效代数均分，比例10%
//     * @author: sui q
//     * @date: 2024/10/17 11:34
//     * @param: null null
//     **/
//    List<CuMemberBonusCoach> calculateLuckBonus(Map<Long, CuMemberRangeExt> memberRangeExtMap, Map<Long, CuMemberBonus> cuMemberBonusMap, BonusConfigDTO bonusConfigDTO,
//                                                Integer period, SaOrderExt saOrderExt) {
//        CuMemberRangeExt sourceMemberRangeExt = memberRangeExtMap.get(saOrderExt.getPkMember());
//        long pkParent = sourceMemberRangeExt.getPkParent();
//        int generation = 1;
//        List<CuMemberBonusCoach> memberBonusCoachList = new ArrayList<>();
//        // 计算代数
//        while (true) {
//            CuMemberRangeExt targetMemberRangeExt = memberRangeExtMap.get(pkParent);
//            if (targetMemberRangeExt == null) {
//                generation--;
//                break;
//            }
//            pkParent = targetMemberRangeExt.getPkParent();
//            if (ECategory.NORMAL.getValue() != targetMemberRangeExt.getCategory() ||
//                    EAccountStatus.STOP_INCOME.getValue() == targetMemberRangeExt.getAccountStatus()) {
//                continue;
//            }
//            // 验证推荐有效代数是否大于当前代数
//            if (targetMemberRangeExt.getEffectiveNum() >= generation && EAssessStatus.EXAMINE_PASS.getValue() == targetMemberRangeExt.getAssessStatus()) {
//                getCuMemberBonus(period, cuMemberBonusMap, targetMemberRangeExt.getPkMember(),
//                        targetMemberRangeExt.getIncomeStatus(), targetMemberRangeExt.getPkSettleCountry(), targetMemberRangeExt.getPkRate());
//                CuMemberBonusCoach cuMemberBonusCoach = getCuMemberBonusCoach(bonusConfigDTO, saOrderExt, generation, targetMemberRangeExt);
//                memberBonusCoachList.add(cuMemberBonusCoach);
//                generation++;
//            }
//        }
//        // 奖金
//        BigDecimal bonusRatio = ComputeUtil.computeDivide(BigDecimal.valueOf(10), BigDecimal.valueOf(generation));
//        for (CuMemberBonusCoach cuMemberBonusCoach : memberBonusCoachList) {
//            cuMemberBonusCoach.setCoachGeneration(generation);
//            cuMemberBonusCoach.setCalValue(bonusRatio);
//            cuMemberBonusCoach.setPretaxIncome(ComputeUtil.computeBonusMultiply(cuMemberBonusCoach.getCalAchieve(), bonusRatio));
//            CuMemberRangeExt targetMemberRangeExt = memberRangeExtMap.get(cuMemberBonusCoach.getPkBonus());
//            CuMemberBonus cuMemberBonus = cuMemberBonusMap.get(cuMemberBonusCoach.getPkBonus());
//            BdBonusDeduct bdBonusDeduct = setBonusDetailDeduct(bonusConfigDTO, cuMemberBonusCoach, saOrderExt.getOrderAmount(), saOrderExt.getInExchangeRate());
//            coachRangeRemark(saOrderExt, cuMemberBonusCoach, sourceMemberRangeExt, targetMemberRangeExt);
//            if (EBonusIncomeStatus.NORMAL.getValue() == cuMemberBonusCoach.getIncomeStatus()) {
//                cuMemberBonus.setCloudDirectIncome(ComputeUtil.computeAdd(cuMemberBonus.getCloudDirectIncome(), cuMemberBonusCoach.getPretaxIncome()));
//                setCloudTotal(bdBonusDeduct, cuMemberBonus, cuMemberBonusCoach);
//            }
//        }
//        return memberBonusCoachList;
//    }

    /**
     * 计算直推级差收益，根据直推级差收益计算平级收益
     */
    List<CuMemberBonusRange> calculateRetailRangeBonus(Map<Long, CuMemberRetailRangeExt> memberRangeExtMap, Map<Long, CuMemberBonus> cuMemberBonusMap,
                                                       Map<Integer, BdGrade> gradeMap, BonusConfigDTO bonusConfigDTO, Integer period,
                                                       SaOrderWaresExt saOrderItems, SaOrderExt saOrderExt) {
        // 直推级差返回数据
        List<CuMemberBonusRange> memberBonusRangeList = new ArrayList<>();
        // 用等级计算，按照一级级算

        // 订单下单人自己
        CuMemberRetailRangeExt sourceMemberRangeExt = memberRangeExtMap.get(saOrderExt.getPkMember());
        // 推荐人
        long pkParent = sourceMemberRangeExt.getPkParent();

//        // 商品价格
//        BigDecimal beginBuyPrice = saOrderItems.getWaresPrice();
//        BigDecimal comBuyPrice = saOrderItems.getWaresPrice();
//
//        // 开始计算等级值
//        int beginGradeValue = sourceMemberRangeExt.getGradeValue();
//        // 直推级差收益
//        BigDecimal calBonusIncome = BigDecimal.ZERO;

        // 商品最终价格
        BigDecimal waresPrice = saOrderItems.getWaresPrice();
        // 商品数量
        BigDecimal waresQuantityBig = new BigDecimal(saOrderItems.getWaresQuantity());
        // 前一个会员等级
        int beforeGradeValue = 0;
        // 前一个会员等级的平级收益人数
        int beforeSameAlgebra = 0;
        // 前一个会员等级的平级收益
        BigDecimal beforeSameBonus = BigDecimal.ZERO;
        // 计算直推级差
        while (true) {
            // 推荐人
            CuMemberRetailRangeExt targetMemberRangeExt = memberRangeExtMap.get(pkParent);
            if (targetMemberRangeExt == null) {
                break;
            }
            // 推荐人的推荐人
            pkParent = targetMemberRangeExt.getPkParent();

            if (EAccountStatus.STOP_INCOME.getValue() == targetMemberRangeExt.getAccountStatus()
                    || ECategory.NORMAL.getValue() != targetMemberRangeExt.getCategory()
                    || targetMemberRangeExt.getEnableStatus() == EYesNo.NO.getIntValue()
                    || targetMemberRangeExt.getGradeValue() == EGrade.START_UP.getValue()
                    || EIncomeStatus.STOP_INCOME.getValue() == targetMemberRangeExt.getIncomeStatus()) {
                // 停算收益、非正常会员、未激活、等级为顾客、停止收益，直接跳过
                continue;
            }
            // 当前会员等级值
            int calGradeValue = targetMemberRangeExt.getGradeValue();
            // 当前会员等级
            BdGrade bdGrade = gradeMap.get(calGradeValue);

            // 直推级差税前收益
            BigDecimal rangeBonusIncome = null;
            // 平级税前收益
            BigDecimal sameBonusIncome = null;

            if (beforeGradeValue == 0) {
                // 前一个会员等级为0，肯定为第一次处理，直接处理直推级差收益
                if (EGrade.HAI_FAN.getValue() == calGradeValue) {
                    // VIP，拿1份40
                    rangeBonusIncome = RetailConstants.RANGE_BONUS.multiply(waresQuantityBig);
                } else if (EGrade.YOU_KE.getValue() == calGradeValue) {
                    // SVIP，拿2份40
                    rangeBonusIncome = RetailConstants.RANGE_BONUS.multiply(waresQuantityBig).multiply(new BigDecimal("2"));
                } else if (EGrade.MAKER.getValue() == calGradeValue) {
                    // 卓越，拿3份40
                    rangeBonusIncome = RetailConstants.RANGE_BONUS.multiply(waresQuantityBig).multiply(new BigDecimal("3"));
                } else if (EGrade.VIP.getValue() == calGradeValue) {
                    // 首席，拿4份40
                    rangeBonusIncome = RetailConstants.RANGE_BONUS.multiply(waresQuantityBig).multiply(new BigDecimal("4"));
                } else if (EGrade.S_VIP.getValue() == calGradeValue) {
                    // 合伙人，拿5份40
                    rangeBonusIncome = RetailConstants.RANGE_BONUS.multiply(waresQuantityBig).multiply(new BigDecimal("5"));
                }
                // 赋值前一个会员等级
                beforeGradeValue = calGradeValue;
            } else if (calGradeValue == beforeGradeValue) {
                // 当前会员等级 = 前一个会员等级
                if (EGrade.HAI_FAN.getValue() == calGradeValue) {
                    // V1 没有平级收益
                    continue;
                }
                if (beforeSameAlgebra >= bdGrade.getAlgebra()) {
                    // 平级收益已经满10代，不继续处理平级收益
                    if (EGrade.S_VIP.getValue() == beforeGradeValue) {
                        // 平级处理等级为最高级V5，则结束处理
                        break;
                    }
                    continue;
                }
                // 平级收益（商品价格 * 千分之五） -- 2位小数，四舍五入
                sameBonusIncome = waresPrice.multiply(RetailConstants.SAME_RATIO).setScale(2, BigDecimal.ROUND_HALF_UP);
                // 平级收益累计
                beforeSameBonus = beforeSameBonus.add(sameBonusIncome);
                // 平级等级代数等级
                beforeSameAlgebra += 1;
            } else if (calGradeValue > beforeGradeValue) {
                // 当前会员等级 > 前一个会员等级
                int tmpGradeVal = (calGradeValue - beforeGradeValue) / 10;

                // 新等级的直推级差收益
                rangeBonusIncome = RetailConstants.RANGE_BONUS.multiply(waresQuantityBig).multiply(new BigDecimal(tmpGradeVal));
                // 直推级差收益 = 新等级的直推级差收益 - 上一等级的平级收益
                rangeBonusIncome = rangeBonusIncome.subtract(beforeSameBonus);

                // 赋值前一个会员等级
                beforeGradeValue = calGradeValue;
                // 平级收益记录从新开始计算
                beforeSameAlgebra = 0;
                beforeSameBonus = BigDecimal.ZERO;
            } else {
                // 当前会员等级 < 前一个会员等级，直接跳过
                continue;
            }

            if (null != rangeBonusIncome) {
                // 处理直推级差收益
                CuMemberBonus cuMemberBonus = getCuMemberBonus(period, cuMemberBonusMap, targetMemberRangeExt.getPkMember(),
                        targetMemberRangeExt.getIncomeStatus(), targetMemberRangeExt.getPkSettleCountry(), targetMemberRangeExt.getPkRate() == null ? saOrderExt.getPkRate() : targetMemberRangeExt.getPkRate());
                int pkBonusItems = getPkBonusItems(bonusConfigDTO, targetMemberRangeExt.getPkSettleCountry(), EBonusItems.RETAIL_RANGE_INCOME.getValue());
                CuMemberBonusRange cuMemberBonusRange = getCuMemberRetailBonusRange(saOrderExt, targetMemberRangeExt, cuMemberBonus, pkBonusItems);
                cuMemberBonusRange.setCalValue(BigDecimal.ZERO);
                cuMemberBonusRange.setCalAchieve(waresPrice);
                cuMemberBonusRange.setPretaxIncome(rangeBonusIncome);
                cuMemberBonusRange.setPkRange(targetMemberRangeExt.getPkGrade());
                cuMemberBonusRange.setPkBeforeRange(sourceMemberRangeExt.getPkGrade());
                cuMemberBonusRange.setPkOrderItems(saOrderItems.getPkId());
                rangeRetailRemark(saOrderExt, cuMemberBonusRange, sourceMemberRangeExt, targetMemberRangeExt);
                BdBonusDeduct bdBonusDeduct = setBonusDetailDeduct(bonusConfigDTO, cuMemberBonusRange, saOrderExt.getOrderAmount(), saOrderExt.getInExchangeRate());
                if (EBonusIncomeStatus.NORMAL.getValue() == cuMemberBonusRange.getIncomeStatus()) {
                    cuMemberBonus.setRetailRangeIncome(ComputeUtil.computeAdd(cuMemberBonus.getRetailRangeIncome(), cuMemberBonusRange.getPretaxIncome()));
                    setRetailTotal(bdBonusDeduct, cuMemberBonus, cuMemberBonusRange);
                }
                memberBonusRangeList.add(cuMemberBonusRange);
            }
            if (null != sameBonusIncome) {
                // 处理平级收益
                CuMemberBonus cuMemberBonus = getCuMemberBonus(period, cuMemberBonusMap, targetMemberRangeExt.getPkMember(),
                        targetMemberRangeExt.getIncomeStatus(), targetMemberRangeExt.getPkSettleCountry(), targetMemberRangeExt.getPkRate() == null ? saOrderExt.getPkRate() : targetMemberRangeExt.getPkRate());
                int pkBonusItems = getPkBonusItems(bonusConfigDTO, targetMemberRangeExt.getPkSettleCountry(), EBonusItems.RETAIL_SAME_LEVEL_INCOME.getValue());
                CuMemberBonusRange oriMemberBonusRange = getCuMemberRetailBonusRange(saOrderExt, targetMemberRangeExt, cuMemberBonus, pkBonusItems);
                oriMemberBonusRange.setCalValue(RetailConstants.SAME_RATIO);
                oriMemberBonusRange.setCalAchieve(waresPrice);
                oriMemberBonusRange.setPretaxIncome(sameBonusIncome);
                oriMemberBonusRange.setPkRange(targetMemberRangeExt.getPkGrade());
                oriMemberBonusRange.setPkBeforeRange(sourceMemberRangeExt.getPkGrade());
                oriMemberBonusRange.setPkOrderItems(saOrderItems.getPkId());
                oriRetailRangeRemark(saOrderExt, oriMemberBonusRange, sourceMemberRangeExt, targetMemberRangeExt);
                BdBonusDeduct bdBonusDeduct = setBonusDetailDeduct(bonusConfigDTO, oriMemberBonusRange, saOrderExt.getOrderAmount(), saOrderExt.getInExchangeRate());
                if (EBonusIncomeStatus.NORMAL.getValue() == oriMemberBonusRange.getIncomeStatus()) {
                    cuMemberBonus.setRetailSameLevelIncome(ComputeUtil.computeAdd(cuMemberBonus.getRetailSameLevelIncome(), oriMemberBonusRange.getPretaxIncome()));
                    setRetailTotal(bdBonusDeduct, cuMemberBonus, oriMemberBonusRange);
                }
                memberBonusRangeList.add(oriMemberBonusRange);
            }

//            // 如果价格是209，代表是第一单激活，只有平级收益，只有V5有平级收益
//            if (beginBuyPrice.equals(BigDecimal.valueOf(209))) {
//                calGradeValue = EGrade.S_VIP.getValue();
//                if (beginGradeValue < EGrade.S_VIP.getValue()) {
//                    beginGradeValue = EGrade.S_VIP.getValue();
//                }
//            }
//            BdGrade bdGrade = gradeMap.get(calGradeValue);
//            BigDecimal buyPrice = bdGrade.getBuyPrice();
//            boolean isRange = Boolean.FALSE;
//            // 有极差或者有平级
//            if (ComputeUtil.compareGreaterThan(beginBuyPrice, buyPrice)) {
//                // 计算极差
//                CuMemberBonus cuMemberBonus = getCuMemberBonus(period, cuMemberBonusMap, targetMemberRangeExt.getPkMember(),
//                        targetMemberRangeExt.getIncomeStatus(), targetMemberRangeExt.getPkSettleCountry(), targetMemberRangeExt.getPkRate() == null ? saOrderExt.getPkRate() : targetMemberRangeExt.getPkRate());
//                int pkBonusItems = getPkBonusItems(bonusConfigDTO, targetMemberRangeExt.getPkSettleCountry(), EBonusItems.RETAIL_RANGE_INCOME.getValue());
//                CuMemberBonusRange cuMemberBonusRange = getCuMemberRetailBonusRange(saOrderExt, targetMemberRangeExt, cuMemberBonus, pkBonusItems);
//                cuMemberBonusRange.setCalValue(BigDecimal.ZERO);
//                cuMemberBonusRange.setPretaxIncome(ComputeUtil.computeDivide(ComputeUtil.computeMultiply(ComputeUtil.computeSubtract(ComputeUtil.computeSubtract(beginBuyPrice, buyPrice), calBonusIncome), saOrderItems.getWaresQuantity()), BigDecimal.ONE));
//                cuMemberBonusRange.setPkRange(targetMemberRangeExt.getPkGrade());
//                cuMemberBonusRange.setPkBeforeRange(sourceMemberRangeExt.getPkGrade());
//                cuMemberBonusRange.setPkOrderItems(saOrderItems.getPkId());
//                rangeRetailRemark(saOrderExt, cuMemberBonusRange, sourceMemberRangeExt, targetMemberRangeExt);
//                BdBonusDeduct bdBonusDeduct = setBonusDetailDeduct(bonusConfigDTO, cuMemberBonusRange, saOrderExt.getOrderAmount(), saOrderExt.getInExchangeRate());
//                if (EBonusIncomeStatus.NORMAL.getValue() == cuMemberBonusRange.getIncomeStatus()) {
//                    cuMemberBonus.setRetailRangeIncome(ComputeUtil.computeAdd(cuMemberBonus.getRetailRangeIncome(), cuMemberBonusRange.getPretaxIncome()));
//                    setRetailTotal(bdBonusDeduct, cuMemberBonus, cuMemberBonusRange);
//                }
//                memberBonusRangeList.add(cuMemberBonusRange);
//
//                beginBuyPrice = buyPrice;
//                comBuyPrice = buyPrice;
//                beginGradeValue = calGradeValue;
//                sourceMemberRangeExt = targetMemberRangeExt;
//                calBonusIncome = BigDecimal.ZERO;
//            } else {
//                isRange = Boolean.TRUE;
//                pkParent = targetMemberRangeExt.getPkMember();
//            }
//            if (saOrderExt.getOrderType().equals(EOrderType.RETAIL_CONSUME.getValue())) {
//                if (isRange) {
//                    pkParent = targetMemberRangeExt.getPkParent();
//                }
//                continue;
//            }
//            if (bdGrade.getAlgebra() > 0) {
//                Long lastPkParent = pkParent;
//                for (int j = 0; j < bdGrade.getAlgebra(); j++) {
//                    targetMemberRangeExt = memberRangeExtMap.get(lastPkParent);
//                    if (targetMemberRangeExt == null) {
//                        if (memberRangeExtMap.get(pkParent) == null) {
//                            break;
//                        }
//                        pkParent = memberRangeExtMap.get(pkParent).getPkParent();
//                        break;
//                    }
//                    calGradeValue = targetMemberRangeExt.getGradeValue();
//                    BigDecimal sameBuyPrice = gradeMap.get(calGradeValue).getBuyPrice();
//                    // 有平级
//                    if (ComputeUtil.compareGreaterThan(sameBuyPrice, comBuyPrice)) {
//                        lastPkParent = targetMemberRangeExt.getPkParent();
//                        pkParent = targetMemberRangeExt.getPkParent();
//                        j--;
//                        continue;
//                    }
//                    if (ComputeUtil.compareGreaterThan(beginBuyPrice, sameBuyPrice)) {
//                        pkParent = lastPkParent;
//                        break;
//                    }
//                    lastPkParent = targetMemberRangeExt.getPkParent();
//                    if (EAccountStatus.STOP_INCOME.getValue() == targetMemberRangeExt.getAccountStatus() ||
//                            ECategory.NORMAL.getValue() != targetMemberRangeExt.getCategory() ||
//                            targetMemberRangeExt.getEnableStatus() == EYesNo.NO.getIntValue() ||
//                            EIncomeStatus.STOP_INCOME.getValue() == targetMemberRangeExt.getIncomeStatus()) {
//                        j--;
//                        continue;
//                    }
//                    BigDecimal bonusIncome = BigDecimal.ZERO;
//                    if (j == 0) {
//                        bonusIncome = bdGrade.getFirstAlgebra();
//                    } else if (j == 1) {
//                        bonusIncome = bdGrade.getSecondAlgebra();
//                    } else if (j == 2) {
//                        bonusIncome = bdGrade.getThirdAlgebra();
//                    }
//                    if (ComputeUtil.compareEqual(beginBuyPrice, sameBuyPrice)) {
//                        CuMemberBonus cuMemberBonus = getCuMemberBonus(period, cuMemberBonusMap, targetMemberRangeExt.getPkMember(),
//                                targetMemberRangeExt.getIncomeStatus(), targetMemberRangeExt.getPkSettleCountry(), targetMemberRangeExt.getPkRate() == null ? saOrderExt.getPkRate() : targetMemberRangeExt.getPkRate());
//                        int pkBonusItems = getPkBonusItems(bonusConfigDTO, targetMemberRangeExt.getPkSettleCountry(), EBonusItems.RETAIL_SAME_LEVEL_INCOME.getValue());
//                        CuMemberBonusRange oriMemberBonusRange = getCuMemberRetailBonusRange(saOrderExt, targetMemberRangeExt, cuMemberBonus, pkBonusItems);
//                        oriMemberBonusRange.setCalValue(BigDecimal.valueOf(10));
//                        oriMemberBonusRange.setPretaxIncome(ComputeUtil.computeDivide(ComputeUtil.computeMultiply(bonusIncome, saOrderItems.getWaresQuantity()), BigDecimal.ONE));
//                        oriMemberBonusRange.setPkRange(targetMemberRangeExt.getPkGrade());
//                        oriMemberBonusRange.setPkBeforeRange(sourceMemberRangeExt.getPkGrade());
//                        oriMemberBonusRange.setPkOrderItems(saOrderItems.getPkId());
//                        oriRetailRangeRemark(saOrderExt, oriMemberBonusRange, sourceMemberRangeExt, targetMemberRangeExt);
//                        BdBonusDeduct bdBonusDeduct = setBonusDetailDeduct(bonusConfigDTO, oriMemberBonusRange, saOrderExt.getOrderAmount(), saOrderExt.getInExchangeRate());
//                        if (EBonusIncomeStatus.NORMAL.getValue() == oriMemberBonusRange.getIncomeStatus()) {
//                            cuMemberBonus.setRetailSameLevelIncome(ComputeUtil.computeAdd(cuMemberBonus.getRetailSameLevelIncome(), oriMemberBonusRange.getPretaxIncome()));
//                            setRetailTotal(bdBonusDeduct, cuMemberBonus, oriMemberBonusRange);
//                        }
//                        memberBonusRangeList.add(oriMemberBonusRange);
//                        calBonusIncome = ComputeUtil.computeAdd(calBonusIncome, bonusIncome);
//                        pkParent = lastPkParent;
//                    } else {
//                        j--;
//                    }
//                    if (j == bdGrade.getAlgebra() - 1) {
//                        beginGradeValue += 1;
//                        comBuyPrice = ComputeUtil.computeSubtract(comBuyPrice, BigDecimal.ONE);
//                        break;
//                    }
//                }
//            } else {
//                if (isRange) {
//                    pkParent = targetMemberRangeExt.getPkParent();
//                }
//            }
//            if (beginGradeValue > EGrade.S_VIP.getValue()) {
//                break;
//            }
        }
        return memberBonusRangeList;
    }

    /**
     * 计算区域奖
     *
     * @param countyRangeExtMap
     * @param saOrder
     * @param bonusConfigDTO
     * @param period
     * @param memberRangeExtMap
     * @param cuMemberBonusMap
     * @return
     */
    CuMemberBonusDetail calculateRetailAreaBonus(Map<String, CuMemberRetailRangeExt> countyRangeExtMap,
                                                 BonusConfigDTO bonusConfigDTO, Integer period, Map<Long, CuMemberRetailRangeExt> memberRangeExtMap,
                                                 Map<Long, CuMemberBonus> cuMemberBonusMap, SaOrderExt saOrder) {
        // 重消订单没有区域分红
        if (saOrder.getOrderType().equals(EOrderType.RETAIL_CONSUME.getValue())) {
            return null;
        }
        // 区域分红根据商品盒数来，如果没有盒数，直接返回为空
        if (saOrder.getBoxNum() == 0) {
            return null;
        }

        CuMemberRetailRangeExt sourceRetailRangeExt = memberRangeExtMap.get(saOrder.getPkMember());
        // 获取对应区域会员
        CuMemberRetailRangeExt cuMemberRetailRangeExt = countyRangeExtMap.get(sourceRetailRangeExt.getSystemType() + "_" + saOrder.getRecCounty());
        if (null == cuMemberRetailRangeExt) {
            return null;
        }
        // 获取区域会员结算数据
        if (memberRangeExtMap.containsKey(cuMemberRetailRangeExt.getPkMember())) {
            cuMemberRetailRangeExt = memberRangeExtMap.get(cuMemberRetailRangeExt.getPkMember());
        }

        // 非正常用户 或者 停止收益 或 未激活，不能获取区域收益
        if (ECategory.NORMAL.getValue() != cuMemberRetailRangeExt.getCategory()
                || EAccountStatus.STOP_INCOME.getValue() == cuMemberRetailRangeExt.getAccountStatus()
                || cuMemberRetailRangeExt.getEnableStatus() == EYesNo.NO.getIntValue()) {
            return null;
        }
        // 验证是否有奖金
        if (validatePkBonusItems(bonusConfigDTO, cuMemberRetailRangeExt.getPkSettleCountry(), EBonusItems.RETAIL_AREA_INCOME.getValue())) {
            return null;
        }
        // 没有盒数商品，直接返回空
        if (CollectionUtil.isEmpty(saOrder.getOrderWaresExtList())) {
            return null;
        }

        // 区域收益，商品价格 * 0.5% * 商品数量
        // 处理区域收益 -- 计算比例为 0.5%
        BigDecimal benefitIncome = BigDecimal.ZERO;
        // 计算业绩（此处作为比例）
        BigDecimal calAchieve = BigDecimal.ZERO;
        for (SaOrderWaresExt saOrderWaresExt : saOrder.getOrderWaresExtList()) {
            benefitIncome = benefitIncome.add(saOrderWaresExt.getWaresPrice().multiply(RetailConstants.SAME_RATIO)).setScale(2, BigDecimal.ROUND_HALF_UP);
            calAchieve = calAchieve.add(saOrderWaresExt.getWaresPrice());
        }
        CuMemberBonusDetail cuMemberBonusDetail = packageBenefitIncome(bonusConfigDTO, period, cuMemberBonusMap, null, RetailConstants.SAME_RATIO, benefitIncome,
                cuMemberRetailRangeExt, EBonusItems.RETAIL_AREA_INCOME.getValue(), BonusMsgConstants.RETAIL_AREA_INCOME);
        // 计算业绩以盒数做为基础
        cuMemberBonusDetail.setCalAchieve(new BigDecimal(saOrder.getBoxNum()));
        cuMemberBonusDetail.setPkOrder(saOrder.getPkId());
        String remark = String.format(BonusMsgConstants.RETAIL_AREA_INCOME, saOrder.getOrderCode(),
                memberRangeExtMap.get(saOrder.getPkMember()).getMemberCode() + memberRangeExtMap.get(saOrder.getPkMember()).getMemberName(),
                cuMemberRetailRangeExt.getMemberCode() + cuMemberRetailRangeExt.getMemberName(),
                cuMemberBonusDetail.getPretaxIncome(), cuMemberRetailRangeExt.getCountryName());
        cuMemberBonusDetail.setRemark(remark);
        return cuMemberBonusDetail;
    }

    /**
     * 计算某条订单的推荐奖金
     */
    CuMemberBonusPush calculatePushBonusOne(CuMemberRangeExt sourceMemberRangeExt, Map<Long, CuMemberRangeExt> cuMemberRangeExtMap, BonusConfigDTO bonusConfigDTO, Integer period, Map<Long, CuMemberBonus> cuMemberBonusMap,
                                            SaOrderExt saOrderExt, int algebra, BigDecimal orderAssAchieve, List<CuMemberBonusPush> cuMemberBonusPushList) {
        if (sourceMemberRangeExt == null) {
            return null;
        }
        if (algebra >= 12) {
            return null;
        }
        long pkParent = sourceMemberRangeExt.getPkParent();
        int i = 1;
        while (true) {
            CuMemberRangeExt targetMemberRangeExt = cuMemberRangeExtMap.get(pkParent);
            if (targetMemberRangeExt == null) {
                break;
            }
            pkParent = targetMemberRangeExt.getPkParent();
            if (i < algebra) {
                i++;
                continue;
            }
            // 死点没有奖金,自身没有购买没有奖金
            if (ECategory.NORMAL.getValue() != targetMemberRangeExt.getCategory() || EAccountStatus.STOP_INCOME.getValue() == targetMemberRangeExt.getAccountStatus() ||
                    targetMemberRangeExt.getBuyEffectiveNum() <= 0 || EAssessStatus.EXAMINE_PASS.getValue() != targetMemberRangeExt.getAssessStatus()) {
                // 记录烧伤记录
                targetMemberRangeExt.setIncomeStatus(EBonusIncomeStatus.FIRE_BURN.getValue());
            }
            if (validatePkBonusItems(bonusConfigDTO, targetMemberRangeExt.getPkSettleCountry(), EBonusItems.HELP_EACH_INCOME.getValue())) {
                continue;
            }
            CuMemberBonus cuMemberBonus = getCuMemberBonus(period, cuMemberBonusMap, targetMemberRangeExt.getPkMember(),
                    targetMemberRangeExt.getIncomeStatus(), targetMemberRangeExt.getPkSettleCountry(), targetMemberRangeExt.getPkRate());
            // 直推奖金明细
            int pkBonusItem = getPkBonusItems(bonusConfigDTO, targetMemberRangeExt.getPkSettleCountry(), EBonusItems.HELP_EACH_INCOME.getValue());
            CuMemberBonusPush cuMemberBonusPush = getCuMemberBonusPush(saOrderExt, targetMemberRangeExt, cuMemberBonus, pkBonusItem);
            cuMemberBonusPush.setCalType(ECalType.VALUE.getValue());
            // 前2代买的有特殊规则
            if (algebra == 1) {
                // 第一代前三单需要自购一单，从第四单开始需要自动二单，需要验证是否买了第二单
                if (targetMemberRangeExt.getFirstAgent() >= 3 && targetMemberRangeExt.getBuyEffectiveNum() <= 1) {
                    continue;
                }
                targetMemberRangeExt.setFirstAgent(targetMemberRangeExt.getFirstAgent() + 1);
                cuMemberBonusPush.setSecond(targetMemberRangeExt.getFirstAgent());
            } else if (algebra == 2) {
                if (targetMemberRangeExt.getSecondAgent() < 3 && targetMemberRangeExt.getBuyEffectiveNum() <= 1) {
                    continue;
                } else if (targetMemberRangeExt.getSecondAgent() >= 3 && targetMemberRangeExt.getBuyEffectiveNum() <= 2) {
                    continue;
                }
                targetMemberRangeExt.setSecondAgent(targetMemberRangeExt.getSecondAgent() + 1);
                cuMemberBonusPush.setSecond(targetMemberRangeExt.getSecondAgent());
            } else {
                if (targetMemberRangeExt.getBuyEffectiveNum() < algebra) {
                    continue;
                }
                cuMemberBonusPush.setSecond(-1);
            }
            cuMemberBonusPush.setRound(algebra);
            cuMemberBonusPush.setCalAchieve(orderAssAchieve);
            cuMemberBonusPush.setCalValue(BigDecimal.ONE);
            cuMemberBonusPush.setPretaxIncome(orderAssAchieve);
            BdBonusDeduct bdBonusDeduct = setBonusDetailDeduct(bonusConfigDTO, cuMemberBonusPush, saOrderExt.getOrderAmount(), saOrderExt.getInExchangeRate());
            recommendRangeRemark(saOrderExt, cuMemberBonusPush, cuMemberRangeExtMap, targetMemberRangeExt);
            if (EBonusIncomeStatus.NORMAL.getValue() == cuMemberBonusPush.getIncomeStatus()) {
                cuMemberBonus.setRepurPushIncome(ComputeUtil.computeAdd(cuMemberBonus.getRepurPushIncome(), cuMemberBonusPush.getPretaxIncome()));
                setCloudTotal(bdBonusDeduct, cuMemberBonus, cuMemberBonusPush);
            }
            cuMemberBonusPushList.add(cuMemberBonusPush);
            if (targetMemberRangeExt.getIncomeStatus() == EBonusIncomeStatus.NORMAL.getValue()) {
                return cuMemberBonusPush;
            } else {
                cuMemberBonusPush.setSecond(-1);
            }
        }
        return null;
    }

    /**
     * 计算服务中心奖
     */
    CuMemberBonusDetail calculateRangeStoreBonusOne(Map<Long, CuMemberRangeExt> cuMemberRangeExtMap, CuMemberRangeExt targetMemberRangeExt, BonusConfigDTO bonusConfigDTO, Integer period, Map<Long, CuMemberBonus> cuMemberBonusMap, SaOrderExt saOrderExt) {
        CuMemberRangeExt sourceMemberRangeExt = cuMemberRangeExtMap.get(saOrderExt.getPkMember());
        if (targetMemberRangeExt == null || ECategory.NORMAL.getValue() != targetMemberRangeExt.getCategory() || EAccountStatus.STOP_INCOME.getValue() == targetMemberRangeExt.getAccountStatus() ||
                EAssessStatus.EXAMINE_PASS.getValue() != targetMemberRangeExt.getAssessStatus()) {
            return null;
        }
        // 验证是否有奖金
        if (validatePkBonusItems(bonusConfigDTO, targetMemberRangeExt.getPkSettleCountry(), EBonusItems.STORE_INCOME.getValue())) {
            return null;
        }
        CuMemberBonus cuMemberBonus = getCuMemberBonus(period, cuMemberBonusMap, targetMemberRangeExt.getPkMember(),
                targetMemberRangeExt.getIncomeStatus(), targetMemberRangeExt.getPkSettleCountry(), targetMemberRangeExt.getPkRate());
        CuMemberBonusDetail cuMemberBonusDetail = getCuMemberBonusDetail(saOrderExt, targetMemberRangeExt.getIncomeStatus(), targetMemberRangeExt.getPkSettleCountry(), cuMemberBonus);
        BigDecimal serviceRadio = BigDecimal.valueOf(5);
        // 计算比例
        cuMemberBonusDetail.setCalValue(serviceRadio);
        cuMemberBonusDetail.setPkBonusItems(getPkBonusItems(bonusConfigDTO, targetMemberRangeExt.getPkSettleCountry(), EBonusItems.STORE_INCOME.getValue()));
        cuMemberBonusDetail.setPretaxIncome(ComputeUtil.computeBonusMultiply(cuMemberBonusDetail.getCalAchieve(), serviceRadio));
        // 收益占比
        BdBonusDeduct bdBonusDeduct = setBonusDetailDeduct(bonusConfigDTO, cuMemberBonusDetail, saOrderExt.getOrderAmount(), saOrderExt.getInExchangeRate());
        rangeServiceRemark(saOrderExt, cuMemberBonusDetail, sourceMemberRangeExt, targetMemberRangeExt);
        if (EBonusIncomeStatus.NORMAL.getValue() == cuMemberBonusDetail.getIncomeStatus()) {
            cuMemberBonus.setStoreIncome(ComputeUtil.computeAdd(cuMemberBonus.getStoreIncome(), cuMemberBonusDetail.getPretaxIncome()));
            setCloudTotal(bdBonusDeduct, cuMemberBonus, cuMemberBonusDetail);
        }
        return cuMemberBonusDetail;
    }

    /**
     * @param settleDateStr 结算日期
     */
    void calculateRetailShareBonus(String settleDateStr, BonusConfigDTO bonusConfigDTO,
                                   Integer period, BonusRecordDetailVO bonusRecordDetailVO, Map<Long, CuMemberBonus> cuMemberBonusMap) {
        Date settleDate = DateUtils.parseStringToDate(settleDateStr);
        String beforeMonthLastDate = DateUtils.beforeMonthLastDateStr(settleDate);
        // 查询上月最后一天
        Integer beforeMonthLastPeriod = getCuMemberSettlePeriodService().getCuMemberSettlePeriodByDate(beforeMonthLastDate).getPkId();
        String rangeTableName = TableNameConstants.CU_MEMBER_RETAIL_RANGE + beforeMonthLastPeriod;
        // 查询上月订单
        // 结算月第一天
        Date currentMonthFirstDate = DateUtils.beforeMonthFirstDate(settleDate);
        // 结算月下月第一天
        Date nextMonthFirstDate = DateUtils.currentMonthFirstDate(settleDate);
        List<Integer> orderType = new ArrayList<>();
        orderType.add(EOrderType.RETAIL_REGISTER.getValue());
        orderType.add(EOrderType.RETAIL_UPGRADE.getValue());
        orderType.add(EOrderType.RETAIL_REPURCHASE.getValue());
        List<SaOrder> totalMonthOrderList = new ArrayList<>();
        List<CuMemberBonusRange> memberBonusRangeList = new ArrayList<>();
        List<CuMemberBonusDetail> memberBonusDetailList = new ArrayList<>();
        String month = DateUtils.getMonth(settleDateStr);
        while (!DateUtils.compareDateEqual(currentMonthFirstDate, nextMonthFirstDate)) {
            Date endDate = DateUtils.afterDate(1, ChronoUnit.DAYS, currentMonthFirstDate);
            List<SaOrder> currentMonthOrderList = saOrderServiceApi.querySaOrderByDayForCloud(currentMonthFirstDate, endDate, orderType).getData();
            totalMonthOrderList.addAll(currentMonthOrderList);
            currentMonthFirstDate = endDate;
        }
        if (totalMonthOrderList.size() > 0) {
            Set<Long> pkMemberSet = new HashSet<>();
            totalMonthOrderList.forEach(saOrder -> pkMemberSet.add(saOrder.getPkMember()));
            List<CuMemberRetailRangeExt> cuMemberRetailRangeExtList = iCuMemberRetailRangeService.batchQueryMemberRetailRangeByMemberPk(rangeTableName, pkMemberSet);
            Map<Long, CuMemberRetailRangeExt> memberRangeExtMap = new HashMap<>();
            cuMemberRetailRangeExtList.forEach(cuMemberRetailRangeExt ->
                    memberRangeExtMap.put(cuMemberRetailRangeExt.getPkMember(), cuMemberRetailRangeExt));

            // 按照体系将订单区分
            Map<Integer, List<SaOrder>> orderMap = new HashMap<>();
            for (SaOrder saOrder : totalMonthOrderList) {
                if (memberRangeExtMap.containsKey(saOrder.getPkMember())) {
                    CuMemberRetailRangeExt cuMemberRetailRangeExt = memberRangeExtMap.get(saOrder.getPkMember());
                    if (orderMap.containsKey(cuMemberRetailRangeExt.getSystemType())) {
                        orderMap.get(cuMemberRetailRangeExt.getSystemType()).add(saOrder);
                    } else {
                        List<SaOrder> orderList = new ArrayList<>();
                        orderList.add(saOrder);
                        orderMap.put(cuMemberRetailRangeExt.getSystemType(), orderList);
                    }
                }
            }

            // 计算福利极差
            // 当月总pv，用于计算 福利分红、福利加权
            for (Integer systemType : orderMap.keySet()) {
                List<SaOrder> saOrders = orderMap.get(systemType);
                BigDecimal totalMonthConsumePv = BigDecimal.ZERO;
                for (SaOrder saOrder : saOrders) {
                    totalMonthConsumePv = ComputeUtil.computeAdd(totalMonthConsumePv, saOrder.getOrderAchieve());
                    CuMemberRetailRangeExt sourceMemberRetailRangeExt = memberRangeExtMap.get(saOrder.getPkMember());
                    BigDecimal rangeRatio = sourceMemberRetailRangeExt.getRangeRatio();
                    long pkParent = sourceMemberRetailRangeExt.getPkMember();
                    while (true) {
                        CuMemberRetailRangeExt targetMemberRangeExt = memberRangeExtMap.get(pkParent);
                        if (targetMemberRangeExt == null) {
                            break;
                        }
                        pkParent = targetMemberRangeExt.getPkParent();
                        // 只有v5 有福利奖金
                        if (EAccountStatus.STOP_INCOME.getValue() == targetMemberRangeExt.getAccountStatus() ||
                                ECategory.NORMAL.getValue() != targetMemberRangeExt.getCategory() ||
                                targetMemberRangeExt.getGradeValue() != EGrade.S_VIP.getValue() ||
                                targetMemberRangeExt.getEnableStatus() == EYesNo.NO.getIntValue() ||
                                EIncomeStatus.STOP_INCOME.getValue() == targetMemberRangeExt.getIncomeStatus()) {
                            continue;
                        }
                        BigDecimal targetRangeRatio = targetMemberRangeExt.getRangeRatio();
                        if ((targetMemberRangeExt.getPkMember().equals(saOrder.getPkMember()) && ComputeUtil.compareValue(rangeRatio)) ||
                                ComputeUtil.compareGreaterThan(targetRangeRatio, rangeRatio)) {
                            // 计算极差
                            CuMemberBonus cuMemberBonus = getCuMemberBonus(period, cuMemberBonusMap, targetMemberRangeExt.getPkMember(),
                                    targetMemberRangeExt.getIncomeStatus(), targetMemberRangeExt.getPkSettleCountry(), targetMemberRangeExt.getPkRate());
                            int pkBonusItems = getPkBonusItems(bonusConfigDTO, targetMemberRangeExt.getPkSettleCountry(), EBonusItems.RETAIL_BENEFIT_RANGE_INCOME.getValue());
                            CuMemberBonusRange cuMemberBonusRange = getCuMemberRetailBonusRange(saOrder, targetMemberRangeExt, cuMemberBonus, pkBonusItems);
                            if (targetMemberRangeExt.getPkMember().equals(saOrder.getPkMember())) {
                                cuMemberBonusRange.setCalValue(targetRangeRatio);
                            } else {
                                cuMemberBonusRange.setCalValue(ComputeUtil.computeSubtract(targetRangeRatio, rangeRatio));
                            }
                            cuMemberBonusRange.setPretaxIncome(ComputeUtil.computeBonusMultiply(saOrder.getOrderAchieve(), cuMemberBonusRange.getCalValue()));
                            cuMemberBonusRange.setPkRange(targetMemberRangeExt.getPkGrade());
                            cuMemberBonusRange.setPkBeforeRange(sourceMemberRetailRangeExt.getPkGrade());
                            cuMemberBonusRange.setPkOrderItems(0L);
                            rangeBenefitRetailRemark(saOrder, cuMemberBonusRange, sourceMemberRetailRangeExt, targetMemberRangeExt);
                            BdBonusDeduct bdBonusDeduct = setBonusDetailDeduct(bonusConfigDTO, cuMemberBonusRange, saOrder.getOrderAmount(), BigDecimal.ONE);
                            if (EBonusIncomeStatus.NORMAL.getValue() == cuMemberBonusRange.getIncomeStatus()) {
                                cuMemberBonus.setRetailBenefitRangeIncome(ComputeUtil.computeAdd(cuMemberBonus.getRetailBenefitRangeIncome(), cuMemberBonusRange.getPretaxIncome()));
                                setRetailTotal(bdBonusDeduct, cuMemberBonus, cuMemberBonusRange);
                            }
                            memberBonusRangeList.add(cuMemberBonusRange);
                            rangeRatio = targetRangeRatio;
                            sourceMemberRetailRangeExt = targetMemberRangeExt;
                        }
                    }
                }
                // CAR_AWARD_POINTS 福利平均收益  SHARE_INCOME 福利收益
                // 查询v5 等级 且奖衔>=S4的
                List<CuMemberRetailRangeExt> memberRetailRangeExtList = iCuMemberRetailRangeService.batchQueryMemberRetailRangeByAwards(rangeTableName);
                if (memberRetailRangeExtList.size() > 0) {
                    List<CuMemberRetailRangeExt> retailRangeExtList = iCuMemberRetailRangeService.batchQueryMemberRetailRangeByParent(rangeTableName, memberRetailRangeExtList);
                    Map<Long, List<CuMemberRetailRangeExt>> parentMemberRangeExtMap = new HashMap<>();
                    for (CuMemberRetailRangeExt cuMemberRetailRangeExt : retailRangeExtList) {
                        if (parentMemberRangeExtMap.containsKey(cuMemberRetailRangeExt.getPkParent())) {
                            parentMemberRangeExtMap.get(cuMemberRetailRangeExt.getPkParent()).add(cuMemberRetailRangeExt);
                        } else {
                            List<CuMemberRetailRangeExt> cuMemberRangeExtList = new ArrayList<>();
                            cuMemberRangeExtList.add(cuMemberRetailRangeExt);
                            parentMemberRangeExtMap.put(cuMemberRetailRangeExt.getPkParent(), cuMemberRangeExtList);
                        }
                    }
                    // 分类，分为4 5 6  7 8 9
                    List<CuMemberRetailRangeExt> firstAwardsRetailRangeList = new ArrayList<>();
                    BigDecimal benefitAvgRatio = BigDecimal.ZERO;
                    BigDecimal benefitShareRatio = BigDecimal.ZERO;
                    BigDecimal firstConsumePv = BigDecimal.ZERO;
                    BigDecimal secondBenefitAvgRatio = BigDecimal.ZERO;
                    BigDecimal secondBenefitShareRatio = BigDecimal.ZERO;
                    BigDecimal secondConsumePv = BigDecimal.ZERO;
                    List<CuMemberRetailRangeExt> secondAwardsRetailRangeList = new ArrayList<>();
                    for (CuMemberRetailRangeExt cuMemberRetailRangeExt : memberRetailRangeExtList) {
                        if (parentMemberRangeExtMap.containsKey(cuMemberRetailRangeExt.getPkMember())) {
                            List<CuMemberRetailRangeExt> rangeExtList = parentMemberRangeExtMap.get(cuMemberRetailRangeExt.getPkMember());
                            // 计算小区
                            BigDecimal bigConsumePv = BigDecimal.ZERO;
                            for (CuMemberRetailRangeExt memberRetailRangeExt : rangeExtList) {
                                BigDecimal monthConsumePv = ComputeUtil.computeAdd(memberRetailRangeExt.getMonthConsumePv(), memberRetailRangeExt.getTeamMonthPv());
                                if (ComputeUtil.compareGreaterThan(monthConsumePv, bigConsumePv)) {
                                    bigConsumePv = monthConsumePv;
                                }
                            }
                            cuMemberRetailRangeExt.setSmallAreaConsumePv(ComputeUtil.computeSubtract(cuMemberRetailRangeExt.getTeamMonthPv(), bigConsumePv));
                        } else {
                            cuMemberRetailRangeExt.setSmallAreaConsumePv(BigDecimal.ZERO);
                        }
                        if (cuMemberRetailRangeExt.getShareAwardsValue() >= EAwards.SENIOR_MANAGER.getValue() &&
                                cuMemberRetailRangeExt.getShareAwardsValue() <= EAwards.HIGH_CHIEF.getValue()) {
                            firstAwardsRetailRangeList.add(cuMemberRetailRangeExt);
                            benefitAvgRatio = cuMemberRetailRangeExt.getBenefitAvgRatio();
                            benefitShareRatio = cuMemberRetailRangeExt.getBenefitShareRatio();
                            firstConsumePv = ComputeUtil.computeAdd(cuMemberRetailRangeExt.getSmallAreaConsumePv(), firstConsumePv);
                        } else {
                            secondAwardsRetailRangeList.add(cuMemberRetailRangeExt);
                            secondBenefitAvgRatio = cuMemberRetailRangeExt.getBenefitAvgRatio();
                            secondBenefitShareRatio = cuMemberRetailRangeExt.getBenefitShareRatio();
                            secondConsumePv = ComputeUtil.computeAdd(cuMemberRetailRangeExt.getSmallAreaConsumePv(), secondConsumePv);
                        }
                    }
                    if (firstAwardsRetailRangeList.size() > 0) {
                        BigDecimal benefitAvgIncome = ComputeUtil.computeDivide(ComputeUtil.computeBonusMultiply(totalMonthConsumePv, benefitAvgRatio), BigDecimal.valueOf(firstAwardsRetailRangeList.size()));
                        BigDecimal benefitShareIncome = ComputeUtil.computeBonusMultiply(totalMonthConsumePv, benefitShareRatio);
                        for (CuMemberRetailRangeExt cuMemberRetailRangeExt : firstAwardsRetailRangeList) {
                            if (ECategory.NORMAL.getValue() != cuMemberRetailRangeExt.getCategory() ||
                                    EAccountStatus.STOP_INCOME.getValue() == cuMemberRetailRangeExt.getAccountStatus() ||
                                    EIncomeStatus.STOP_INCOME.getValue() == cuMemberRetailRangeExt.getIncomeStatus()) {
                                continue;
                            }
                            // 验证是否有奖金
                            if (validatePkBonusItems(bonusConfigDTO, cuMemberRetailRangeExt.getPkSettleCountry(), EBonusItems.RETAIL_BENEFIT_AVG_INCOME.getValue())) {
                                continue;
                            }
                            memberBonusDetailList.add(packageBenefitIncome(bonusConfigDTO, period, cuMemberBonusMap, month, benefitAvgRatio, benefitAvgIncome, cuMemberRetailRangeExt, EBonusItems.RETAIL_BENEFIT_AVG_INCOME.getValue(), BonusMsgConstants.RETAIL_BENEFIT_AVG_INCOME));
                            BigDecimal bonusIncome = ComputeUtil.computeDivide(ComputeUtil.computeMultiply(benefitShareIncome, cuMemberRetailRangeExt.getSmallAreaConsumePv()), firstConsumePv);
                            CuMemberBonusDetail cuMemberBonusDetail = packageBenefitIncome(bonusConfigDTO, period, cuMemberBonusMap, month, benefitShareRatio, bonusIncome, cuMemberRetailRangeExt, EBonusItems.RETAIL_BENEFIT_INCOME.getValue(), BonusMsgConstants.RETAIL_BENEFIT_INCOME);
                            memberBonusDetailList.add(cuMemberBonusDetail);
                        }
                    }
                    if (secondAwardsRetailRangeList.size() > 0) {
                        BigDecimal benefitAvgIncome = ComputeUtil.computeDivide(ComputeUtil.computeBonusMultiply(totalMonthConsumePv, secondBenefitAvgRatio), BigDecimal.valueOf(secondAwardsRetailRangeList.size()));
                        BigDecimal benefitShareIncome = ComputeUtil.computeBonusMultiply(totalMonthConsumePv, secondBenefitShareRatio);
                        for (CuMemberRetailRangeExt cuMemberRetailRangeExt : secondAwardsRetailRangeList) {
                            if (ECategory.NORMAL.getValue() != cuMemberRetailRangeExt.getCategory() ||
                                    EAccountStatus.STOP_INCOME.getValue() == cuMemberRetailRangeExt.getAccountStatus() ||
                                    EIncomeStatus.STOP_INCOME.getValue() == cuMemberRetailRangeExt.getIncomeStatus()) {
                                continue;
                            }
                            // 验证是否有奖金
                            if (validatePkBonusItems(bonusConfigDTO, cuMemberRetailRangeExt.getPkSettleCountry(), EBonusItems.RETAIL_BENEFIT_AVG_INCOME.getValue())) {
                                continue;
                            }
                            memberBonusDetailList.add(packageBenefitIncome(bonusConfigDTO, period, cuMemberBonusMap, month, secondBenefitAvgRatio, benefitAvgIncome, cuMemberRetailRangeExt, EBonusItems.RETAIL_BENEFIT_AVG_INCOME.getValue(), BonusMsgConstants.RETAIL_BENEFIT_AVG_INCOME));
                            BigDecimal bonusIncome = ComputeUtil.computeDivide(ComputeUtil.computeMultiply(benefitShareIncome, cuMemberRetailRangeExt.getSmallAreaConsumePv()), secondConsumePv);
                            CuMemberBonusDetail cuMemberBonusDetail = packageBenefitIncome(bonusConfigDTO, period, cuMemberBonusMap, month, secondBenefitShareRatio, bonusIncome, cuMemberRetailRangeExt, EBonusItems.RETAIL_BENEFIT_INCOME.getValue(), BonusMsgConstants.RETAIL_BENEFIT_INCOME);
                            memberBonusDetailList.add(cuMemberBonusDetail);
                        }
                    }
                }
            }
        }
        if (memberBonusDetailList.size() > 0) {
            if (bonusRecordDetailVO.getCuMemberBonusDetailList() == null) {
                bonusRecordDetailVO.setCuMemberBonusDetailList(memberBonusDetailList);
            } else {
                bonusRecordDetailVO.getCuMemberBonusDetailList().addAll(memberBonusDetailList);
            }
        }
        if (memberBonusRangeList.size() > 0) {
            if (bonusRecordDetailVO.getCuMemberBonusRangeList() == null) {
                bonusRecordDetailVO.setCuMemberBonusRangeList(memberBonusRangeList);
            } else {
                bonusRecordDetailVO.getCuMemberBonusRangeList().addAll(memberBonusRangeList);
            }
        }
    }

    private CuMemberBonusDetail packageBenefitIncome(BonusConfigDTO bonusConfigDTO, Integer period, Map<Long, CuMemberBonus> cuMemberBonusMap, String month,
                                                     BigDecimal benefitAvgRatio, BigDecimal benefitAvgIncome, CuMemberRetailRangeExt cuMemberRetailRangeExt, Integer bonusItemsValue, String msg) {
        CuMemberBonus cuMemberBonus = getCuMemberBonus(period, cuMemberBonusMap, cuMemberRetailRangeExt.getPkMember(),
                cuMemberRetailRangeExt.getIncomeStatus(), cuMemberRetailRangeExt.getPkSettleCountry(), cuMemberRetailRangeExt.getPkRate());
        SaOrder saOrderExt = SaOrder.builder().pkId(0L).orderAchieve(BigDecimal.ZERO).build();
        CuMemberBonusDetail cuMemberBonusDetail = getCuMemberBonusDetail(saOrderExt, cuMemberRetailRangeExt.getIncomeStatus(), cuMemberRetailRangeExt.getPkSettleCountry(), cuMemberBonus);
        // 计算比例
        cuMemberBonusDetail.setCalValue(benefitAvgRatio);
        cuMemberBonusDetail.setPretaxIncome(benefitAvgIncome);
        cuMemberBonusDetail.setPkBonusItems(getPkBonusItems(bonusConfigDTO, cuMemberRetailRangeExt.getPkSettleCountry(), bonusItemsValue));
        // 收益占比
        BdBonusDeduct bdBonusDeduct = setBonusDetailDeduct(bonusConfigDTO, cuMemberBonusDetail, BigDecimal.ZERO, BigDecimal.ONE);
        if (bonusItemsValue != EBonusItems.RETAIL_AREA_INCOME.getValue()) {
            String remark = String.format(msg, cuMemberBonusDetail.getPretaxIncome(), month);
            cuMemberBonusDetail.setRemark(remark);
        }
        if (EBonusIncomeStatus.NORMAL.getValue() == cuMemberBonusDetail.getIncomeStatus()) {
            if (bonusItemsValue == EBonusItems.RETAIL_AREA_INCOME.getValue()) {
                cuMemberBonus.setRetailAreaIncome(ComputeUtil.computeAdd(cuMemberBonus.getRetailAreaIncome(), cuMemberBonusDetail.getPretaxIncome()));
            } else if (bonusItemsValue == EBonusItems.RETAIL_BENEFIT_AVG_INCOME.getValue()) {
                cuMemberBonus.setRetailBenefitAvgIncome(ComputeUtil.computeAdd(cuMemberBonus.getRetailBenefitAvgIncome(), cuMemberBonusDetail.getPretaxIncome()));
            } else {
                cuMemberBonus.setRetailBenefitIncome(ComputeUtil.computeAdd(cuMemberBonus.getRetailBenefitIncome(), cuMemberBonusDetail.getPretaxIncome()));
            }
            setRetailTotal(bdBonusDeduct, cuMemberBonus, cuMemberBonusDetail);
        }
        return cuMemberBonusDetail;
    }

    CuMemberBonusPush getCuMemberBonusPush(SaOrderExt saOrderExt, CuMemberRangeExt cuMemberRangeExt, CuMemberBonus cuMemberBonus, Integer pkBonusItems) {
        CuMemberBonusPush cuMemberBonusPush = CuMemberBonusPush.builder()
                .pkOrder(saOrderExt.getPkId())
                .pkBonus(cuMemberBonus.getPkId())
                .pkBonusItems(pkBonusItems)
                // 正常还是烧伤
                .incomeStatus(cuMemberRangeExt.getIncomeStatus())
                .calType(ECalType.RATIO.getValue())
                .pretaxIncome(BigDecimal.ZERO)
                .incomeTax(BigDecimal.ZERO)
                .realIncome(BigDecimal.ZERO)
                .incomeRatio(BigDecimal.ZERO)
                .incomeDialRatio(BigDecimal.ZERO)
                .orderDialRatio(BigDecimal.ZERO)
                .round(-1)
                .second(-1)
                .build();
        cuMemberBonusPush.setPkCountry(cuMemberRangeExt.getPkSettleCountry());
        cuMemberBonusPush.setPkCreator(MagicNumberConstants.PK_ADMIN);
        return cuMemberBonusPush;
    }

    protected CuMemberBonusCoach getCuMemberBonusCoach(BonusConfigDTO bonusConfigDTO, SaOrderExt saOrderExt,
                                                       int i, CuMemberRangeExt targetMemberRangeExt) {
        CuMemberBonusCoach cuMemberBonusCoach = CuMemberBonusCoach.builder()
                .pkBonus(targetMemberRangeExt.getPkMember())
                .pkOrder(saOrderExt.getPkId())
                .pkBonusItems(getPkBonusItems(bonusConfigDTO, targetMemberRangeExt.getPkSettleCountry(), EBonusItems.CLOUD_AGENT_DIRECT_PUSH.getValue()))
                .calType(ECalType.RATIO.getValue())
                .incomeStatus(targetMemberRangeExt.getIncomeStatus())
                .calAchieve(saOrderExt.getOrderAchieve())
                .currentGeneration(i)
                // 计算比例
                .calValue(BigDecimal.ZERO)
                .incomeTax(BigDecimal.ZERO)
                .realIncome(BigDecimal.ZERO)
                .incomeRatio(BigDecimal.ZERO)
                .incomeDialRatio(BigDecimal.ZERO)
                .orderDialRatio(BigDecimal.ZERO)
                .pretaxIncome(BigDecimal.ZERO)
                .coachNoCapping(BigDecimal.ZERO)
                .coachCapping(BigDecimal.ZERO)
                .coachNormalHalf(BigDecimal.ZERO)
                .coachNormalReal(BigDecimal.ZERO)
                .build();
        cuMemberBonusCoach.setPkCountry(targetMemberRangeExt.getPkSettleCountry());
        cuMemberBonusCoach.setPkCreator(MagicNumberConstants.PK_ADMIN);
        return cuMemberBonusCoach;
    }

    private CuMemberBonusRange getCuMemberBonusRange(SaOrderExt saOrderExt, CuMemberRangeExt targetMemberRangeExt,
                                                     CuMemberBonus cuMemberBonus, Integer pkBonusItems) {
        CuMemberBonusRange cuMemberBonusRange = CuMemberBonusRange.builder()
                .pkOrder(saOrderExt.getPkId())
                .pkBonus(cuMemberBonus.getPkId())
                .pkBonusItems(pkBonusItems)
                // 正常还是烧伤
                .incomeStatus(targetMemberRangeExt.getIncomeStatus())
                .calType(ECalType.VALUE.getValue())
                .calAchieve(saOrderExt.getOrderAchieve())
                .calValue(BigDecimal.ZERO)
                .incomeRatio(BigDecimal.ZERO)
                .incomeDialRatio(BigDecimal.ZERO)
                .orderDialRatio(BigDecimal.ZERO)
                .build();
        cuMemberBonusRange.setPkCountry(targetMemberRangeExt.getPkSettleCountry());
        cuMemberBonusRange.setPkCreator(MagicNumberConstants.PK_ADMIN);
        return cuMemberBonusRange;
    }

    private CuMemberBonusRange getCuMemberRetailBonusRange(SaOrder saOrderExt, CuMemberRetailRangeExt targetMemberRangeExt,
                                                           CuMemberBonus cuMemberBonus, Integer pkBonusItems) {
        CuMemberBonusRange cuMemberBonusRange = CuMemberBonusRange.builder()
                .incomeStatus(targetMemberRangeExt.getIncomeStatus())
                .pkOrder(saOrderExt.getPkId())
                .pkBonusItems(pkBonusItems)
                .pkBonus(cuMemberBonus.getPkId())
                // 正常还是烧伤
                .calAchieve(saOrderExt.getOrderAchieve())
                .calType(ECalType.VALUE.getValue())
                .calValue(BigDecimal.ZERO)
                .incomeRatio(BigDecimal.ZERO)
                .incomeDialRatio(BigDecimal.ZERO)
                .orderDialRatio(BigDecimal.ZERO)
                .build();
        cuMemberBonusRange.setPkCountry(targetMemberRangeExt.getPkSettleCountry());
        cuMemberBonusRange.setPkCreator(MagicNumberConstants.PK_ADMIN);
        return cuMemberBonusRange;
    }

    /**
     * 记录需要修改的会员结算表数据, 安置的
     *
     * @param memberRangeMap 查询出来的结算数据
     */
    private Map<Long, CuMemberRangeExt> getMemberSettle(Map<Long, List<CuMemberRangeExt>> memberRangeMap) {
        Map<Long, CuMemberRangeExt> memberRangeExtMap = new HashMap<>();
        memberRangeMap.forEach((key, memberRangeExtList) -> {
            memberRangeExtList.forEach(cuMemberSettleExt -> {
                if (!memberRangeExtMap.containsKey(cuMemberSettleExt.getPkMember())) {
                    memberRangeExtMap.put(cuMemberSettleExt.getPkMember(), cuMemberSettleExt);
                } else {
                    CuMemberRangeExt cuMemberRangeExt = memberRangeExtMap.get(cuMemberSettleExt.getPkMember());
                    if (cuMemberRangeExt.getNewTeamPv() == null) {
                        cuMemberRangeExt.setNewTeamPv(BigDecimal.ZERO);
                    }
                }
            });
        });
        return memberRangeExtMap;
    }

    private CuMemberAwards getCuMemberAwards(CuMemberRangeExt sourceRangeExt, Integer period, SaOrderExt saOrderExt, BdRangeAwards bdRangeAwards) {
        CuMemberAwards cuMemberAwards = CuMemberAwards.builder()
                .pkMember(sourceRangeExt.getPkMember())
                .period(period)
                .upType(EUpgradeType.AUTO_UPGRADE.getValue())
                // 原等级
                .oldLevel(sourceRangeExt.getPkRangeAwards())
                .newLevel(bdRangeAwards.getPkId())
                // 默认不免考
                .purchaseStatus(EYesNo.NO.getIntValue())
                .pkOrder(saOrderExt.getPkId())
                .systemType(1)
                .build();
        cuMemberAwards.setPkCreator(MagicNumberConstants.PK_ADMIN);
        cuMemberAwards.setPkCountry(saOrderExt.getPkCountry());
        cuMemberAwards.setCreationTime(saOrderExt.getPayTime());
        return cuMemberAwards;
    }

    private CuMemberAwards getCuMemberRetailAwards(CuMemberRetailRangeExt sourceRangeExt, Integer period,
                                                   SaOrderExt saOrderExt, BdAwards bdRangeAwards, Integer awardType) {
        CuMemberAwards cuMemberAwards = CuMemberAwards.builder()
                .pkMember(sourceRangeExt.getPkMember())
                .period(period)
                .upType(EUpgradeType.AUTO_UPGRADE.getValue())
                .awardType(awardType)
                // 原等级
                .oldLevel(sourceRangeExt.getPkAwards())
                .newLevel(bdRangeAwards.getPkId())
                // 默认不免考
                .purchaseStatus(EYesNo.NO.getIntValue())
                .pkOrder(saOrderExt.getPkId())
                .systemType(2)
                .build();
        cuMemberAwards.setPkCreator(MagicNumberConstants.PK_ADMIN);
        cuMemberAwards.setPkCountry(saOrderExt.getPkCountry());
        cuMemberAwards.setCreationTime(saOrderExt.getPayTime());
        return cuMemberAwards;
    }

    /**
     * 奖金明细
     *
     * @param saOrderExt    订单
     * @param cuMemberBonus 奖金主表
     */
    private CuMemberBonusDetail getCuMemberBonusDetail(SaOrder saOrderExt, Integer incomeStatus, Integer pkCountry, CuMemberBonus cuMemberBonus) {
        CuMemberBonusDetail cuMemberBonusDetail = CuMemberBonusDetail.builder()
                .pkOrder(saOrderExt.getPkId())
                .calType(ECalType.RATIO.getValue())
                .incomeStatus(incomeStatus)
                .calAchieve(saOrderExt.getOrderAchieve())
                .pkBonus(cuMemberBonus.getPkId())
                .pretaxIncome(BigDecimal.ZERO)
                .incomeTax(BigDecimal.ZERO)
                .realIncome(BigDecimal.ZERO)
                .incomeRatio(BigDecimal.ZERO)
                .incomeDialRatio(BigDecimal.ZERO)
                .orderDialRatio(BigDecimal.ZERO)
                .build();
        cuMemberBonusDetail.setPkCountry(pkCountry);
        cuMemberBonusDetail.setPkCreator(MagicNumberConstants.PK_ADMIN);
        return cuMemberBonusDetail;
    }

    /**
     * 获取手动激活map
     *
     * @param settleStartDate
     * @return
     */
    private Map<Long, Date> getActivateMap(Date settleStartDate) {
        // 当期的手动激活的记录列表
        List<CuMemberServiceLog> activateList = iCuMemberServiceLogServiceApi.listActivateLog(settleStartDate).getData();
        return activateList.stream()
                .collect(Collectors.groupingBy(
                        CuMemberServiceLog::getPkMember,
                        Collectors.collectingAndThen(
                                Collectors.minBy(Comparator.comparing(CuMemberServiceLog::getCreationTime)),
                                optional -> optional.get().getCreationTime()
                        )
                ));
    }
}
