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

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.hzs.bonus.achieve.service.ICuMemberRetailRangeService;
import com.hzs.bonus.base.service.IBdVertexBonusService;
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.config.BdConfig;
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.CuMemberSettlePeriod;
import com.hzs.common.domain.member.achieve.ext.CuMemberRetailRangeExt;
import com.hzs.common.domain.member.bonus.*;
import com.hzs.common.domain.member.detail.*;
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.sale.wares.ext.WaresRangeTmp;
import com.hzs.common.domain.system.config.BdAwards;
import com.hzs.common.domain.system.config.BdGrade;
import com.hzs.member.detail.ICuMemberServiceLogServiceApi;
import com.hzs.system.config.dto.BonusConfigDTO;
import lombok.extern.slf4j.Slf4j;
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.math.RoundingMode;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 计算新零售收益
 */
@Slf4j
@Component
public class BonusSettleRangeHandle extends BonusSettleHandle {

    @Autowired
    private ICuMemberRetailRangeService iCuMemberRetailRangeService;
    @Autowired
    private ICuMemberAwardsService iCuMemberAwardsService;
    @Autowired
    private ICuMemberGradeService iCuMemberGradeService;
    @Autowired
    private ICuMemberService iCuMemberService;
    @Autowired
    private IBonusOrderService iBonusOrderService;
    @Autowired
    private IBdVertexBonusService iBdVertexBonusService;

