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

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.hzs.bonus.achieve.mapper.CuMemberRetailRangeMapper;
import com.hzs.bonus.achieve.service.ICuMemberRetailRangeService;
import com.hzs.bonus.bonus.vo.BonusRecordDetailVO;
import com.hzs.bonus.detail.service.ICuMemberGradeService;
import com.hzs.bonus.order.service.IBonusOrderService;
import com.hzs.common.core.constant.MagicNumberConstants;
import com.hzs.common.core.constant.RetailConstants;
import com.hzs.common.core.constant.TableNameConstants;
import com.hzs.common.core.enums.*;
import com.hzs.common.core.utils.ComputeUtil;
import com.hzs.common.core.utils.DateUtils;
import com.hzs.common.domain.bonus.BdBonusDeduct;
import com.hzs.common.domain.member.achieve.ext.CuMemberRetailRangeExt;
import com.hzs.common.domain.member.bonus.*;
import com.hzs.common.domain.member.detail.CuMemberLevel;
import com.hzs.common.domain.member.detail.CuMemberServiceLog;
import com.hzs.common.domain.retail.member.CuMemberRetailRegion;
import com.hzs.common.domain.sale.ext.SaOrderExt;
import com.hzs.common.domain.sale.ext.SaOrderWaresExt;
import com.hzs.common.domain.sale.order.SaOrder;
import com.hzs.common.domain.system.config.BdGrade;
import com.hzs.member.base.IMemberServiceApi;
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 javax.annotation.Resource;
import java.math.BigDecimal;
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 IBonusOrderService iBonusOrderService;
    @Autowired
    private ICuMemberGradeService iCuMemberGradeService;

    @Resource
    private CuMemberRetailRangeMapper cuMemberRetailRangeMapper;

    @DubboReference
    ICuMemberServiceLogServiceApi iCuMemberServiceLogServiceApi;
    @DubboReference
    IMemberServiceApi iMemberServiceApi;

    /**
     * 秒结：
     * 首购级差、复购级差、复购配送（业绩、盒数、等级、奖衔、日奖）
     */
    List<CuMemberBonusRange> calculateCuMemberRetailRangeBonusBySecond(String settleDate, SaOrderExt saOrderExt, BonusConfigDTO bonusConfigDTO,
                                                                       int currentPeriod, Map<Long, CuMemberBonus> cuMemberBonusMap,
                                                                       List<CuMemberBonusDetail> cuMemberBonusDetailList) {
        // 直推、复购级差收益
        List<CuMemberBonusRange> cuMemberBonusRangeList = new ArrayList<>();

        // 按照血缘，查询该会员所有伞上会员 -- 不处理业绩等，直接查询会员表 cu_member
        List<CuMemberRetailRangeExt> memberRetailRangeExtList = iCuMemberRetailRangeService.getCuMemberRetailRangeParent(saOrderExt);
        // 会员结算map（key：会员ID，value：结算扩展）
        Map<Long, CuMemberRetailRangeExt> memberRangeExtMap = new HashMap<>();
        for (CuMemberRetailRangeExt cuMemberRetailRangeExt : memberRetailRangeExtList) {
            if (!memberRangeExtMap.containsKey(cuMemberRetailRangeExt.getPkMember())) {
                memberRangeExtMap.put(cuMemberRetailRangeExt.getPkMember(), cuMemberRetailRangeExt);
            }
        }

        // 配送收益配置
        Map<Integer, CuMemberRetailRegion> regionMap = iMemberServiceApi.listEffectiveRegion(DateUtils.parseStringToDate(settleDate)).getData();
        // 订单指定产品盒数
        BigDecimal boxNum = saOrderExt.getBoxNum();

        // 计算奖金 直推级差
        if ((EOrderType.RETAIL_REGISTER.getValue() == saOrderExt.getOrderType()
                || EOrderType.RETAIL_UPGRADE.getValue() == saOrderExt.getOrderType())
                && boxNum.compareTo(BigDecimal.ZERO) > 0
        ) {
            // 注册或升级订单并且存在盒数产品，才有 直推级差
            cuMemberBonusRangeList.addAll(calculateRetailRangeBonus(memberRangeExtMap, cuMemberBonusMap, bonusConfigDTO, currentPeriod, saOrderExt));
        } else if (EOrderType.RETAIL_REPURCHASE.getValue() == saOrderExt.getOrderType()) {
            // 复购订单
            if (boxNum.compareTo(BigDecimal.ZERO) > 0) {
                // 存在盒数商品，计算复购级差
                cuMemberBonusRangeList.addAll(calculateRetailRepurRangeBonus(memberRangeExtMap, cuMemberBonusMap,
                        bonusConfigDTO, currentPeriod, saOrderExt));
            }
            // 计算配送收益
            if (regionMap.size() != 0) {
                cuMemberBonusDetailList.addAll(calculateRetailRepurRegionBonus(memberRangeExtMap, cuMemberBonusMap,
                        bonusConfigDTO, currentPeriod, saOrderExt, regionMap, null, true));
            }
        }
        return cuMemberBonusRangeList;
    }

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

        List<SaOrderExt> retailOrderList = new ArrayList<>();
        // 新零售订单
        List<SaOrderExt> orderList = iBonusOrderService.queryRetailSaOrderByDay(settleStartDate, settleEndDate, null);
        for (SaOrderExt saOrderExt : orderList) {
            if (EOrderType.PICK_ORDER.getValue() == saOrderExt.getOrderType()) {
                // 提货订单不需要处理奖金相关
                continue;
            }
            if (saOrderExt.getDelFlag() == EYesNo.YES.getIntValue()) {
                retailOrderList.add(saOrderExt);
            }
        }

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

        // 更新网体
        iCuMemberRetailRangeService.mergeMemberRetailRangeByYesterday(settleEndDate, rangeTableName, yesterdayRangeTableName, isSameMonth);
        // 更新会员手动升级
        iCuMemberGradeService.updateCuMemberManualGrade(rangeTableName, period);

        // 当期的手动激活的记录列表
        List<CuMemberServiceLog> activateList = this.getActivateList(settleStartDate);

        if (retailOrderList.size() > 0) {
            // 会员购买升级记录
            Map<Long, CuMemberLevel> memberLevelMap = new HashMap<>();
            List<CuMemberLevel> memberLevelList = iCuMemberGradeService.queryCuMemberLevel(settleStartDate, settleEndDate);
            memberLevelList.forEach(cuMemberLevel -> memberLevelMap.put(cuMemberLevel.getPkOrder(), cuMemberLevel));

            // 会员的自动升级记录
            Map<Long, CuMemberLevel> autoLevelMap = new HashMap<>();
            List<CuMemberLevel> autoLevelList = iCuMemberGradeService.listAutoLevel(settleStartDate, settleEndDate);
            autoLevelList.forEach(tmpLevel -> autoLevelMap.put(tmpLevel.getPkOrder(), tmpLevel));

            Map<Long, Date> activateMap = new HashMap<>();
            if (CollectionUtil.isNotEmpty(activateList)) {
                activateMap = activateList.stream()
                        .collect(Collectors.groupingBy(
                                CuMemberServiceLog::getPkMember,
                                Collectors.collectingAndThen(
                                        Collectors.minBy(Comparator.comparing(CuMemberServiceLog::getCreationTime)),
                                        optional -> optional.get().getCreationTime()
                                )
                        ));
            }

            // 会员结算map（key：会员ID，value：结算扩展）
            Map<Long, CuMemberRetailRangeExt> memberRangeExtMap = new HashMap<>();
            // 按照血缘，查询该会员所有伞上会员
            List<CuMemberRetailRangeExt> memberRetailRangeExtList = iCuMemberRetailRangeService.queryCuMemberRetailRangeParent(rangeTableName, retailOrderList);
            // 结算会员map处理
            for (CuMemberRetailRangeExt cuMemberRetailRangeExt : memberRetailRangeExtList) {
                if (!memberRangeExtMap.containsKey(cuMemberRetailRangeExt.getPkMember())) {
                    memberRangeExtMap.put(cuMemberRetailRangeExt.getPkMember(), cuMemberRetailRangeExt);
                }
            }

            // 等级map（key:等级ID，value:等级对象）
            Map<Integer, BdGrade> gradeIdMap = new HashMap<>();
            // 等级列表
            List<BdGrade> retailGradeList = bonusConfigDTO.getRetaiGradeList();
            for (BdGrade bdGrade : retailGradeList) {
                gradeIdMap.put(bdGrade.getPkId(), bdGrade);
            }
            // 配送收益配置
            Map<Integer, CuMemberRetailRegion> regionMap = iMemberServiceApi.listEffectiveRegion(settleStartDate).getData();

            // 直推、复购级差收益
            List<CuMemberBonusRange> cuMemberBonusRangeList = new ArrayList<>();
            // 复购配送收益
            List<CuMemberBonusDetail> cuMemberBonusDetailList = new ArrayList<>();

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

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

                // 订单指定产品盒数（计算等级使用）
                BigDecimal boxNum = saOrderExt.getBoxNum();
                // 个人累计消费pv
                BigDecimal orderAchieve = saOrderExt.getOrderAchieve();
                // 个人累计消费金额
                BigDecimal orderAmount = saOrderExt.getOrderAmount();
                // 复购、重消，盒数、业绩算个人累计数据（盒数、业绩）
                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.setNewConsumeAmount(ComputeUtil.computeAdd(sourceMemberRangeExt.getNewConsumeAmount(), orderAmount));
                sourceMemberRangeExt.setConsumeAmount(ComputeUtil.computeAdd(sourceMemberRangeExt.getConsumeAmount(), orderAmount));
                sourceMemberRangeExt.setMonthConsumeAmount(ComputeUtil.computeAdd(sourceMemberRangeExt.getMonthConsumeAmount(), orderAmount));
                if (EOrderType.RETAIL_REPURCHASE.getValue() == saOrderExt.getOrderType()) {
                    // 复购
                    sourceMemberRangeExt.setMonthRepBoxNum(ComputeUtil.computeAdd(sourceMemberRangeExt.getMonthRepBoxNum(), boxNum));
                    sourceMemberRangeExt.setMonthRepConsumePv(ComputeUtil.computeAdd(sourceMemberRangeExt.getMonthRepConsumePv(), orderAchieve));
                    sourceMemberRangeExt.setMonthRepConsumeAmount(ComputeUtil.computeAdd(sourceMemberRangeExt.getMonthRepConsumeAmount(), orderAmount));
                }
                if (EYesNo.NO.getIntValue() == sourceMemberRangeExt.getEnableStatus()
                        && activateMap.containsKey(sourceMemberRangeExt.getPkMember())) {
                    // 存在手动激活
                    sourceMemberRangeExt.setEnableStatus(EYesNo.YES.getIntValue());
                }
                // 计算团队业绩、盒数
                calculateRetailRangeGradeAwards(memberRangeExtMap, saOrderExt, boxNum, activateMap);

                // 计算奖金 直推级差
                if ((EOrderType.RETAIL_REGISTER.getValue() == saOrderExt.getOrderType()
                        || EOrderType.RETAIL_UPGRADE.getValue() == saOrderExt.getOrderType())
                        && boxNum.compareTo(BigDecimal.ZERO) > 0
                ) {
                    // 注册或升级订单并且存在盒数产品，才有 直推级差
                    cuMemberBonusRangeList.addAll(calculateRetailRangeBonus(memberRangeExtMap, cuMemberBonusMap, bonusConfigDTO, period, 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());
                            }
                        }
                    }
                    // 订单存在自动升级记录（高级店主、区域董事处理）
                    if (autoLevelMap.containsKey(saOrderExt.getPkId())) {
                        CuMemberLevel cuMemberLevel = autoLevelMap.get(saOrderExt.getPkId());
                        if (gradeIdMap.containsKey(cuMemberLevel.getNewLevel())) {
                            BdGrade bdGrade = gradeIdMap.get(cuMemberLevel.getNewLevel());
                            CuMemberRetailRangeExt tmpMemberRetailRange = memberRangeExtMap.get(cuMemberLevel.getPkMember());
                            if (bdGrade.getGradeValue() > tmpMemberRetailRange.getGradeValue()) {
                                tmpMemberRetailRange.setPkGrade(bdGrade.getPkId());
                                tmpMemberRetailRange.setGradeValue(bdGrade.getGradeValue());
                                tmpMemberRetailRange.setGradeName(bdGrade.getGradeName());
                            }
                        }
                    }
                } else if (EOrderType.RETAIL_REPURCHASE.getValue() == saOrderExt.getOrderType()) {
                    // 复购订单
                    if (boxNum.compareTo(BigDecimal.ZERO) > 0) {
                        // 存在盒数商品，计算复购级差
                        cuMemberBonusRangeList.addAll(calculateRetailRepurRangeBonus(memberRangeExtMap, cuMemberBonusMap,
                                bonusConfigDTO, period, saOrderExt));
                    }
                    // 计算配送收益
                    if (regionMap.size() != 0) {
                        cuMemberBonusDetailList.addAll(calculateRetailRepurRegionBonus(memberRangeExtMap, cuMemberBonusMap,
                                bonusConfigDTO, period, saOrderExt, regionMap, rangeTableName, false));
                    }
                }
            }

            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);
                }
            }
            // 更新网体
            iCuMemberRetailRangeService.updateCuMemberRetailRange(rangeTableName, memberRangeExtMap);
        } else {
            // 当日没有订单，也需要处理手动激活
            if (CollectionUtil.isNotEmpty(activateList)) {
                List<Long> pkMemberList = activateList.stream().map(CuMemberServiceLog::getPkMember).collect(Collectors.toList());
                iCuMemberRetailRangeService.updateMemberEnable(rangeTableName, pkMemberList);
            }
        }
    }

    /**
     * 累计团队盒数、业绩等
     */
    public void calculateRetailRangeGradeAwards(Map<Long, CuMemberRetailRangeExt> memberRangeExtMap, SaOrderExt saOrderExt,
                                                BigDecimal boxNum, Map<Long, Date> activateMap) {
        // 订单会员
        CuMemberRetailRangeExt sourceMemberRangeExt = memberRangeExtMap.get(saOrderExt.getPkMember());
        // 订单会员的推荐人
        CuMemberRetailRangeExt targetMemberRangeExt = memberRangeExtMap.get(sourceMemberRangeExt.getPkParent());

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

            // 激活的账号才能累计业绩和盒数（有注册、升级订单）
            if (targetMemberRangeExt.getEnableStatus() == EYesNo.YES.getIntValue()) {
                // 累计金额
                targetMemberRangeExt.setTeamNewAmount(ComputeUtil.computeAdd(targetMemberRangeExt.getTeamNewAmount(), orderAmount));
                targetMemberRangeExt.setTeamConsumeAmount(ComputeUtil.computeAdd(targetMemberRangeExt.getTeamConsumeAmount(), orderAmount));
                targetMemberRangeExt.setTeamMonthAmount(ComputeUtil.computeAdd(targetMemberRangeExt.getTeamMonthAmount(), orderAmount));
                // 累计业绩
                targetMemberRangeExt.setTeamNewPv(ComputeUtil.computeAdd(targetMemberRangeExt.getTeamNewPv(), orderAchieve));
                targetMemberRangeExt.setTeamConsumePv(ComputeUtil.computeAdd(targetMemberRangeExt.getTeamConsumePv(), orderAchieve));
                targetMemberRangeExt.setTeamMonthPv(ComputeUtil.computeAdd(targetMemberRangeExt.getTeamMonthPv(), orderAchieve));
                // 累计盒数
                targetMemberRangeExt.setTeamNewBoxNum(targetMemberRangeExt.getTeamNewBoxNum().add(boxNum));
                targetMemberRangeExt.setTeamBoxNum(targetMemberRangeExt.getTeamBoxNum().add(boxNum));
                targetMemberRangeExt.setTeamMonthBoxNum(targetMemberRangeExt.getTeamMonthBoxNum().add(boxNum));
            }
            targetMemberRangeExt = memberRangeExtMap.get(targetMemberRangeExt.getPkParent());
        }
    }

    /**
     * 计算直推级差收益
     */
    List<CuMemberBonusRange> calculateRetailRangeBonus(Map<Long, CuMemberRetailRangeExt> memberRangeExtMap, Map<Long, CuMemberBonus> cuMemberBonusMap,
                                                       BonusConfigDTO bonusConfigDTO, Integer period, SaOrderExt saOrderExt) {
        // 直推级差返回数据
        List<CuMemberBonusRange> memberBonusRangeList = new ArrayList<>();

        // 订单下单人自己
        CuMemberRetailRangeExt sourceMemberRangeExt = memberRangeExtMap.get(saOrderExt.getPkMember());
        // 推荐人
        long pkParent = sourceMemberRangeExt.getPkParent();
        // 2025.08.21 需要修改：累计升级制，按订单金额以及等级对应比例拿直推级差
        // 订单金额
        BigDecimal orderAmount = saOrderExt.getOrderAmount();
        if (null == orderAmount || orderAmount.compareTo(BigDecimal.ZERO) == 0) {
            log.warn("订单 {} 金额为0", saOrderExt.getOrderCode());
            return memberBonusRangeList;
        }

        // 前一个会员等级
        int beforeGradeValue = 0;
        // 前面累计奖金
        BigDecimal totalBonus = BigDecimal.ZERO;
        // 平级合伙人数量
        int v3Count = 1;
        // 计算直推级差
        while (true) {
            // 上一次处理的是公司等级，则结束退出
            if (beforeGradeValue == EGrade.COMPANY.getValue()) {
                break;
            }
            // 推荐人 - 当前处理会员
            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;
            }
            // 当前会员等级值
            int targetGradeValue = targetMemberRangeExt.getGradeValue();
            // 直推级差收益
            BigDecimal rangeBonusIncome = BigDecimal.ZERO;

            if (EGrade.HAI_FAN.getValue() == targetGradeValue && targetGradeValue > beforeGradeValue) {
                // 推荐人是 会员
                rangeBonusIncome = orderAmount.multiply(RetailConstants.RECOMMEND_HAI_FAN).setScale(4, BigDecimal.ROUND_HALF_UP);
                // 已经算完级差等级的累计奖金
                totalBonus = totalBonus.add(rangeBonusIncome);
                // 前一级会员等级
                beforeGradeValue = targetGradeValue;
            } else if (EGrade.YOU_KE.getValue() == targetGradeValue && targetGradeValue > beforeGradeValue) {
                // 推荐人是 VIP
                rangeBonusIncome = orderAmount.multiply(RetailConstants.RECOMMEND_YOU_KE).subtract(totalBonus).setScale(4, BigDecimal.ROUND_HALF_UP);
                // 已经算完级差等级的累计奖金
                totalBonus = totalBonus.add(rangeBonusIncome);
                // 前一级会员等级
                beforeGradeValue = targetGradeValue;
            } else if (EGrade.MAKER.getValue() == targetGradeValue && targetGradeValue >= beforeGradeValue) {
                // 推荐人是 合伙人
                if (v3Count == 1) {
                    rangeBonusIncome = orderAmount.multiply(RetailConstants.RECOMMEND_MAKER_1).subtract(totalBonus).setScale(4, BigDecimal.ROUND_HALF_UP);
                } else if (v3Count == 2) {
                    rangeBonusIncome = orderAmount.multiply(RetailConstants.RECOMMEND_MAKER_2).subtract(totalBonus).setScale(4, BigDecimal.ROUND_HALF_UP);
                } else if (v3Count == 3) {
                    rangeBonusIncome = orderAmount.multiply(RetailConstants.RECOMMEND_MAKER_3).subtract(totalBonus).setScale(4, BigDecimal.ROUND_HALF_UP);
                }
                v3Count++;
                // 已经算完级差等级的累计奖金
                totalBonus = totalBonus.add(rangeBonusIncome);
                // 前一级会员等级
                beforeGradeValue = targetGradeValue;
            } else if (EGrade.VIP.getValue() == targetGradeValue && targetGradeValue > beforeGradeValue) {
                // 推荐人是 博羚店主
                rangeBonusIncome = orderAmount.multiply(RetailConstants.RECOMMEND_VIP).subtract(totalBonus).setScale(4, BigDecimal.ROUND_HALF_UP);
                // 已经算完级差等级的累计奖金
                totalBonus = totalBonus.add(rangeBonusIncome);
                // 前一级会员等级
                beforeGradeValue = targetGradeValue;
            } else if (EGrade.S_VIP.getValue() == targetGradeValue && targetGradeValue > beforeGradeValue) {
                // 推荐人是 高级店主
                rangeBonusIncome = orderAmount.multiply(RetailConstants.RECOMMEND_S_VIP).subtract(totalBonus).setScale(4, BigDecimal.ROUND_HALF_UP);
                // 已经算完级差等级的累计奖金
                totalBonus = totalBonus.add(rangeBonusIncome);
                // 前一级会员等级
                beforeGradeValue = targetGradeValue;
            } else if (EGrade.REGION.getValue() == targetGradeValue && targetGradeValue > beforeGradeValue) {
                // 推荐人是 区域代理
                rangeBonusIncome = orderAmount.multiply(RetailConstants.RECOMMEND_REGION).subtract(totalBonus).setScale(4, BigDecimal.ROUND_HALF_UP);
                // 已经算完级差等级的累计奖金
                totalBonus = totalBonus.add(rangeBonusIncome);
                // 前一级会员等级
                beforeGradeValue = targetGradeValue;
            } else if (EGrade.DIRECTOR.getValue() == targetGradeValue && targetGradeValue > beforeGradeValue) {
                // 推荐人是 董事代理
                rangeBonusIncome = orderAmount.multiply(RetailConstants.RECOMMEND_DIRECTOR).subtract(totalBonus).setScale(4, BigDecimal.ROUND_HALF_UP);
                // 已经算完级差等级的累计奖金
                totalBonus = totalBonus.add(rangeBonusIncome);
                // 前一级会员等级
                beforeGradeValue = targetGradeValue;
            } else if (EGrade.COMPANY.getValue() == targetGradeValue && targetGradeValue > beforeGradeValue) {
                // 推荐人是 总公司
                rangeBonusIncome = orderAmount.multiply(RetailConstants.RECOMMEND_COMPANY).subtract(totalBonus).setScale(4, BigDecimal.ROUND_HALF_UP);
                // 已经算完级差等级的累计奖金
                totalBonus = totalBonus.add(rangeBonusIncome);
                // 前一级会员等级
                beforeGradeValue = targetGradeValue;
            }

            if (rangeBonusIncome.compareTo(BigDecimal.ZERO) > 0) {
                // 处理直推级差收益
                // 会员奖金
                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(saOrderExt.getOrderAmount());
                cuMemberBonusRange.setPretaxIncome(rangeBonusIncome);
                cuMemberBonusRange.setPkRange(targetMemberRangeExt.getPkGrade());
                cuMemberBonusRange.setPkBeforeRange(sourceMemberRangeExt.getPkGrade());
                cuMemberBonusRange.setPkOrder(saOrderExt.getPkId());
                cuMemberBonusRange.setPkOrderItems(0L);
                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);
            }
        }
        return memberBonusRangeList;
    }

    /**
     * 计算复购级差收益
     */
    List<CuMemberBonusRange> calculateRetailRepurRangeBonus(Map<Long, CuMemberRetailRangeExt> memberRangeExtMap, Map<Long, CuMemberBonus> cuMemberBonusMap,
                                                            BonusConfigDTO bonusConfigDTO, Integer period, SaOrderExt saOrderExt) {
        // 直推级差返回数据
        List<CuMemberBonusRange> memberBonusRangeList = new ArrayList<>();

        // 订单下单人自己
        CuMemberRetailRangeExt sourceMemberRangeExt = memberRangeExtMap.get(saOrderExt.getPkMember());
        // 推荐人
        long pkParent = sourceMemberRangeExt.getPkParent();
        // 商品盒数
        BigDecimal boxNum = saOrderExt.getBoxNum();

        // 2025.08.13 添加分公司级差收益，每1盒（4个产品）第一分公司4元，第二分公司4元，公司6元，总拨出14元
        int branch = 0;

        // 前一个会员等级
        int beforeGradeValue = 0;
        // 前面累计奖金
        BigDecimal totalBonus = BigDecimal.ZERO;
        // 平级合伙人数量
        int v3Count = 1;
        // 计算直推级差
        while (true) {
            // 上一次处理的是公司等级，则结束退出
            if (beforeGradeValue == EGrade.COMPANY.getValue()) {
                break;
            }
            // 推荐人
            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;
            }
            // 当前会员等级值
            int targetGradeValue = targetMemberRangeExt.getGradeValue();

            // 复购级差收益
            BigDecimal rangeBonusIncome = BigDecimal.ZERO;

            if (targetGradeValue > beforeGradeValue) {
                // 当前等级大于之前等级
                if (EGrade.HAI_FAN.getValue() == targetGradeValue) {
                    // V1 拿 6
                    rangeBonusIncome = RetailConstants.REPURCHASE_V1.multiply(boxNum);
                    // 前面累计的奖金
                    totalBonus = totalBonus.add(RetailConstants.REPURCHASE_V1).multiply(boxNum);
                } else if (EGrade.YOU_KE.getValue() == targetGradeValue) {
                    // V2 拿 8，或者减去之前累计
                    rangeBonusIncome = RetailConstants.REPURCHASE_V2.multiply(boxNum).subtract(totalBonus);
                    // 前面累计的奖金
                    totalBonus = totalBonus.add(RetailConstants.REPURCHASE_V2.multiply(boxNum).subtract(totalBonus));
                } else if (EGrade.MAKER.getValue() == targetGradeValue) {
                    // V3 拿 10，或者减去之前累计
                    rangeBonusIncome = RetailConstants.REPURCHASE_V3_1.multiply(boxNum).subtract(totalBonus);
                    // 前面累计的奖金
                    totalBonus = totalBonus.add(RetailConstants.REPURCHASE_V3_1.multiply(boxNum).subtract(totalBonus));
                } else if (EGrade.VIP.getValue() == targetGradeValue) {
                    // V4 拿 20，或者减去之前累计
                    rangeBonusIncome = RetailConstants.REPURCHASE_V4.multiply(boxNum).subtract(totalBonus);
                    // 前面累计的奖金
                    totalBonus = totalBonus.add(RetailConstants.REPURCHASE_V4.multiply(boxNum).subtract(totalBonus));
                } else if (EGrade.S_VIP.getValue() == targetGradeValue) {
                    // V5 拿 20.8，或者减去之前累计
                    rangeBonusIncome = RetailConstants.REPURCHASE_V5.multiply(boxNum).subtract(totalBonus);
                    // 前面累计的奖金
                    totalBonus = totalBonus.add(RetailConstants.REPURCHASE_V5.multiply(boxNum).subtract(totalBonus));
                } else if (EGrade.REGION.getValue() == targetGradeValue
                        || EGrade.DIRECTOR.getValue() == targetGradeValue) {
                    // V6、V7 拿 22，或者减去之前累计
                    rangeBonusIncome = RetailConstants.REPURCHASE_V6_V7.multiply(boxNum).subtract(totalBonus);
                    // 前面累计的奖金
                    totalBonus = totalBonus.add(RetailConstants.REPURCHASE_V6_V7.multiply(boxNum).subtract(totalBonus));
                } else if (EGrade.COMPANY.getValue() == targetGradeValue) {
                    // V8 拿 24，或者减去之前累计
                    rangeBonusIncome = RetailConstants.REPURCHASE_V8.multiply(boxNum).subtract(totalBonus);
                    // 前面累计的奖金
                    totalBonus = totalBonus.add(RetailConstants.REPURCHASE_V8.multiply(boxNum).subtract(totalBonus));
                }
                // 前一级会员等级
                beforeGradeValue = targetGradeValue;
            } else if (EGrade.MAKER.getValue() == beforeGradeValue
                    && EGrade.MAKER.getValue() == targetGradeValue) {
                // 之前和现在都是合伙人，处理平级
                if (v3Count == 1) {
                    // V3第一平级 推拿 12，或者减去之前累计
                    rangeBonusIncome = RetailConstants.REPURCHASE_V3_2.multiply(boxNum).subtract(totalBonus);
                    // 前面累计的奖金
                    totalBonus = totalBonus.add(RetailConstants.REPURCHASE_V3_2.multiply(boxNum).subtract(totalBonus));
                    v3Count++;
                } else if (v3Count == 2) {
                    // V3第二平级 推拿 13，或者减去之前累计
                    rangeBonusIncome = RetailConstants.REPURCHASE_V3_3.multiply(boxNum).subtract(totalBonus);
                    // 前面累计的奖金
                    totalBonus = totalBonus.add(RetailConstants.REPURCHASE_V3_3.multiply(boxNum).subtract(totalBonus));
                    v3Count++;
                }
            }

            if (rangeBonusIncome.compareTo(BigDecimal.ZERO) > 0) {
                // 处理复购级差收益
                // 会员奖金
                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_REPURCHASE_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);
                rangeRepurRetailRemark(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);
            }

            // 2025.08.13 添加 代理 级差收益，每1盒（4个产品）区域代理4元，董事代理4元，公司6元，总拨出14元
            if ((EGrade.REGION.getValue() == targetMemberRangeExt.getGradeValue()
                    || EGrade.DIRECTOR.getValue() == targetMemberRangeExt.getGradeValue())
                    && branch < 2) {
                // 等级是分公司 并且 发放次数小于2
                this.calculateRetailRepurCompanyRangeBonus(sourceMemberRangeExt, targetMemberRangeExt, cuMemberBonusMap, bonusConfigDTO,
                        period, saOrderExt, boxNum, memberBonusRangeList, branch);
                branch++;
            } else if (EGrade.COMPANY.getValue() == targetGradeValue && branch != 3) {
                // 等级是总公司
                this.calculateRetailRepurCompanyRangeBonus(sourceMemberRangeExt, targetMemberRangeExt, cuMemberBonusMap, bonusConfigDTO,
                        period, saOrderExt, boxNum, memberBonusRangeList, branch);
                branch = 3;
            }
        }
        return memberBonusRangeList;
    }

    private void calculateRetailRepurCompanyRangeBonus(CuMemberRetailRangeExt sourceMemberRangeExt, CuMemberRetailRangeExt targetMemberRangeExt,
                                                       Map<Long, CuMemberBonus> cuMemberBonusMap, BonusConfigDTO bonusConfigDTO, Integer period,
                                                       SaOrderExt saOrderExt, BigDecimal boxNum, List<CuMemberBonusRange> memberBonusRangeList,
                                                       int branch) {
        // 2025.08.13 二级代理，一级总公司复购级差
        BigDecimal calValue = BigDecimal.ZERO;
        if (EGrade.REGION.getValue() == targetMemberRangeExt.getGradeValue()
                || EGrade.DIRECTOR.getValue() == targetMemberRangeExt.getGradeValue()) {
            // 分公司奖金
            calValue = RetailConstants.BRANCH;
        } else if (EGrade.COMPANY.getValue() == targetMemberRangeExt.getGradeValue()) {
            // 总公司奖金 = 总拨出奖金 - （分公司奖金 * 分公司数量）
            calValue = RetailConstants.COMPANY_TOTAL.subtract(RetailConstants.BRANCH.multiply(new BigDecimal(branch)));
        }
        BigDecimal bonusIncome = calValue.multiply(boxNum);

        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_REPURCHASE_INCOME.getValue());
        // 会员级差
        CuMemberBonusRange cuMemberBonusRange = getCuMemberRetailBonusRange(saOrderExt, targetMemberRangeExt, cuMemberBonus, pkBonusItems);
        cuMemberBonusRange.setCalAchieve(saOrderExt.getOrderAmount());
        cuMemberBonusRange.setCalValue(calValue);
        cuMemberBonusRange.setPretaxIncome(bonusIncome);
        cuMemberBonusRange.setPkRange(targetMemberRangeExt.getPkGrade());
        cuMemberBonusRange.setPkBeforeRange(sourceMemberRangeExt.getPkGrade());
        cuMemberBonusRange.setPkOrder(saOrderExt.getPkId());
        cuMemberBonusRange.setPkOrderItems(0L);
        rangeRepurRetailRemark(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);
    }

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


    /**
     * 计算复购配送区域收益
     */
    List<CuMemberBonusDetail> calculateRetailRepurRegionBonus(Map<Long, CuMemberRetailRangeExt> memberRangeExtMap, Map<Long, CuMemberBonus> cuMemberBonusMap,
                                                              BonusConfigDTO bonusConfigDTO, Integer period, SaOrderExt saOrderExt, Map<Integer, CuMemberRetailRegion> regionMap,
                                                              String rangeTableName, boolean secondFlag) {
        // 复购配送区域返回数据
        List<CuMemberBonusDetail> memberBonusDetailList = new ArrayList<>();

        // 订单下单人自己
        CuMemberRetailRangeExt sourceMemberRangeExt = memberRangeExtMap.get(saOrderExt.getPkMember());
        // 配送区域配置
        CuMemberRetailRegion retailRegion = regionMap.get(saOrderExt.getRecCounty());
        if (null != retailRegion) {
            CuMemberRetailRangeExt targetMemberRangeExt = memberRangeExtMap.get(retailRegion.getPkMember());
            if (ObjectUtil.isEmpty(targetMemberRangeExt)) {
                if (secondFlag) {
                    // 秒结处理
                    targetMemberRangeExt = cuMemberRetailRangeMapper.getMemberRetailRange(retailRegion.getPkMember());
                } else {
                    // 非秒结处理
                    targetMemberRangeExt = cuMemberRetailRangeMapper.queryCuMemberRetailRangeByMemberId(rangeTableName, retailRegion.getPkMember());
                }
                if (null == targetMemberRangeExt) {
                    // 配送区域对应的会员不存在了，直接跳过
                    return memberBonusDetailList;
                }
                memberRangeExtMap.put(retailRegion.getPkMember(), targetMemberRangeExt);
            }
            // 复购配送区域收益
            BigDecimal bonusIncome = BigDecimal.ZERO;

            List<Integer> pkWaresList = new ArrayList<>();
            for (SaOrderWaresExt saOrderWaresExt : saOrderExt.getOrderWaresExtList()) {
                if (!pkWaresList.contains(saOrderWaresExt.getPkWares())) {
                    // 商品没有处理过，则进行处理
                    pkWaresList.add(saOrderWaresExt.getPkWares());
                    // 复购区分收益 * 商品数量
                    bonusIncome = bonusIncome.add(saOrderWaresExt.getAreaIncome().multiply(new BigDecimal(saOrderWaresExt.getWaresQuantity())));
                }
            }

            if (bonusIncome.compareTo(BigDecimal.ZERO) > 0) {
                // 处理复购级差收益
                // 会员奖金
                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_REPURCHASE_DELIVERY_INCOME.getValue());
                // 会员配送区域收益
                CuMemberBonusDetail cuMemberBonusDetail = getCuMemberBonusDetail(saOrderExt, targetMemberRangeExt, cuMemberBonus, pkBonusItems);
                cuMemberBonusDetail.setCalValue(BigDecimal.ZERO);
                cuMemberBonusDetail.setCalAchieve(BigDecimal.ZERO);
                cuMemberBonusDetail.setPretaxIncome(bonusIncome);
                cuMemberBonusDetail.setPkOrder(saOrderExt.getPkId());
                // 备注
                regionRepurRetailRemark(saOrderExt, cuMemberBonusDetail, sourceMemberRangeExt, targetMemberRangeExt);
                BdBonusDeduct bdBonusDeduct = setBonusDetailDeduct(bonusConfigDTO, cuMemberBonusDetail, saOrderExt.getOrderAmount(), saOrderExt.getInExchangeRate());
                if (EBonusIncomeStatus.NORMAL.getValue() == cuMemberBonusDetail.getIncomeStatus()) {
                    cuMemberBonus.setRetailAreaIncome(ComputeUtil.computeAdd(cuMemberBonus.getRetailAreaIncome(), cuMemberBonusDetail.getPretaxIncome()));
                    setRetailTotal(bdBonusDeduct, cuMemberBonus, cuMemberBonusDetail);
                }
                memberBonusDetailList.add(cuMemberBonusDetail);
            }
        }
        return memberBonusDetailList;
    }

    private CuMemberBonusDetail getCuMemberBonusDetail(SaOrder saOrderExt, CuMemberRetailRangeExt targetMemberRangeExt,
                                                       CuMemberBonus cuMemberBonus, Integer pkBonusItems) {
        CuMemberBonusDetail cuMemberBonusDetail = CuMemberBonusDetail.builder()
                .pkOrder(saOrderExt.getPkId())
                .pkBonusItems(pkBonusItems)
                .pkBonus(cuMemberBonus.getPkId())
                .incomeStatus(targetMemberRangeExt.getIncomeStatus())
                .calAchieve(saOrderExt.getOrderAchieve())
                .calType(ECalType.VALUE.getValue())
                .calValue(BigDecimal.ZERO)
                .pretaxIncome(BigDecimal.ZERO)
                .incomeTax(BigDecimal.ZERO)
                .realIncome(BigDecimal.ZERO)
                .incomeRatio(BigDecimal.ZERO)
                .incomeDialRatio(BigDecimal.ZERO)
                .orderDialRatio(BigDecimal.ZERO)
                .build();
        cuMemberBonusDetail.setPkCountry(targetMemberRangeExt.getPkSettleCountry());
        cuMemberBonusDetail.setPkCreator(MagicNumberConstants.PK_ADMIN);
        return cuMemberBonusDetail;
    }


    /**
     * 获取手动激活List
     *
     * @param settleStartDate
     * @return
     */
    private List<CuMemberServiceLog> getActivateList(Date settleStartDate) {
        // 当期的手动激活的记录列表
        return iCuMemberServiceLogServiceApi.listActivateLog(settleStartDate).getData();
    }
}