    @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().compareTo(BigDecimal.ZERO) > 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());
        // 查询体系奖项配置
        Map<Long, List<Integer>> vertexBonusMap = iBdVertexBonusService.queryVertexBonus();

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

        // 订单业绩
        BigDecimal orderAchieve = saOrderExt.getOrderAchieve();
        // 注册、升级、复购、重消，盒数、业绩算个人累计数据（盒数、业绩）
        sourceMemberRangeExt.setNewBoxNum(sourceMemberRangeExt.getNewBoxNum().add(boxNum));
        sourceMemberRangeExt.setConsumeBoxNum(sourceMemberRangeExt.getConsumeBoxNum().add(boxNum));
        sourceMemberRangeExt.setMonthBoxNum(sourceMemberRangeExt.getMonthBoxNum().add(boxNum));
        sourceMemberRangeExt.setNewConsumePv(ComputeUtil.computeAdd(sourceMemberRangeExt.getNewConsumePv(), orderAchieve));
        sourceMemberRangeExt.setConsumePv(ComputeUtil.computeAdd(sourceMemberRangeExt.getConsumePv(), orderAchieve));
        sourceMemberRangeExt.setMonthConsumePv(ComputeUtil.computeAdd(sourceMemberRangeExt.getMonthConsumePv(), orderAchieve));
        // 累计盒数、业绩，不管激活不激活都处理，兼容不激活判断显示有问题
        sourceMemberRangeExt.setAllNewBoxNum(sourceMemberRangeExt.getAllNewBoxNum().add(boxNum));
        sourceMemberRangeExt.setAllNewConsumePv(sourceMemberRangeExt.getAllNewConsumePv().add(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())
                        && EDelFlag.UN_DELETE.getValue() == saOrderItems.getDelFlag()) {
                    // 指定盒数商品
                    // 计算直推级差收益 + 平级收益
                    cuMemberBonusRangeList.addAll(calculateRetailRangeBonus(memberRangeExtMap, cuMemberBonusMap, gradeMap, bonusConfigDTO, currentPeriod, saOrderItems, saOrderExt));
                }
            }
        }

        // 区域处理
        List<CuMemberRetailRangeExt> countyRangeExtList = iCuMemberRetailRangeService.batchQueryMemberRetailSecondRangeByCounty(rangeTableName, secondRangeTableName, saOrderExt.getRecCounty());
        // 区域会员map（key:区域分组ID + 区ID ,value: 区域会员结算数据）
        Map<String, CuMemberRetailRangeExt> countyRangeExtMap = new HashMap<>();
        countyRangeExtList.forEach(cuMemberRetailRangeExt ->
                countyRangeExtMap.put(cuMemberRetailRangeExt.getRegionVertexPkId() + "_" + cuMemberRetailRangeExt.getRegionAddress(), cuMemberRetailRangeExt));
        // 计算区域奖
        CuMemberBonusDetail cuMemberBonusDetail = calculateRetailAreaBonus(countyRangeExtMap, bonusConfigDTO, currentPeriod, memberRangeExtMap, cuMemberBonusMap, saOrderExt);
        if (cuMemberBonusDetail != null) {
            cuMemberBonusDetailList.add(cuMemberBonusDetail);
        }

        // TODO 2025.07.04 部分体系单独奖项处理
        if (EOrderType.RETAIL_REPURCHASE.getValue() == saOrderExt.getOrderType()) {
            // 复购订单级差数据map(key:订单ID，value:订单明细+级差)
            Map<Long, List<SaOrderItemsExt>> rangeOrderMap = iBonusOrderService.getWaresRange(Collections.singletonList(saOrderExt));
            // 复购订单
            cuMemberBonusRangeList.addAll(this.calculateRepurchaseRangeBonus(saOrderExt, memberRangeExtMap, vertexBonusMap, rangeOrderMap,
                    bonusConfigDTO, currentPeriod, cuMemberBonusMap));
        }

        // 回退会员等级
        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;
        // 是否当天
        boolean isSecond = DateUtils.isSameDay(saOrderExt.getPayTime(), DateUtils.currentDate());

        if (isSecond) {
            // 当天撤单
            // 实时网体查询血缘伞上会员，更新秒结表等级、奖衔
            iCuMemberRetailRangeService.mergeMemberRetailGradeByMember(secondRangeTableName, saOrderExt.getPkMember(), EYesNo.YES.getIntValue());
            // 恢复秒结表奖衔
            iCuMemberAwardsService.mergeCuMemberBackAwards(secondRangeTableName, saOrderExt.getPkMember(), currentPeriod, EYesNo.YES.getIntValue());
            // 查询 昨天日结 + 今天秒结 血缘伞上+直推
            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(), EYesNo.NO.getIntValue());
            // 恢复日结表奖衔
            iCuMemberAwardsService.mergeCuMemberBackAwards(rangeTableName, saOrderExt.getPkMember(), beforePeriod, EYesNo.NO.getIntValue());
            // 查询 订单下单日结 血缘上会员结算数据
            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> retailGradeList = bonusConfigDTO.getRetaiGradeList();
        // 等级
        for (BdGrade bdGrade : retailGradeList) {
            if (bdGrade.getBoxTotal().compareTo(BigDecimal.ZERO) > 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());
        // 先算等级 注册、升级计算等级
        BigDecimal boxNum = saOrderExt.getBoxNum();
//        BigDecimal boxNum = BigDecimal.ZERO;
//        for (SaOrderWaresExt saOrderItems : saOrderExt.getOrderWaresExtList()) {
//            if (RetailConstants.ALL_BOX_WARES_LIST.contains(saOrderItems.getWaresCode())) {
//                boxNum = boxNum.add(saOrderItems.getWaresBoxNum().multiply(new BigDecimal(saOrderItems.getWaresQuantity())));
//            }
//        }
//        saOrderExt.setBoxNum(boxNum);

        // 订单业绩
        BigDecimal orderAchieve = saOrderExt.getOrderAchieve();
        // 复购、重消，盒数、业绩算个人累计数据（盒数、业绩）
        sourceMemberRangeExt.setNewBoxNum(sourceMemberRangeExt.getNewBoxNum().subtract(boxNum));
        sourceMemberRangeExt.setConsumeBoxNum(sourceMemberRangeExt.getConsumeBoxNum().subtract(boxNum));
        sourceMemberRangeExt.setMonthBoxNum(sourceMemberRangeExt.getMonthBoxNum().subtract(boxNum));
        sourceMemberRangeExt.setNewConsumePv(ComputeUtil.computeSubtract(sourceMemberRangeExt.getNewConsumePv(), orderAchieve));
        sourceMemberRangeExt.setConsumePv(ComputeUtil.computeSubtract(sourceMemberRangeExt.getConsumePv(), orderAchieve));
        sourceMemberRangeExt.setMonthConsumePv(ComputeUtil.computeSubtract(sourceMemberRangeExt.getMonthConsumePv(), orderAchieve));
        if (isSecond) {
            // 当天
            // 累计盒数、业绩，不管激活不激活都处理，兼容不激活判断显示有问题
            sourceMemberRangeExt.setAllNewBoxNum(sourceMemberRangeExt.getAllNewBoxNum().subtract(boxNum));
            sourceMemberRangeExt.setAllNewConsumePv(sourceMemberRangeExt.getAllNewConsumePv().subtract(orderAchieve));
        }

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

        // 查询期间的等级（来源 cu_member_grade）
        List<CuMemberGrade> memberGradeList = iCuMemberGradeService.queryCuMemberGrade(cuMemberRetailRangeExtList, currentPeriod);
        // 查询最大的手动等级（来源 cu_member_grade）
        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() < 11) {
                        // 如果是合伙人，奖衔肯定得有，不能置为无
                        cuMemberRetailRangeExt.setPkAwards(11);
                    }
                }
            }
        }
        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) {
                // 删除等级（cu_member_grade）
                iCuMemberGradeService.deleteCuMemberGrade(cuMemberGradeList, currentPeriod);
                // 批量更新会员等级（更新 cu_member）
                iCuMemberService.updateCuMemberMinGradeByList(cuMemberGradeList, currentPeriod);
            }
        }
        // 当期的所有奖衔升级记录
        List<CuMemberAwards> memberAwardsList = iCuMemberAwardsService.queryCuMemberAwards(cuMemberRetailRangeExtList, currentPeriod);
        if (memberAwardsList.size() > 0) {
            // 当月奖衔升级记录
            List<CuMemberAwards> pkAwardsList = memberAwardsList.stream().filter(tmpData -> tmpData.getAwardType() == EAwardsType.RANGE_TYPE.getValue()).collect(Collectors.toList());
            // 分红奖衔升级记录
            List<CuMemberAwards> pkShareAwardsList = memberAwardsList.stream().filter(tmpData -> tmpData.getAwardType() == EAwardsType.SHARE_TYPE.getValue()).collect(Collectors.toList());

            List<CuMemberAwards> cuMemberAwardsList = new ArrayList<>();
            if (CollectionUtil.isNotEmpty(pkAwardsList)) {
                for (CuMemberAwards cuMemberAwards : pkAwardsList) {
                    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() < 11) {
                            // 如果是合伙人，奖衔肯定得有，不能置为无
                            cuMemberRetailRangeExt.setPkAwards(11);
                            continue;
                        }
                        cuMemberAwards.setNewLevel(cuMemberAwards.getOldLevel());
                        cuMemberAwardsList.add(cuMemberAwards);
                    }
                }
            }
            if (CollectionUtil.isNotEmpty(pkShareAwardsList)) {
                for (CuMemberAwards cuMemberAwards : pkShareAwardsList) {
                    String key = cuMemberAwards.getPkMember() + "_" + cuMemberAwards.getNewLevel();
                    if (!cuMemberShareAwardsMap.containsKey(key)) {
                        CuMemberRetailRangeExt cuMemberRetailRangeExt = memberRangeExtMap.get(cuMemberAwards.getPkMember());
                        if (cuMemberAwards.getOldLevel() < cuMemberRetailRangeExt.getPkShareAwards()) {
                            cuMemberRetailRangeExt.setPkShareAwards(cuMemberAwards.getOldLevel());
                        }
                        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, Map<Long, List<Integer>> vertexBonusMap) {
        // 结算期间日期
        Date settleStartDate = DateUtils.parseStringToDate(settleDate);
        // 结算期间日期后一天
        Date settleEndDate = DateUtils.afterDate(1, ChronoUnit.DAYS, settleStartDate);

        // 所有有效订单列表
        List<SaOrderExt> retailOrderList = new ArrayList<>();
        // 复购订单列表
        List<SaOrderExt> repurchaseOrderList = new ArrayList<>();
        // 新零售订单
        List<SaOrderExt> orderList = iBonusOrderService.queryRetailSaOrderByDay(settleStartDate, settleEndDate, null);
        for (SaOrderExt saOrderExt : orderList) {
            if (saOrderExt.getDelFlag() == EYesNo.YES.getIntValue()) {
                retailOrderList.add(saOrderExt);
                if (EOrderType.RETAIL_REPURCHASE.getValue() == saOrderExt.getOrderType()) {
                    // 复购订单
                    repurchaseOrderList.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(key:订单ID，value:订单明细+级差)
            Map<Long, List<SaOrderItemsExt>> rangeOrderMap = new HashMap<>();
            if (CollectionUtil.isNotEmpty(repurchaseOrderList)) {
                rangeOrderMap = iBonusOrderService.getWaresRange(repurchaseOrderList);
            }

            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().compareTo(BigDecimal.ZERO) > 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));

            // 会员转map
            for (CuMemberRetailRangeExt cuMemberRetailRangeExt : memberRetailRangeExtList) {
                if (!memberRangeExtMap.containsKey(cuMemberRetailRangeExt.getPkMember())) {
                    memberRangeExtMap.put(cuMemberRetailRangeExt.getPkMember(), cuMemberRetailRangeExt);
                }
            }

            // 区域处理
            List<CuMemberRetailRangeExt> countyRangeExtList = iCuMemberRetailRangeService.batchQueryMemberRetailRangeByCounty(rangeTableName);
            // 区域会员map（key:区域分组ID + 区ID ,value: 区域会员结算数据）
            Map<String, CuMemberRetailRangeExt> countyRangeExtMap = new HashMap<>();
            countyRangeExtList.forEach(cuMemberRetailRangeExt ->
                    countyRangeExtMap.put(cuMemberRetailRangeExt.getRegionVertexPkId() + "_" + 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());

                // 订单指定产品盒数（计算等级使用）
                BigDecimal boxNum = saOrderExt.getBoxNum();
//                BigDecimal boxNum = BigDecimal.ZERO;
//                for (SaOrderWaresExt saOrderItems : saOrderExt.getOrderWaresExtList()) {
//                    if (RetailConstants.ALL_BOX_WARES_LIST.contains(saOrderItems.getWaresCode())) {
//                        boxNum = boxNum.add(saOrderItems.getWaresBoxNum().multiply(new BigDecimal(saOrderItems.getWaresQuantity())));
//                    }
//                }

                // 个人累计消费pv
                BigDecimal orderAchieve = saOrderExt.getOrderAchieve();
                // 复购、重消，盒数、业绩算个人累计数据（盒数、业绩）
                sourceMemberRangeExt.setNewBoxNum(sourceMemberRangeExt.getNewBoxNum().add(boxNum));
                sourceMemberRangeExt.setConsumeBoxNum(sourceMemberRangeExt.getConsumeBoxNum().add(boxNum));
                sourceMemberRangeExt.setMonthBoxNum(sourceMemberRangeExt.getMonthBoxNum().add(boxNum));
                sourceMemberRangeExt.setNewConsumePv(ComputeUtil.computeAdd(sourceMemberRangeExt.getNewConsumePv(), orderAchieve));
                sourceMemberRangeExt.setConsumePv(ComputeUtil.computeAdd(sourceMemberRangeExt.getConsumePv(), orderAchieve));
                sourceMemberRangeExt.setMonthConsumePv(ComputeUtil.computeAdd(sourceMemberRangeExt.getMonthConsumePv(), 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.compareTo(BigDecimal.ZERO) > 0
                ) {
                    // 注册或升级订单并且存在盒数产品，才有 直推级差收益 和 平级收益
                    for (SaOrderWaresExt saOrderItems : saOrderExt.getOrderWaresExtList()) {
                        if (RetailConstants.ALL_BOX_WARES_LIST.contains(saOrderItems.getWaresCode())
                                && EDelFlag.UN_DELETE.getValue() == saOrderItems.getDelFlag()) {
                            // 盒数商品 计算 直推级差 + 平级收益
                            cuMemberBonusRangeList.addAll(calculateRetailRangeBonus(memberRangeExtMap, cuMemberBonusMap, gradeMap, bonusConfigDTO, period, saOrderItems, saOrderExt));
                        }
                    }

                    // 订单存在升级记录
                    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);
                }

                // TODO 2025.07.04 部分体系单独奖项处理
                if (EOrderType.RETAIL_REPURCHASE.getValue() == saOrderExt.getOrderType()) {
                    // 复购订单
                    cuMemberBonusRangeList.addAll(this.calculateRepurchaseRangeBonus(saOrderExt, memberRangeExtMap, vertexBonusMap, rangeOrderMap,
                            bonusConfigDTO, period, cuMemberBonusMap));
                }
            }

            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(period);
            }
            if (cuMemberGradeList.size() > 0) {
                // 批量插入会员等级记录
                iCuMemberGradeService.insertCuMemberGrade(cuMemberGradeList);
                // 更新会员表（cu_member）等级数据（来源 cu_member_grade)
                iCuMemberService.updateCuMemberGradeByPeriod(period);
                // 更新会员表（cu_member）等级数据（来源 cu_member_level)
                iCuMemberService.updateCuMemberLevel(settleStartDate, settleEndDate);
            }
            // 更新网体
            iCuMemberRetailRangeService.updateCuMemberRetailRange(rangeTableName, memberRangeExtMap);
        }
    }

    /**
     * 计算团队等级、奖衔 -- 秒结、日结
     */
    public List<CuMemberAwards> calculateRetailRangeGradeAwards(Integer period, Map<Long, CuMemberRetailRangeExt> memberRangeExtMap, String rangeTableName, SaOrderExt saOrderExt,
                                                                Map<Integer, BdGrade> retailTeamGradeMap, Map<Integer, BdAwards> retailAwardsMap, String secondRangeTableName,
                                                                BigDecimal 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());
            }

            // 累计盒数、业绩，不管激活不激活都处理，兼容不激活判断显示有问题
            targetMemberRangeExt.setAllTeamNewBoxNum(targetMemberRangeExt.getAllTeamNewBoxNum().add(boxNum));
            targetMemberRangeExt.setAllTeamBoxNum(targetMemberRangeExt.getAllTeamBoxNum().add(boxNum));
            targetMemberRangeExt.setAllTeamMonthBoxNum(targetMemberRangeExt.getAllTeamMonthBoxNum().add(boxNum));
            targetMemberRangeExt.setAllTeamNewPv(targetMemberRangeExt.getAllTeamNewPv().add(orderAchieve));
            targetMemberRangeExt.setAllTeamConsumePv(targetMemberRangeExt.getAllTeamConsumePv().add(orderAchieve));
            targetMemberRangeExt.setAllTeamMonthPv(targetMemberRangeExt.getAllTeamMonthPv().add(orderAchieve));

            // 激活的账号才能累计业绩和盒数（有注册、升级订单）
            if (targetMemberRangeExt.getEnableStatus() == EYesNo.YES.getIntValue()) {
                // 累计盒数
                targetMemberRangeExt.setTeamNewBoxNum(targetMemberRangeExt.getTeamNewBoxNum().add(boxNum));
                targetMemberRangeExt.setTeamBoxNum(targetMemberRangeExt.getTeamBoxNum().add(boxNum));
                targetMemberRangeExt.setTeamMonthBoxNum(targetMemberRangeExt.getTeamMonthBoxNum().add(boxNum));
                // 累计业绩
                targetMemberRangeExt.setTeamNewPv(ComputeUtil.computeAdd(targetMemberRangeExt.getTeamNewPv(), orderAchieve));
                targetMemberRangeExt.setTeamConsumePv(ComputeUtil.computeAdd(targetMemberRangeExt.getTeamConsumePv(), orderAchieve));
                targetMemberRangeExt.setTeamMonthPv(ComputeUtil.computeAdd(targetMemberRangeExt.getTeamMonthPv(), orderAchieve));
                // 累计金额
                targetMemberRangeExt.setTeamNewAmount(ComputeUtil.computeAdd(targetMemberRangeExt.getTeamNewAmount(), orderAmount));
                targetMemberRangeExt.setTeamConsumeAmount(ComputeUtil.computeAdd(targetMemberRangeExt.getTeamConsumeAmount(), orderAmount));
                targetMemberRangeExt.setTeamMonthAmount(ComputeUtil.computeAdd(targetMemberRangeExt.getTeamMonthAmount(), orderAmount));
                // 计算等级
                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);
            // 等级总盒数
            BigDecimal boxTotal = bdGrade.getBoxTotal();
            // 等级小市场盒数
            BigDecimal boxSmallTotal = bdGrade.getBoxSmallTotal();

            if (RetailConstants.VERTEX_PK_ID.equals(targetMemberRangeExt.getPkVertex())) {
                // TODO 需要根据配置写死的体系，进行单独处理
                // V4： 总 500，小 100
                // V5： 总 2000，小 400
                if (EGrade.VIP.getValue() == bdGrade.getGradeValue()) {
                    boxTotal = RetailConstants.VERTEX_V4_TOTAL_BOX;
                    boxSmallTotal = RetailConstants.VERTEX_V4_SMALL_BOX;
                } else if (EGrade.S_VIP.getValue() == bdGrade.getGradeValue()) {
                    boxTotal = RetailConstants.VERTEX_V5_TOTAL_BOX;
                    boxSmallTotal = RetailConstants.VERTEX_V5_SMALL_BOX;
                }
            }

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

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

                // 小区盒数（团队累计盒数 + 自消费累计盒数 + 两个注水虚拟盒数 - 大市场盒数）
                BigDecimal smallBoxNum = targetMemberRangeExt.getAllTeamBoxNum().add(targetMemberRangeExt.getConsumeBoxNum()).add(targetMemberRangeExt.getBigBoxNum()).add(targetMemberRangeExt.getSmallBoxNum()).subtract(bigBoxNum);
                if (smallBoxNum.compareTo(boxSmallTotal) >= 0) {
                    // 小区盒数 大于等于 升级小区盒数
                    CuMemberGrade cuMemberGrade = getCuMemberGrade(period, targetMemberRangeExt, bdGrade);
                    cuMemberGradeList.add(cuMemberGrade);
                    targetMemberRangeExt.setPkGrade(bdGrade.getPkId());
                    targetMemberRangeExt.setGradeValue(bdGrade.getGradeValue());
                    targetMemberRangeExt.setGradeName(bdGrade.getGradeName());
                }
            }
        }

        if (null != secondRangeTableName) {
            if (targetMemberRangeExt.getPkMember().equals(saOrderExt.getPkMember())) {
                // new 兼容购买等级多送2级的问题，秒结处理V4 V5方式不一样，会出现秒结等级和实际等级不匹配
                CuMemberRetailRangeExt memberRetailLevel = iCuMemberGradeService.getMemberLevel(saOrderExt.getPkMember(), saOrderExt.getPkId());
                if (null != memberRetailLevel) {
                    if (memberRetailLevel.getGradeValue() > targetMemberRangeExt.getGradeValue()) {
                        targetMemberRangeExt.setPkGrade(memberRetailLevel.getPkGrade());
                        targetMemberRangeExt.setGradeValue(memberRetailLevel.getGradeValue());
                    }
                }
            }
        }

        // 计算当月奖衔
        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())) {
                    // 累计业绩足够，即可升奖衔
                    cuMemberAwardsList.add(getCuMemberRetailAwards(targetMemberRangeExt, period, saOrderExt, bdAwards, EAwardsType.RANGE_TYPE.getValue(), targetMemberRangeExt.getPkAwards()));
                    targetMemberRangeExt.setPkAwards(bdAwards.getPkId());
                    targetMemberRangeExt.setAwardsValue(bdAwards.getAwardsValue());
                    targetMemberRangeExt.setAwardsName(bdAwards.getAwardsName());
                    continue;
                }
            }
            break;
        }

        // 校验大小区会员数据
        List<CuMemberRetailRangeExt> cuMemberRangeExtList = null;
        // 校验累计小部门会员数据
        List<CuMemberRetailRangeExt> cuMemberRetailRangeExtList = null;
        // 计算分红奖衔
        while (true) {
            // 当月奖衔值 + 5，获取下一个奖衔值
            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())) {
                    // 再验证小区，计算小区业绩（拉取直推会员数据）
                    if (null == cuMemberRangeExtList) {
                        if (null != secondRangeTableName) {
                            // 会员表 关联 秒结表 和 昨日结算表，查询订单会员直推数据
                            cuMemberRangeExtList = iCuMemberRetailRangeService.queryCuMemberSecondRangeExtByParent(rangeTableName, secondRangeTableName, targetMemberRangeExt.getPkMember());
                        } else {
                            // 昨日结算表，查询订单会员直推数据
                            cuMemberRangeExtList = iCuMemberRetailRangeService.queryCuMemberRetailRangeExtByParent(rangeTableName, targetMemberRangeExt.getPkMember());
                        }
                    }
                    // 本人月消费业绩（默认为大区）
                    BigDecimal consumeBigPv = targetMemberRangeExt.getMonthConsumePv();
                    for (CuMemberRetailRangeExt cuMemberRetailRangeExt : cuMemberRangeExtList) {
                        if (memberRangeExtMap.containsKey(cuMemberRetailRangeExt.getPkMember())) {
                            cuMemberRetailRangeExt = memberRangeExtMap.get(cuMemberRetailRangeExt.getPkMember());
                        }
                        // 月累计业绩 = 本人月消费业绩 + 团队月消费业绩
                        BigDecimal consumePv = ComputeUtil.computeAdd(cuMemberRetailRangeExt.getMonthConsumePv(), cuMemberRetailRangeExt.getAllTeamMonthPv());
                        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) {
                            // 验证是否有多个区满足业绩
                            if (null == cuMemberRetailRangeExtList) {
                                // 非秒结需要查询日结相关数据，秒结表使用上面查出的数据就可以
                                if (null != secondRangeTableName) {
                                    // 会员表 关联 秒结表 和 昨日结算表，查询订单会员直推数据
                                    cuMemberRetailRangeExtList = cuMemberRangeExtList;
                                } else {
                                    // 昨日结算表，查询订单会员直推数据
                                    cuMemberRetailRangeExtList = iCuMemberRetailRangeService.queryCuMemberRetailRangeEnoughAchieve(rangeTableName, targetMemberRangeExt.getPkMember(), bdAwards.getShareCommunityCheck());
                                }
                            }

                            int enoughNum = 0;
                            if (ComputeUtil.compareValue(targetMemberRangeExt.getMonthConsumePv(), bdAwards.getShareCommunityCheck())) {
                                enoughNum += 1;
                            }
                            for (CuMemberRetailRangeExt cuMemberRetailRangeExt : cuMemberRetailRangeExtList) {
                                if (memberRangeExtMap.containsKey(cuMemberRetailRangeExt.getPkMember())) {
                                    cuMemberRetailRangeExt = memberRangeExtMap.get(cuMemberRetailRangeExt.getPkMember());
                                }
                                if (ComputeUtil.compareValue(ComputeUtil.computeAdd(cuMemberRetailRangeExt.getMonthConsumePv(), cuMemberRetailRangeExt.getAllTeamMonthPv()), bdAwards.getShareCommunityCheck())) {
                                    // 本人月消费业绩 + 团队月消费业绩 >= 小区考核业绩，则满足条件小部门 +1
                                    enoughNum += 1;
                                }
                            }
                            if (bdAwards.getPlaceDeptNum() > enoughNum) {
                                break;
                            }
                        }
                        cuMemberAwardsList.add(getCuMemberRetailAwards(targetMemberRangeExt, period, saOrderExt, bdAwards, EAwardsType.SHARE_TYPE.getValue(), targetMemberRangeExt.getPkShareAwards()));
                        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, BigDecimal boxNum,
                                                                            Map<String, CuMemberGrade> cuMemberGradeMap, Map<String, CuMemberAwards> cuMemberAwardsMap, Map<String, CuMemberAwards> cuMemberShareAwardsMap,
                                                                            boolean isSecond) {
        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 (isSecond) {
                // 当天，秒结处理
                targetMemberRangeExt.setAllTeamNewBoxNum(targetMemberRangeExt.getAllTeamNewBoxNum().subtract(boxNum));
                targetMemberRangeExt.setAllTeamNewPv(targetMemberRangeExt.getAllTeamNewPv().subtract(orderAchieve));
            } else {
                // 非当天，日结处理
                targetMemberRangeExt.setAllTeamNewBoxNum(targetMemberRangeExt.getAllTeamNewBoxNum().subtract(boxNum));
                targetMemberRangeExt.setAllTeamBoxNum(targetMemberRangeExt.getAllTeamBoxNum().subtract(boxNum));
                targetMemberRangeExt.setAllTeamMonthBoxNum(targetMemberRangeExt.getAllTeamMonthBoxNum().subtract(boxNum));
                targetMemberRangeExt.setAllTeamNewPv(targetMemberRangeExt.getAllTeamNewPv().subtract(orderAchieve));
                targetMemberRangeExt.setAllTeamConsumePv(targetMemberRangeExt.getAllTeamConsumePv().subtract(orderAchieve));
                targetMemberRangeExt.setAllTeamMonthPv(targetMemberRangeExt.getAllTeamMonthPv().subtract(orderAchieve));
            }

            // 激活的账号才能累计业绩和盒数（有注册、升级订单）
            if (targetMemberRangeExt.getEnableStatus() == EYesNo.YES.getIntValue()) {
                // 累计盒数
                targetMemberRangeExt.setTeamNewBoxNum(targetMemberRangeExt.getTeamNewBoxNum().subtract(boxNum));
                targetMemberRangeExt.setTeamBoxNum(targetMemberRangeExt.getTeamBoxNum().subtract(boxNum));
                targetMemberRangeExt.setTeamMonthBoxNum(targetMemberRangeExt.getTeamMonthBoxNum().subtract(boxNum));
                // 累计金额
                targetMemberRangeExt.setTeamNewAmount(ComputeUtil.computeSubtract(targetMemberRangeExt.getTeamNewAmount(), orderAmount));
                targetMemberRangeExt.setTeamConsumeAmount(ComputeUtil.computeSubtract(targetMemberRangeExt.getTeamConsumeAmount(), orderAmount));
                targetMemberRangeExt.setTeamMonthAmount(ComputeUtil.computeSubtract(targetMemberRangeExt.getTeamMonthAmount(), orderAmount));
                // 累计业绩
                targetMemberRangeExt.setTeamNewPv(ComputeUtil.computeSubtract(targetMemberRangeExt.getTeamNewPv(), orderAchieve));
                targetMemberRangeExt.setTeamConsumePv(ComputeUtil.computeSubtract(targetMemberRangeExt.getTeamConsumePv(), orderAchieve));
                targetMemberRangeExt.setTeamMonthPv(ComputeUtil.computeSubtract(targetMemberRangeExt.getTeamMonthPv(), orderAchieve));
                // 计算等级
                calculateBackGrade(period, memberRangeExtMap, rangeTableName, saOrderExt, retailTeamGradeMap, retailAwardsMap, secondRangeTableName,
                        cuMemberGradeMap, cuMemberAwardsMap, cuMemberShareAwardsMap, 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, Map<String, CuMemberAwards> cuMemberShareAwardsMap,
                                    CuMemberRetailRangeExt targetMemberRangeExt) {
        // 遍历团队等级map（V4,V5）
        for (Integer gradeValue : retailTeamGradeMap.keySet()) {
            BdGrade bdGrade = retailTeamGradeMap.get(gradeValue);
            // 等级总盒数
            BigDecimal boxTotal = bdGrade.getBoxTotal();
            // 等级小市场盒数
            BigDecimal boxSmallTotal = bdGrade.getBoxSmallTotal();

            if (RetailConstants.VERTEX_PK_ID.equals(targetMemberRangeExt.getPkVertex())) {
                // TODO 需要根据配置写死的体系，进行单独处理
                // V4： 总 500，小 100
                // V5： 总 2000，小 400
                if (EGrade.VIP.getValue() == bdGrade.getGradeValue()) {
                    boxTotal = RetailConstants.VERTEX_V4_TOTAL_BOX;
                    boxSmallTotal = RetailConstants.VERTEX_V4_SMALL_BOX;
                } else if (EGrade.S_VIP.getValue() == bdGrade.getGradeValue()) {
                    boxTotal = RetailConstants.VERTEX_V5_TOTAL_BOX;
                    boxSmallTotal = RetailConstants.VERTEX_V5_SMALL_BOX;
                }
            }

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

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

                // 小区盒数（团队累计盒数 + 自消费累计盒数 + 两个注水虚拟盒数 - 大市场盒数）
                BigDecimal smallBoxNum = targetMemberRangeExt.getAllTeamBoxNum().add(targetMemberRangeExt.getConsumeBoxNum()).add(targetMemberRangeExt.getBigBoxNum()).add(targetMemberRangeExt.getSmallBoxNum()).subtract(bigBoxNum);
                if (smallBoxNum.compareTo(boxSmallTotal) >= 0) {
                    // 小区盒数 大于等于 升级小区盒数
                    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())) {
                    // 累计业绩足够，即可升奖衔
                    CuMemberAwards cuMemberRetailAwards = getCuMemberRetailAwards(targetMemberRangeExt, period, saOrderExt, bdAwards, EAwardsType.RANGE_TYPE.getValue(), targetMemberRangeExt.getPkAwards());
                    cuMemberAwardsMap.put(cuMemberRetailAwards.getPkMember() + "_" + cuMemberRetailAwards.getNewLevel(), cuMemberRetailAwards);
                    targetMemberRangeExt.setPkAwards(bdAwards.getPkId());
                    targetMemberRangeExt.setAwardsValue(bdAwards.getAwardsValue());
                    targetMemberRangeExt.setAwardsName(bdAwards.getAwardsName());
                    continue;
                }
            }
            break;
        }

        // 计算分红奖衔
        while (true) {
            // 当月奖衔值 + 5，获取下一个奖衔值
            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;
                    if (secondRangeTableName != null) {
                        // 会员表 关联 秒结表 和 昨日结算表，查询订单会员直推数据
                        cuMemberRangeExtList = iCuMemberRetailRangeService.queryCuMemberSecondRangeExtByParent(rangeTableName, secondRangeTableName, targetMemberRangeExt.getPkMember());
                    } else {
                        // 昨日结算表，查询订单会员直推数据
                        cuMemberRangeExtList = iCuMemberRetailRangeService.queryCuMemberRetailRangeExtByParent(rangeTableName, targetMemberRangeExt.getPkMember());
                    }
                    // 本人月消费业绩（默认为大区）
                    BigDecimal consumeBigPv = targetMemberRangeExt.getMonthConsumePv();
                    for (CuMemberRetailRangeExt cuMemberRetailRangeExt : cuMemberRangeExtList) {
                        if (memberRangeExtMap.containsKey(cuMemberRetailRangeExt.getPkMember())) {
                            cuMemberRetailRangeExt = memberRangeExtMap.get(cuMemberRetailRangeExt.getPkMember());
                        }
                        // 月累计业绩 = 本人月消费业绩 + 团队月消费业绩
                        BigDecimal consumePv = ComputeUtil.computeAdd(cuMemberRetailRangeExt.getMonthConsumePv(), cuMemberRetailRangeExt.getAllTeamMonthPv());
                        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;
                            if (secondRangeTableName != null) {
                                // 会员表 关联 秒结表 和 昨日结算表，查询订单会员直推数据
                                cuMemberRetailRangeExtList = iCuMemberRetailRangeService.queryCuMemberSecondRangeExtByParent(rangeTableName, secondRangeTableName, targetMemberRangeExt.getPkMember());
                            } else {
                                // 昨日结算表，查询订单会员直推数据
                                cuMemberRetailRangeExtList = iCuMemberRetailRangeService.queryCuMemberRetailRangeEnoughAchieve(rangeTableName, targetMemberRangeExt.getPkMember(), bdAwards.getShareCommunityCheck());
                            }

                            int enoughNum = 0;
                            if (ComputeUtil.compareValue(targetMemberRangeExt.getMonthConsumePv(), bdAwards.getShareCommunityCheck())) {
                                enoughNum += 1;
                            }
                            for (CuMemberRetailRangeExt cuMemberRetailRangeExt : cuMemberRetailRangeExtList) {
                                if (memberRangeExtMap.containsKey(cuMemberRetailRangeExt.getPkMember())) {
                                    cuMemberRetailRangeExt = memberRangeExtMap.get(cuMemberRetailRangeExt.getPkMember());
                                }
                                if (ComputeUtil.compareValue(ComputeUtil.computeAdd(cuMemberRetailRangeExt.getMonthConsumePv(), cuMemberRetailRangeExt.getAllTeamMonthPv()), bdAwards.getShareCommunityCheck())) {
                                    // 本人月消费业绩 + 团队月消费业绩 >= 小区考核业绩，则满足条件小部门 +1
                                    enoughNum += 1;
                                }
                            }
                            if (bdAwards.getPlaceDeptNum() > enoughNum) {
                                break;
                            }
                        }
                        CuMemberAwards cuMemberRetailAwards = getCuMemberRetailAwards(targetMemberRangeExt, period, saOrderExt, bdAwards, EAwardsType.SHARE_TYPE.getValue(), targetMemberRangeExt.getPkShareAwards());
                        cuMemberShareAwardsMap.put(cuMemberRetailAwards.getPkMember() + "_" + cuMemberRetailAwards.getNewLevel(), cuMemberRetailAwards);
                        targetMemberRangeExt.setShareAwardsValue(bdAwards.getAwardsValue());
                        targetMemberRangeExt.setPkShareAwards(bdAwards.getPkId());
                        continue;
                    }
                }
            }
            break;
        }
    }


    /**
     * 计算直推级差收益，根据直推级差收益计算平级收益
     */
    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 = saOrderItems.getWaresQuantity();
        // 单个商品价格
        BigDecimal waresOnePrice = waresPrice.divide(waresQuantityBig, 6, RoundingMode.FLOOR);

        // 前一个会员等级
        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 份 10%
                    rangeBonusIncome = RetailConstants.RANGE_BONUS.multiply(waresPrice);
                } else if (EGrade.YOU_KE.getValue() == calGradeValue) {
                    // SVIP，拿 2 份 10%
                    rangeBonusIncome = RetailConstants.RANGE_BONUS.multiply(waresPrice).multiply(new BigDecimal("2"));
                } else if (EGrade.MAKER.getValue() == calGradeValue) {
                    // 卓越，拿 3 份 10%
                    rangeBonusIncome = RetailConstants.RANGE_BONUS.multiply(waresPrice).multiply(new BigDecimal("3"));
                } else if (EGrade.VIP.getValue() == calGradeValue) {
                    // 首席，拿 4 份 10%
                    rangeBonusIncome = RetailConstants.RANGE_BONUS.multiply(waresPrice).multiply(new BigDecimal("4"));
                } else if (EGrade.S_VIP.getValue() == calGradeValue) {
                    // 合伙人，拿 5 份 10%
                    rangeBonusIncome = RetailConstants.RANGE_BONUS.multiply(waresPrice).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;
                }
                // 平级收益（商品价格 * 千分之五） -- 6位小数，四舍五入
                sameBonusIncome = waresOnePrice.multiply(RetailConstants.SAME_RATIO).setScale(6, BigDecimal.ROUND_HALF_UP).multiply(waresQuantityBig);
                // 平级收益累计
                beforeSameBonus = beforeSameBonus.add(sameBonusIncome);
                // 平级等级代数等级
                beforeSameAlgebra += 1;
            } else if (calGradeValue > beforeGradeValue) {
                // 当前会员等级 > 前一个会员等级
                int tmpGradeVal = (calGradeValue - beforeGradeValue) / 10;

                // 新等级的直推级差收益
                rangeBonusIncome = RetailConstants.RANGE_BONUS.multiply(waresPrice).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().compareTo(BigDecimal.ZERO) == 0) {
//            return null;
//        }

        CuMemberRetailRangeExt sourceRetailRangeExt = memberRangeExtMap.get(saOrder.getPkMember());
        // 获取对应区域会员
        CuMemberRetailRangeExt cuMemberRetailRangeExt = countyRangeExtMap.get(sourceRetailRangeExt.getRegionVertexPkId() + "_" + 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%
        BigDecimal benefitIncome = BigDecimal.ZERO;
        if (EOrderType.RETAIL_REGISTER.getValue() == saOrder.getOrderType()
                || EOrderType.RETAIL_UPGRADE.getValue() == saOrder.getOrderType()) {
            // 注册、升级订单， 区域收益 = 商品价格 * 0.5% * 商品数量
            for (SaOrderWaresExt saOrderWaresExt : saOrder.getOrderWaresExtList()) {
                // 商品最终价格
                BigDecimal waresPrice = saOrderWaresExt.getWaresPrice();
                // 商品数量
                BigDecimal waresQuantityBig = saOrderWaresExt.getWaresQuantity();
                // 单个商品价格
                BigDecimal waresOnePrice = waresPrice.divide(waresQuantityBig, 6, RoundingMode.FLOOR);

                benefitIncome = benefitIncome.add(waresOnePrice.multiply(RetailConstants.SAME_RATIO).setScale(6, BigDecimal.ROUND_HALF_UP).multiply(waresQuantityBig));
            }
        } else if (EOrderType.RETAIL_REPURCHASE.getValue() == saOrder.getOrderType()) {
            // 复购订单， 区域收益 = 复购区域分红 * 商品数量
            for (SaOrderWaresExt saOrderWaresExt : saOrder.getOrderWaresExtList()) {
                if (EDelFlag.UN_DELETE.getValue() == saOrderWaresExt.getDelFlag()) {
                    if (ERatioType.VALUE.getValue() == saOrderWaresExt.getAreaIncomeType()) {
                        // 按比值处理
                        benefitIncome = benefitIncome.add(saOrderWaresExt.getAreaIncome().multiply(saOrderWaresExt.getWaresQuantity()));
                    } else {
                        // 按比率处理
                        benefitIncome = benefitIncome.add(saOrderWaresExt.getWaresPrice().multiply(saOrderWaresExt.getAreaIncome()).divide(new BigDecimal("100"), 6, BigDecimal.ROUND_HALF_UP));
                    }
                }
            }
        }

        CuMemberBonusDetail cuMemberBonusDetail = packageBenefitIncome(bonusConfigDTO, period, cuMemberBonusMap, null, RetailConstants.SAME_RATIO, benefitIncome,
                cuMemberRetailRangeExt, EBonusItems.RETAIL_AREA_INCOME.getValue(), BonusMsgConstants.RETAIL_AREA_INCOME);
        // 计算业绩以盒数做为基础
        cuMemberBonusDetail.setCalAchieve(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;
    }

    /**
     * 团队福利、福利分红等奖金 -- 月奖
     *
     * @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);
        // 上月最后一天期数
        CuMemberSettlePeriod beforeMonthLast = getCuMemberSettlePeriodService().getCuMemberSettlePeriodByDate(beforeMonthLastDate);
        String rangeTableName = TableNameConstants.CU_MEMBER_RETAIL_RANGE;
        // 如果上月最后一期有值则使用，没有值则使用昨天期数
        if (ObjectUtil.isNotEmpty(beforeMonthLast)) {
            rangeTableName += beforeMonthLast.getPkId();
        } else {
            rangeTableName += period;
        }

        // 查询上月订单
        // 结算月第一天（上月第一天）
        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<CuMemberBonusCoach> memberBonusCoachList = new ArrayList<>();
        // 月度分红收益
        List<CuMemberBonusDetail> memberBonusDetailList = new ArrayList<>();
        // 当前年月
        String month = DateUtils.getMonth(settleDateStr);

        if (EEnv.TEST.getValue().equals(BdConfig.getEnv())) {
            // 测试环境，只查昨天订单
            Date endDate = DateUtils.afterDate(1, ChronoUnit.DAYS, settleDate);
            log.info("测试环境,月结日期： {}", endDate);
            List<SaOrder> currentMonthOrderList = iBonusOrderService.listSaOrderByTime(settleDate, endDate, orderType);
            totalMonthOrderList.addAll(currentMonthOrderList);
            // 测试环境奖衔取当前结算期
            rangeTableName = TableNameConstants.CU_MEMBER_RETAIL_RANGE + period;
            log.info("测试环境,月结期间： {}", rangeTableName);
        } else {
            // 非测试环境
            while (!DateUtils.compareDateEqual(currentMonthFirstDate, nextMonthFirstDate)) {
                // 从上月第一天开始，每天查一次订单，查到本月第一天停止
                Date endDate = DateUtils.afterDate(1, ChronoUnit.DAYS, currentMonthFirstDate);
                // 查询指定时间范围内订单
                List<SaOrder> currentMonthOrderList = iBonusOrderService.listSaOrderByTime(currentMonthFirstDate, endDate, orderType);
                totalMonthOrderList.addAll(currentMonthOrderList);
                currentMonthFirstDate = endDate;
            }
        }

        if (totalMonthOrderList.size() > 0) {
            // 会员ID集合
            Set<Long> pkMemberSet = new HashSet<>();
            totalMonthOrderList.forEach(saOrder -> pkMemberSet.add(saOrder.getPkMember()));
            // 查询会员血缘伞上数据
            List<CuMemberRetailRangeExt> cuMemberRetailRangeExtList = iCuMemberRetailRangeService.batchQueryMemberRetailRangeByMemberPk(rangeTableName, pkMemberSet);
            // 会员结算map（key:会员ID, value:会员结算数据）
            Map<Long, CuMemberRetailRangeExt> memberRangeExtMap = new HashMap<>();
            cuMemberRetailRangeExtList.forEach(cuMemberRetailRangeExt ->
                    memberRangeExtMap.put(cuMemberRetailRangeExt.getPkMember(), cuMemberRetailRangeExt));

            // 按照系统类型将订单区分 -- 目前只有一个系统类型
            // key:会员体系，value：会员订单列表
            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;
                // 订单对应map
                Map<Long, SaOrder> saOrderMap = new HashMap<>();

                // new 两个月奖
                // 月度级差：注册、升级订单，从自己开始往上算，最多拨出10代（紧缩）
                // 复购级差：复购订单，从自己开始往上算，最多拨出10代（紧缩）
                for (SaOrder saOrder : saOrders) {
                    // 累计订单业绩
                    totalMonthConsumePv = ComputeUtil.computeAdd(totalMonthConsumePv, saOrder.getOrderAchieve());
                    // 封装订单map
                    saOrderMap.put(saOrder.getPkId(), saOrder);

                    if (EOrderType.RETAIL_REGISTER.getValue() == saOrder.getOrderType()
                            || EOrderType.RETAIL_UPGRADE.getValue() == saOrder.getOrderType()) {
                        // 注册、升级订单，计算福利级差收益
                        // 订单会员
                        CuMemberRetailRangeExt sourceMemberRetailRangeExt = memberRangeExtMap.get(saOrder.getPkMember());
                        // 会员奖衔级差比例 -- 初始为下单会员奖衔级差比例
                        BigDecimal rangeRatio = sourceMemberRetailRangeExt.getRangeRatio();
                        // 从自己开始往上算，第一个人用自己处理
                        long pkParent = sourceMemberRetailRangeExt.getPkMember();
                        while (true) {
                            CuMemberRetailRangeExt targetMemberRangeExt = memberRangeExtMap.get(pkParent);
                            if (null == targetMemberRangeExt) {
                                break;
                            }
                            pkParent = targetMemberRangeExt.getPkParent();

                            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)) {
                                // 第一代是自己 并且 级差比例大于0 或者 级差比例大于前一代会员的奖衔级差比例
                                // 计算极差
                                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;
                            }
                        }
                    } else if (EOrderType.RETAIL_REPURCHASE.getValue() == saOrder.getOrderType()) {
                        // 复购订单，计算复购级差收益
                        // 订单会员
                        CuMemberRetailRangeExt sourceMemberRetailRangeExt = memberRangeExtMap.get(saOrder.getPkMember());
                        // 会员奖衔级差比例 -- 初始为下单会员奖衔级差比例
                        BigDecimal rangeRatio = sourceMemberRetailRangeExt.getMonthRepurchaseRatio();
                        // 从自己开始往上算，第一个人用自己处理
                        long pkParent = sourceMemberRetailRangeExt.getPkMember();
                        while (true) {
                            CuMemberRetailRangeExt targetMemberRangeExt = memberRangeExtMap.get(pkParent);
                            if (null == targetMemberRangeExt) {
                                break;
                            }
                            pkParent = targetMemberRangeExt.getPkParent();

                            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.getMonthRepurchaseRatio();
                            if ((targetMemberRangeExt.getPkMember().equals(saOrder.getPkMember()) && ComputeUtil.compareValue(rangeRatio))
                                    || ComputeUtil.compareGreaterThan(targetRangeRatio, rangeRatio)) {
                                // 第一代是自己 并且 级差比例大于0 或者 级差比例大于前一代会员的奖衔级差比例
                                // 计算极差
                                CuMemberBonus cuMemberBonus = getCuMemberBonus(period, cuMemberBonusMap, targetMemberRangeExt.getPkMember(),
                                        targetMemberRangeExt.getIncomeStatus(), targetMemberRangeExt.getPkSettleCountry(), targetMemberRangeExt.getPkRate());
                                // 复购级差收益
                                int pkBonusItems = getPkBonusItems(bonusConfigDTO, targetMemberRangeExt.getPkSettleCountry(), EBonusItems.RETAIL_MONTH_REPURCHASE_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);
                                rangeMonthRepurchaseRetailRemark(saOrder, cuMemberBonusRange, sourceMemberRetailRangeExt, targetMemberRangeExt);
                                BdBonusDeduct bdBonusDeduct = setBonusDetailDeduct(bonusConfigDTO, cuMemberBonusRange, saOrder.getOrderAmount(), BigDecimal.ONE);
                                if (EBonusIncomeStatus.NORMAL.getValue() == cuMemberBonusRange.getIncomeStatus()) {
                                    cuMemberBonus.setRetailMonthRepurchaseIncome(ComputeUtil.computeAdd(cuMemberBonus.getRetailMonthRepurchaseIncome(), cuMemberBonusRange.getPretaxIncome()));
                                    setRetailTotal(bdBonusDeduct, cuMemberBonus, cuMemberBonusRange);
                                }
                                memberBonusRangeList.add(cuMemberBonusRange);
                                // 下一代会员
                                rangeRatio = targetRangeRatio;
                                sourceMemberRetailRangeExt = targetMemberRangeExt;
                            }
                        }
                    }
                }

                // 培育津贴
                if (CollectionUtil.isNotEmpty(memberBonusRangeList)) {
                    for (CuMemberBonusRange cuMemberBonusRange : memberBonusRangeList) {
                        // 第一代开始
                        int i = MagicNumberConstants.BLOOD_GENERATION_START;
                        // 推荐人
                        Long pkMember = memberRangeExtMap.get(cuMemberBonusRange.getPkBonus()).getPkParent();
                        // 提供奖金会员
                        CuMemberRetailRangeExt sourceMemberRetailExt = memberRangeExtMap.get(cuMemberBonusRange.getPkBonus());
                        // 级差所产生的培育津贴列表
                        List<CuMemberBonusCoach> rangeBonusCoachList = new ArrayList<>();
                        // 最多发十代
                        while (i <= MagicNumberConstants.BLOOD_GENERATION_END) {
                            // 当前需要拿奖金的会员
                            CuMemberRetailRangeExt targetMemberRetailExt = memberRangeExtMap.get(pkMember);
                            if (null == targetMemberRetailExt) {
                                break;
                            }
                            pkMember = targetMemberRetailExt.getPkParent();

                            if (EAccountStatus.STOP_INCOME.getValue() == targetMemberRetailExt.getAccountStatus()
                                    || ECategory.NORMAL.getValue() != targetMemberRetailExt.getCategory()
                                    || targetMemberRetailExt.getGradeValue() != EGrade.S_VIP.getValue()
                                    || targetMemberRetailExt.getEnableStatus() == EYesNo.NO.getIntValue()
                                    || EIncomeStatus.STOP_INCOME.getValue() == targetMemberRetailExt.getIncomeStatus()) {
                                // 停算收益、非正常会员、未激活、等级不为合伙人、停止收益，直接跳过
                                continue;
                            }

                            if (validatePkBonusItems(bonusConfigDTO, targetMemberRetailExt.getPkSettleCountry(), EBonusItems.RETAIL_COACHING_INCOME.getValue())) {
                                // 校验当前国家是否有该奖项
                                continue;
                            }

                            // 奖金订单
                            SaOrder saOrder = saOrderMap.get(cuMemberBonusRange.getPkOrder());
                            if (null == saOrder) {
                                log.warn("培育津贴因订单为空跳过, cuMemberBonusRange: {}", cuMemberBonusRange);
                                continue;
                            }

                            // 获取奖衔能拿多少代领导奖的奖衔值
                            Integer awardsValue = targetMemberRetailExt.getCoachAlgebra();

                            // 判断是否有奖金
                            if (awardsValue >= i) {
                                // 培育津贴比例
                                BigDecimal awardCalRadio = targetMemberRetailExt.getCoachRatio();
                                // 生成培育津贴明细
                                CuMemberBonusCoach cuMemberBonusCoach = getCuMemberBonusCoach(bonusConfigDTO, cuMemberBonusRange, i, targetMemberRetailExt, awardCalRadio);
                                // 获取会员奖金数据
                                CuMemberBonus cuMemberBonus = getCuMemberBonus(period, cuMemberBonusMap, targetMemberRetailExt.getPkMember(),
                                        targetMemberRetailExt.getIncomeStatus(), targetMemberRetailExt.getPkSettleCountry(), targetMemberRetailExt.getPkRate());

                                // 收益占比
                                BdBonusDeduct bdBonusDeduct = setBonusDetailDeduct(bonusConfigDTO, cuMemberBonusCoach, saOrder.getOrderAmount(), BigDecimal.ONE);
                                retailCoachRemark(saOrder, cuMemberBonusCoach, sourceMemberRetailExt, targetMemberRetailExt);

                                if (EBonusIncomeStatus.NORMAL.getValue() == cuMemberBonusCoach.getIncomeStatus()) {
                                    cuMemberBonus.setCoachIncome(ComputeUtil.computeAdd(cuMemberBonus.getCoachIncome(), cuMemberBonusCoach.getPretaxIncome()));
                                    setRetailTotal(bdBonusDeduct, cuMemberBonus, cuMemberBonusCoach);
                                }
                                rangeBonusCoachList.add(cuMemberBonusCoach);

                                // 这一代领导奖计算完，计算代数加1
                                i++;
                            }
                        }

                        if (rangeBonusCoachList.size() > 0) {
                            // 共多少代
                            --i;
                            for (CuMemberBonusCoach cuMemberBonusCoach : rangeBonusCoachList) {
                                cuMemberBonusCoach.setCoachGeneration(i);
                                cuMemberBonusCoach.setRemark(cuMemberBonusCoach.getRemark().replace("#", cuMemberBonusCoach.getCoachGeneration().toString()));
                                memberBonusCoachList.add(cuMemberBonusCoach);
                            }
                        }
                    }
                }

                // 查询 v5 等级 且 分红奖衔 >= S4
                List<CuMemberRetailRangeExt> memberRetailRangeExtList = iCuMemberRetailRangeService.batchQueryMemberRetailRangeByAwards(rangeTableName);
                if (memberRetailRangeExtList.size() > 0) {
                    // 查询月度分红会员的直推
                    List<CuMemberRetailRangeExt> retailRangeExtList = iCuMemberRetailRangeService.batchQueryMemberRetailRangeByParent(rangeTableName, memberRetailRangeExtList);
                    // 推荐会员列表（key：推荐人，value：推荐会员列表）
                    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 级奖衔会员
                    List<CuMemberRetailRangeExt> firstAwardsRetailRangeList = new ArrayList<>();
                    // 4 5 6 级奖衔累计业绩
                    BigDecimal firstConsumePv = BigDecimal.ZERO;
                    // 4 5 6 月度分红平均 比例
                    BigDecimal benefitAvgRatio = BigDecimal.ZERO;
                    // 4 5 6 月度分红加权 比例
                    BigDecimal benefitShareRatio = BigDecimal.ZERO;

                    // 7 8 9 级奖衔会员
                    List<CuMemberRetailRangeExt> secondAwardsRetailRangeList = new ArrayList<>();
                    // 7 8 9 级奖衔累计业绩
                    BigDecimal secondConsumePv = BigDecimal.ZERO;
                    // 7 8 9 月度分红平均 比例
                    BigDecimal secondBenefitAvgRatio = BigDecimal.ZERO;
                    // 7 8 9 月度分红加权 比例
                    BigDecimal secondBenefitShareRatio = BigDecimal.ZERO;

                    for (CuMemberRetailRangeExt cuMemberRetailRangeExt : memberRetailRangeExtList) {
                        if (parentMemberRangeExtMap.containsKey(cuMemberRetailRangeExt.getPkMember())) {
                            // 获取会员的推荐数据
                            List<CuMemberRetailRangeExt> rangeExtList = parentMemberRangeExtMap.get(cuMemberRetailRangeExt.getPkMember());
                            // 计算小区（本人月消费默认为大区）
                            BigDecimal bigConsumePv = cuMemberRetailRangeExt.getMonthConsumePv();
                            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().add(cuMemberRetailRangeExt.getMonthConsumePv()), bigConsumePv));
                        } else {
                            cuMemberRetailRangeExt.setSmallAreaConsumePv(BigDecimal.ZERO);
                        }
                        if (cuMemberRetailRangeExt.getShareAwardsValue() >= EAwards.SENIOR_MANAGER.getValue()
                                && cuMemberRetailRangeExt.getShareAwardsValue() <= EAwards.HIGH_CHIEF.getValue()) {
                            // 奖衔 4 5 6 级数据处理
                            firstAwardsRetailRangeList.add(cuMemberRetailRangeExt);
                            benefitAvgRatio = cuMemberRetailRangeExt.getBenefitAvgRatio();
                            benefitShareRatio = cuMemberRetailRangeExt.getBenefitShareRatio();
                            firstConsumePv = ComputeUtil.computeAdd(cuMemberRetailRangeExt.getSmallAreaConsumePv(), firstConsumePv);
                        } else {
                            // 奖衔 7 8 9 级数据处理
                            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);
                            // 月度分红 - 加权收益
                            memberBonusDetailList.add(packageBenefitIncome(bonusConfigDTO, period, cuMemberBonusMap, month, benefitShareRatio,
                                    bonusIncome, cuMemberRetailRangeExt, EBonusItems.RETAIL_BENEFIT_INCOME.getValue(), BonusMsgConstants.RETAIL_BENEFIT_INCOME));
                        }
                    }
                    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);
                            // 月度分红 - 加权收益
                            memberBonusDetailList.add(packageBenefitIncome(bonusConfigDTO, period, cuMemberBonusMap, month, secondBenefitShareRatio,
                                    bonusIncome, cuMemberRetailRangeExt, EBonusItems.RETAIL_BENEFIT_INCOME.getValue(), BonusMsgConstants.RETAIL_BENEFIT_INCOME));
                        }
                    }
                }
            }
        }
        if (memberBonusDetailList.size() > 0) {
            if (bonusRecordDetailVO.getCuMemberBonusDetailList() == null) {
                bonusRecordDetailVO.setCuMemberBonusDetailList(memberBonusDetailList);
            } else {
                bonusRecordDetailVO.getCuMemberBonusDetailList().addAll(memberBonusDetailList);
            }
        }
        if (memberBonusCoachList.size() > 0) {
            if (bonusRecordDetailVO.getCuMemberBonusCoachList() == null) {
                bonusRecordDetailVO.setCuMemberBonusCoachList(memberBonusCoachList);
            } else {
                bonusRecordDetailVO.getCuMemberBonusCoachList().addAll(memberBonusCoachList);
            }
        }
        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;
    }


    protected CuMemberBonusCoach getCuMemberBonusCoach(BonusConfigDTO bonusConfigDTO, CuMemberBonusRange cuMemberBonusRange,
                                                       int i, CuMemberRetailRangeExt targetMemberRangeExt, BigDecimal awardCalRadio) {
        CuMemberBonusCoach cuMemberBonusCoach = CuMemberBonusCoach.builder()
                .pkBonus(targetMemberRangeExt.getPkMember())
                .pkOrder(cuMemberBonusRange.getPkOrder())
                .pkBonusItems(getPkBonusItems(bonusConfigDTO, targetMemberRangeExt.getPkSettleCountry(), EBonusItems.RETAIL_COACHING_INCOME.getValue()))
                .incomeStatus(targetMemberRangeExt.getIncomeStatus())
                .calType(ECalType.RATIO.getValue())
                .calAchieve(cuMemberBonusRange.getCalAchieve())
                .currentGeneration(i)
                // 计算比例
                .calValue(awardCalRadio)
                .incomeTax(BigDecimal.ZERO)
                .realIncome(BigDecimal.ZERO)
                .incomeRatio(BigDecimal.ZERO)
                .incomeDialRatio(BigDecimal.ZERO)
                .orderDialRatio(BigDecimal.ZERO)
                .pretaxIncome(ComputeUtil.computeBonusMultiply(cuMemberBonusRange.getPretaxIncome(), awardCalRadio))
                .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 getCuMemberRetailBonusRange(SaOrder saOrderExt, CuMemberRetailRangeExt targetMemberRangeExt,
                                                           CuMemberBonus cuMemberBonus, Integer pkBonusItems) {
        CuMemberBonusRange cuMemberBonusRange = CuMemberBonusRange.builder()
                .pkBonus(cuMemberBonus.getPkId())
                .incomeStatus(targetMemberRangeExt.getIncomeStatus())
                .pkOrder(saOrderExt.getPkId())
                .pkBonusItems(pkBonusItems)
                .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;
    }

    private CuMemberAwards getCuMemberRetailAwards(CuMemberRetailRangeExt sourceRangeExt, Integer period, SaOrderExt saOrderExt,
                                                   BdAwards bdRangeAwards, Integer awardType, Integer oldLevel) {
        CuMemberAwards cuMemberAwards = CuMemberAwards.builder()
                .pkMember(sourceRangeExt.getPkMember())
                .period(period)
                .upType(EUpgradeType.AUTO_UPGRADE.getValue())
                .awardType(awardType)
                // 原等级
                .oldLevel(null == oldLevel ? sourceRangeExt.getPkAwards() : oldLevel)
                .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()
                        )
                ));
    }

    /**
     * 处理复购级差
     */
    private List<CuMemberBonusRange> calculateRepurchaseRangeBonus(SaOrderExt saOrderExt, Map<Long, CuMemberRetailRangeExt> memberRangeExtMap,
                                                                   Map<Long, List<Integer>> vertexBonusMap, Map<Long, List<SaOrderItemsExt>> rangeOrderMap,
                                                                   BonusConfigDTO bonusConfigDTO, Integer period, Map<Long, CuMemberBonus> cuMemberBonusMap) {
        // 直推级差返回数据
        List<CuMemberBonusRange> memberBonusRangeList = new ArrayList<>();
        // 订单会员
        CuMemberRetailRangeExt sourceMemberRangeExt = memberRangeExtMap.get(saOrderExt.getPkMember());

        List<Integer> vertexBonusList = vertexBonusMap.get(sourceMemberRangeExt.getPkVertex());
        if (CollectionUtil.isNotEmpty(vertexBonusList)) {
            // 存在体系奖项
            for (Integer bonusItems : vertexBonusList) {
                if (EBonusItems.REPURCHASE_RANGE_INCOME.getValue() == bonusItems) {
                    // 复购级差收益（key:会员ID，value:复购级差收益）
                    Map<Long, BigDecimal> bonusIncomeMap = new HashMap<>();

                    List<SaOrderItemsExt> saOrderItemsExtList = rangeOrderMap.get(saOrderExt.getPkId());
                    for (SaOrderItemsExt saOrderItemsExt : saOrderItemsExtList) {
                        // 级别值比当前等级高的级差数据列表
                        Map<Integer, BigDecimal> itemsRangePriceMap = saOrderItemsExt.getWaresRangeTmpList().stream()
                                .collect(Collectors.toMap(WaresRangeTmp::getRangeValue, WaresRangeTmp::getRangePrice));

                        // 临时价格（跟着每一次变动）
                        BigDecimal tmpPrice = saOrderItemsExt.getPrice();
                        // 推荐人
                        long pkParent = sourceMemberRangeExt.getPkParent();
                        // 计算级差
                        while (true) {
                            // 推荐人
                            CuMemberRetailRangeExt targetMemberRangeExt = memberRangeExtMap.get(pkParent);
                            if (null == targetMemberRangeExt) {
                                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;
                            }
                            // 当前会员等级值
                            Integer calGradeValue = EAwards.getGradeValueByValue(targetMemberRangeExt.getGradeValue());
                            // 当前会员的级差价格
                            BigDecimal targetRangePrice = itemsRangePriceMap.get(calGradeValue);
                            if (targetRangePrice.compareTo(tmpPrice) < 0) {
                                // 当前级差价格比上一次的低
                                // 差价就是级差收益
                                BigDecimal bonusIncome;
                                if (bonusIncomeMap.containsKey(targetMemberRangeExt.getPkMember())) {
                                    bonusIncome = bonusIncomeMap.get(targetMemberRangeExt.getPkMember()).add(tmpPrice.subtract(targetRangePrice).multiply(new BigDecimal(saOrderItemsExt.getWaresQuantity())));
                                } else {
                                    bonusIncome = tmpPrice.subtract(targetRangePrice).multiply(new BigDecimal(saOrderItemsExt.getWaresQuantity()));
                                }

                                bonusIncomeMap.put(targetMemberRangeExt.getPkMember(), bonusIncome);
                                // 临时价格更新
                                tmpPrice = targetRangePrice;
                            }

                            // 最高等级则退出
                            if (calGradeValue == EGrade.S_VIP.getValue()) {
                                break;
                            }
                        }
                    }

                    if (bonusIncomeMap.size() > 0) {
                        for (Long key : bonusIncomeMap.keySet()) {
                            // 复购级差收益
                            BigDecimal rangeBonusIncome = bonusIncomeMap.get(key);
                            if (rangeBonusIncome.compareTo(BigDecimal.ZERO) > 0) {
                                CuMemberRetailRangeExt targetMemberRangeExt = memberRangeExtMap.get(key);
                                // 处理复购级差收益
                                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.REPURCHASE_RANGE_INCOME.getValue());
                                CuMemberBonusRange cuMemberBonusRange = getCuMemberRetailBonusRange(saOrderExt, targetMemberRangeExt, cuMemberBonus, pkBonusItems);
                                cuMemberBonusRange.setCalValue(BigDecimal.ZERO);
                                cuMemberBonusRange.setCalAchieve(saOrderExt.getOrderAmount());
                                cuMemberBonusRange.setPretaxIncome(rangeBonusIncome);
                                cuMemberBonusRange.setPkRange(targetMemberRangeExt.getPkGrade());
                                cuMemberBonusRange.setPkBeforeRange(sourceMemberRangeExt.getPkGrade());
                                cuMemberBonusRange.setPkOrder(saOrderExt.getPkId());
                                cuMemberBonusRange.setPkOrderItems(0L);
                                rangeRepurchaseRetailRemark(saOrderExt, cuMemberBonusRange, sourceMemberRangeExt, targetMemberRangeExt);
                                BdBonusDeduct bdBonusDeduct = setBonusDetailDeduct(bonusConfigDTO, cuMemberBonusRange, saOrderExt.getOrderAmount(), saOrderExt.getInExchangeRate());
                                if (EBonusIncomeStatus.NORMAL.getValue() == cuMemberBonusRange.getIncomeStatus()) {
                                    cuMemberBonus.setRepurRangeIncome(ComputeUtil.computeAdd(cuMemberBonus.getRepurRangeIncome(), cuMemberBonusRange.getPretaxIncome()));
                                    setRetailTotal(bdBonusDeduct, cuMemberBonus, cuMemberBonusRange);
                                }
                                memberBonusRangeList.add(cuMemberBonusRange);
                            }
                        }
                    }
                }
            }
        }
        return memberBonusRangeList;
    }

}
