
package com.tmerclub.cloud.distribution.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.tmerclub.cloud.api.distribution.bo.DistributionNotifyOrderAndShopBO;
import com.tmerclub.cloud.api.distribution.bo.DistributionSpuBO;
import com.tmerclub.cloud.api.distribution.vo.DistributionSpuVO;
import com.tmerclub.cloud.api.multishop.bo.ShopWalletBO;
import com.tmerclub.cloud.api.order.feign.OrderFeignClient;
import com.tmerclub.cloud.api.payment.constant.PaySysType;
import com.tmerclub.cloud.api.platform.feign.ConfigFeignClient;
import com.tmerclub.cloud.api.platform.vo.DistributionConfigApiVO;
import com.tmerclub.cloud.common.constant.Constant;
import com.tmerclub.cloud.common.constant.DistributionAudit;
import com.tmerclub.cloud.common.exception.LuckException;
import com.tmerclub.cloud.common.order.bo.PayNotifyBO;
import com.tmerclub.cloud.common.order.constant.OrderType;
import com.tmerclub.cloud.common.order.vo.OrderItemVO;
import com.tmerclub.cloud.common.order.vo.OrderVO;
import com.tmerclub.cloud.common.response.ResponseEnum;
import com.tmerclub.cloud.common.response.ServerResponseEntity;
import com.tmerclub.cloud.common.rocketmq.config.RocketMqConstant;
import com.tmerclub.cloud.common.util.Arith;
import com.tmerclub.cloud.common.util.BeanUtil;
import com.tmerclub.cloud.common.util.PriceUtil;
import com.tmerclub.cloud.distribution.constant.*;
import com.tmerclub.cloud.distribution.model.*;
import com.tmerclub.cloud.distribution.service.*;
import com.tmerclub.cloud.distribution.constant.*;
import com.tmerclub.cloud.distribution.model.*;
import com.tmerclub.cloud.distribution.service.*;
import com.tmerclub.cloud.distribution.vo.DistributionAwardDataVO;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.rocketmq.client.producer.SendStatus;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.support.GenericMessage;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author cl
 * @date 2021-08-18 08:40:26
 */
@Service
public class DistributionOrderServiceImpl implements DistributionOrderService {

    private static final Logger logger = LoggerFactory.getLogger(DistributionOrderServiceImpl.class);

    @Autowired
    private DistributionUserService distributionUserService;
    @Autowired
    private DistributionUserBindService distributionUserBindService;
    @Autowired
    private DistributionConfigService distributionConfigService;
    @Autowired
    private DistributionUserWalletService distributionUserWalletService;
    @Autowired
    private DistributionUserWalletBillService distributionUserWalletBillService;
    @Autowired
    private DistributionUserIncomeService distributionUserIncomeService;
    @Autowired
    private DistributionSpuService distributionSpuService;
    @DubboReference
    private OrderFeignClient orderFeignClient;
    @Autowired
    private RocketMQTemplate distributionNotifyOrderShopTemplate;
    @DubboReference
    private ConfigFeignClient configFeignClient;


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void payNotifyDistributionOrder(PayNotifyBO payNotifyBO) {
        // OrderNotifyConsumer 通知来源类
        // 获取分销设置
        DistributionConfigApiVO distributionConfig = distributionConfigService.getDistributionConfig();
        if (Objects.isNull(distributionConfig) || !Objects.equals(1, distributionConfig.getDistributionSwitch())) {
            logger.info("分销未开启，结束分销");
            return;
        }
        // 获取订单数据
        List<Long> orderIds = payNotifyBO.getOrderIds();
        ServerResponseEntity<List<OrderVO>> orderResponseEntity = orderFeignClient.listOrderAndOrderItemByOrderIds(orderIds);
        if (!orderResponseEntity.isSuccess()) {
            logger.error(orderResponseEntity.getMsg());
            throw new LuckException(orderResponseEntity.getMsg());
        }
        List<OrderVO> esOrderList = orderResponseEntity.getData();
        if (CollUtil.isEmpty(esOrderList)) {
            logger.info("未查询到对应的订单，结束分销 orderIds： {}", orderIds.toString());
            return;
        }
        // 过滤掉shopId = 0的订单，以及积分订单（分销订单不包含积分订单）
        List<OrderVO> orders = esOrderList.stream()
                .filter(item -> !Objects.equals(item.getShopId(), Constant.PLATFORM_SHOP_ID)
                        && !Objects.equals(item.getOrderType(), OrderType.SCORE.value()))
                .collect(Collectors.toList());
        if (CollUtil.isEmpty(orders)) {
            logger.info("没有可以进行分销的订单，结束分销 orderIds： {}", orderIds.toString());
            return;
        }
        // 获取订所有的订单项
        List<OrderItemVO> orderItems = new ArrayList<>(Constant.INITIAL_CAPACITY);
        orders.forEach(item -> orderItems.addAll(item.getOrderItems()));
        // 订单所有的商品
        if (CollUtil.isEmpty(orderItems)) {
            logger.info("未获取到订单项，停止分销");
            return;
        }
        List<Long> spuIds = orderItems.stream().map(OrderItemVO::getSpuId).collect(Collectors.toList());
        // 查询出上架的所有分销商品信息（如何有商品没有在分销活动中上架，那么此商品就不进行分销）
        List<DistributionSpu> distributionSpuList = distributionSpuService.getByStateAndSpuIds(DistributionSpuStatus.PUT_SHELF.value(), spuIds);
        if (CollUtil.isEmpty(distributionSpuList)) {
            logger.info("未获取到订单商品，停止分销");
            return;
        }
        // 开始进行处理订单分销
        handleDistributionOrder(distributionConfig, orders, distributionSpuList);
    }

    private void handleDistributionOrder(DistributionConfigApiVO distributionConfig, List<OrderVO> orders, List<DistributionSpu> distributionSpuList) {
        // 设置为分销的订单项
        List<OrderItemVO> allDistributionOrderItems = new ArrayList<>(Constant.INITIAL_CAPACITY);
        List<Long> spuIds = distributionSpuList.stream().map(DistributionSpu::getSpuId).collect(Collectors.toList());
        List<ShopWalletBO> shopWalletBOList = new ArrayList<>(Constant.INITIAL_CAPACITY);
        for (OrderVO order : orders) {
            // 所有的订单项
            List<OrderItemVO> orderItems = order.getOrderItems();
            boolean isFirstGetBindUser = true;
            DistributionUser oldDistributionUser = null;
            long distributionAumont = 0L;
            List<OrderItemVO> orderItemList = new ArrayList<>(Constant.INITIAL_CAPACITY);
            List<OrderItemVO> distributionOrderItemList = new ArrayList<>(Constant.INITIAL_CAPACITY);
            for (OrderItemVO orderItem : orderItems) {
                // 如果没有状态正常的分销商品则不能进行分销
                if (!spuIds.contains(orderItem.getSpuId())) {
                    continue;
                }
                // 用分销流水来保存幂等
                int row = distributionUserIncomeService.countByOrderIdAndOrderItemId(order.getOrderId(), orderItem.getOrderItemId(), null);
                if (row > 0) {
                    continue;
                }
                // 如果该订单项有分销信息，则将该订单项放入distributionOrderItems中
                if (Objects.nonNull(orderItem.getDistributionUserId()) && !Objects.equals(orderItem.getDistributionUserId(), 0L)) {
                    doDistribution(oldDistributionUser, order, orderItem, distributionConfig);
                    allDistributionOrderItems.add(orderItem);
                    distributionOrderItemList.add(orderItem);
                    continue;
                }
                // 初始化用户的旧绑定分销员
                if (isFirstGetBindUser) {
                    isFirstGetBindUser = false;
                    // 查询该用户以前绑定的分享人
                    DistributionUserBind distributionUserBind = distributionUserBindService.getUserBindByUserIdAndState(order.getUserId(), BindStateEnum.VALID.value());
                    // 并且该用户以前也没有绑定分享人
                    if (distributionUserBind != null) {
                        // 查询以前的绑定的用户信息
                        oldDistributionUser = distributionUserService.getByDistributionUserId(distributionUserBind.getDistributionUserId());
                    }
                }
                if (Objects.isNull(oldDistributionUser)) {
                    continue;
                }
                if (!Objects.equals(oldDistributionUser.getState(), DistributionUserStateEnum.NORMAL.value())) {
                    continue;
                }
                // 将订单项设为分销项
                orderItem.setDistributionUserId(oldDistributionUser.getDistributionUserId());
                doDistribution(oldDistributionUser, order, orderItem, distributionConfig);
                orderItemList.add(orderItem);
                distributionAumont = distributionAumont + orderItem.getDistributionAmount();
            }
            // 该订单中没有分销订单项，不需要进行后面的步骤
            if (CollUtil.isEmpty(orderItemList) && CollUtil.isEmpty(distributionOrderItemList)) {
                continue;
            }
            allDistributionOrderItems.addAll(orderItemList);
            order.setDistributionAmount(distributionAumont);
            // 分销订单需要在商家的未结算金额扣除用户分销金额
            // 我们需要发一个top来同时更新商家店铺钱包和订单项分销金额, 那么这里需要批量更新了
            ShopWalletBO shopWalletBO = new ShopWalletBO();
            shopWalletBO.setShopId(order.getShopId());
            shopWalletBO.setOrderId(order.getOrderId());
            // 订单分销金额
            List<OrderItemVO> filterOrderItems = allDistributionOrderItems.stream().filter(item -> Objects.equals(item.getOrderId(), order.getOrderId())).toList();
            ServerResponseEntity<Long> orderResponse = orderFeignClient.sumTotalDistributionAmountByOrderItem(filterOrderItems);
            if (!orderResponse.isSuccess()) {
                logger.error(orderResponse.getMsg());
                throw new LuckException(orderResponse.getMsg());
            }
            long totalDistributionAmount = orderResponse.getData();
            // 商家待结算改变金额 = - 订单分销佣金 （商家待结算金额 = 商家待结算金额 - 订单分销佣金）
            shopWalletBO.setUnsettledAmount(-totalDistributionAmount);
            shopWalletBOList.add(shopWalletBO);
        }
        sendMsgSubUnSettleAmount(allDistributionOrderItems, shopWalletBOList);
    }

    private void sendMsgSubUnSettleAmount(List<OrderItemVO> allDistributionOrderItems, List<ShopWalletBO> shopWalletBOList) {
        // 发送消息, 去修改订单分销金额和店铺钱包待结算金额
        DistributionNotifyOrderAndShopBO message = new DistributionNotifyOrderAndShopBO();
        message.setDistributionOrderItems(allDistributionOrderItems);
        message.setShopWalletBOList(shopWalletBOList);
        SendStatus sendStatus = distributionNotifyOrderShopTemplate.syncSend(RocketMqConstant.DISTRIBUTION_NOTIFY_ORDER_SHOP_TOPIC, new GenericMessage<>(message)).getSendStatus();
        if (!Objects.equals(sendStatus, SendStatus.SEND_OK)) {
            // 消息发不出去就抛异常
            throw new LuckException(ResponseEnum.EXCEPTION);
        }
    }


    /**
     * 进行分销操作
     *
     * @param oldShareUser       用户已绑定的分销员
     * @param order
     * @param orderItem          订单项
     * @param distributionConfig 分销设置
     */
    private void doDistribution(DistributionUser oldShareUser, OrderVO order, OrderItemVO orderItem, DistributionConfigApiVO distributionConfig) {
        DistributionUser shareUser;
        DistributionUser bindUser;

        if (oldShareUser != null && Objects.equals(orderItem.getDistributionUserId(), oldShareUser.getDistributionUserId())) {
            shareUser = oldShareUser;
            bindUser = oldShareUser;
        } else {
            shareUser = distributionUserService.getByDistributionUserId(orderItem.getDistributionUserId());
            // 判断是否可以进行分销操作
            if (checkAmountOver(orderItem)) {
                return;
            }
            // 自推不进行绑定
            if (Objects.equals(orderItem.getUserId(), shareUser.getUserId())) {
                return;
            }
            // 绑定绑定销售员信息
            ServerResponseEntity<DistributionUser> serverResponse = distributionUserBindService.bindDistribution(shareUser, orderItem.getUserId(), 1);
            if (!serverResponse.isSuccess()) {
                logger.info("绑定销售员信息失败，跳过分销流程,订单号：{}, 订单项Id：{}", order.getOrderId(), orderItem.getOrderItemId());
            }
            // 绑定的用户
            bindUser = serverResponse.getData();
        }
        //推广人若为永久封禁
        if (Objects.equals(shareUser.getState(), DistributionUserStateEnum.PER_BAN.value()) || Objects.equals(shareUser.getState(), DistributionUserStateEnum.BAN.value())) {
            logger.info("推广员已被暂时封禁或永久封禁");
            return;
        }
        // 添加收入流水记录并将收入添加到待结算金额到钱包中
        createIncomeByOrderItem(distributionConfig, order, shareUser, bindUser, orderItem);
    }

    /**
     * 创建订单项收入记录添加待结算金额到钱包中
     *
     * @param distributionConfig 分销配置
     * @param order              订单
     * @param shareUser          分销员
     * @param bindUser           绑定的分销员
     * @param orderItem          订单项
     */
    private void createIncomeByOrderItem(DistributionConfigApiVO distributionConfig, OrderVO order, DistributionUser shareUser, DistributionUser bindUser, OrderItemVO orderItem) {
        //判断是否会产生分销业绩
        if (Objects.isNull(bindUser) && Objects.isNull(shareUser)) {
            logger.error("没有分享人，没有关系人，不产生业绩");
            return;
        }
        // 获取该分销商品的设置数据
        DistributionSpuVO distributionSpuVo = distributionSpuService.getBySpuId(orderItem.getSpuId());
        DistributionSpuBO distributionSpuBO = BeanUtil.map(distributionSpuVo, DistributionSpuBO.class);

        // 这件商品原本是分销商品被加入了购物车，后来又不是了
        if (distributionSpuBO == null) {
            return;
        } else {
            distributionSpuBO.setShopId(orderItem.getShopId());
            // 计算佣金，用实付金额计算
            distributionSpuBO.setPrice(orderItem.getActualTotal());
        }
        //定义一个最终的业绩归属人变量
        DistributionUser finalDistributionUser;

        //判断是分享人优先还是关系链优先 0 允许绑定,关系优先,1,不绑定 分享人优先
        if (distributionConfig.getAttribution() == 0) {
            //关系链优先
            logger.info("关系链优先,关系人获得业绩");
            finalDistributionUser = bindUser;
        } else {
            //分享人优先
            logger.info("分享人优先,分享人获得业绩");
            finalDistributionUser = shareUser;
        }
        if (finalDistributionUser == null) {
            logger.info("没有找到业绩归属者");
            return;
        }
        // 判断是否可以进行分销操作
        if (checkAmountOver(orderItem)) {
            return;
        }
        Integer paySysType = configFeignClient.getPaySysType().getData();
        if (Objects.isNull(paySysType)) {
            paySysType = PaySysType.DEFAULT.value();
        }
        DistributionUserIncome distributionUserIncome = new DistributionUserIncome();
        distributionUserIncome.setPaySysType(paySysType);
        distributionUserIncome.setOrderId(order.getOrderId());
        distributionUserIncome.setOrderItemId(orderItem.getOrderItemId());
        // 如果系统设置为交易完毕后结算，则记录为结算状态，否则为未结算状态
        distributionUserIncome.setState(DistributionUserIncomeStateEnum.UN_COMMISSION.value());
        distributionUserIncome.setShopId(orderItem.getShopId());
        distributionUserIncome.setSpuId(orderItem.getSpuId());
        //计算佣金金额
        DistributionAwardDataVO distributionAwardDataVO = getAwardDataVO(distributionSpuBO, orderItem);
        //创建插入业绩记录对象
//        if (!Objects.equals(distributionAwardDataVO.getAwardNumber(), Constant.ZERO_LONG)) {
        // 直推奖励
        insertAwardNumber(orderItem, finalDistributionUser, distributionAwardDataVO, distributionUserIncome);
//        } else {
//            logger.info("默认奖励为0，不结算");
//        }
        //是否开启了上级奖励(0 关闭 1开启)
        if (!Objects.equals(distributionSpuBO.getParentAwardSet(), 1)) {
            logger.info("没有开启上级奖励");
            return;
        }
        //获取上级id
        if (Objects.isNull(finalDistributionUser.getParentId()) && Objects.equals(distributionConfig.getAttribution(), 0)) {
            logger.info("无法获取推广员的上级id");
            return;
        }
        if (Arith.isEquals(distributionAwardDataVO.getParentAwardNumber(), 0.0)) {
            logger.info("商品上级奖励为0，不结算");
            return;
        }
        logger.info("进入上级奖励流程");
        // 间推奖励
        insertParentAwardNumber(orderItem, finalDistributionUser, bindUser, distributionAwardDataVO, distributionUserIncome);

    }

    private void insertParentAwardNumber(OrderItemVO orderItem, DistributionUser finalDistributionUser, DistributionUser bindUser,
                                         DistributionAwardDataVO distributionAwardDataVO, DistributionUserIncome distributionUserIncome) {
        if (Objects.isNull(finalDistributionUser.getParentId())) {
            logger.info("分销员id-{}：没有上级，不进行间推分销处理", finalDistributionUser.getDistributionUserId());
            return;
        }
        // 添加二级佣金给上级邀请人
        DistributionUserWallet parentDistributionUserWallet = distributionUserWalletService.getByDistributionUserId(finalDistributionUser.getParentId());
        if (Objects.isNull(parentDistributionUserWallet)) {
            logger.info("分销员id-{}：没有钱包信息", finalDistributionUser.getParentId());
            return;
        }
        // 如果上级不为空,则创建上级奖励业绩记录
        distributionUserIncome.setIncomeId(null);
        //类型为二级奖励
        distributionUserIncome.setIncomeType(DistributionUserIncomeTypeEnum.AWARD_TWO.value());
        distributionUserIncome.setDistributionUserId(parentDistributionUserWallet.getDistributionUserId());
        distributionUserIncome.setIncomeAmount(distributionAwardDataVO.getParentAwardNumber());
        distributionUserIncome.setWalletId(parentDistributionUserWallet.getWalletId());
        distributionUserIncome.setUserId(orderItem.getUserId());
        // 若佣金大于实付金额改收入改为失效订单
        setDistributionIncome(orderItem, distributionAwardDataVO, distributionUserIncome, 2);

        distributionUserIncomeService.save(distributionUserIncome);

        if (distributionUserIncome.getState().equals(DistributionUserIncomeStateEnum.UN_COMMISSION.value())) {
            //给邀请人钱包增加待结算金额
            parentDistributionUserWallet.setUnsettledAmount(parentDistributionUserWallet.getUnsettledAmount() + distributionAwardDataVO.getParentAwardNumber());
            //增加钱包流水记录
            if (distributionAwardDataVO.getParentAwardNumber() != 0) {
                distributionUserWalletBillService.save(new DistributionUserWalletBill(parentDistributionUserWallet, "间推奖励", "Second-generation rewards", distributionAwardDataVO.getParentAwardNumber(), 0L, 0L, 0L, 0));
            }
            // 订单项添加上级奖励
            orderItem.setDistributionParentAmount(distributionUserIncome.getIncomeAmount());
        } else {
            logger.info("增加失效佣金");
            //给邀请人钱包增加失效金额
            parentDistributionUserWallet.setInvalidAmount(parentDistributionUserWallet.getInvalidAmount() + distributionUserIncome.getIncomeAmount());
            //增加钱包流水记录
            if (distributionAwardDataVO.getParentAwardNumber() != 0) {
                distributionUserWalletBillService.save(new DistributionUserWalletBill(parentDistributionUserWallet, "间推奖励失效", "Intermittent bonuses are void", 0L, 0L, distributionUserIncome.getIncomeAmount(), 0L, 0));
            }
            //佣金失效后，订单中分销金额要清除（如果不清除，失效的分销金额会插入到订单项中，就参与了订单金额的计算）
            orderItem.setDistributionParentAmount(0L);
        }
        // 更新邀请人钱包 给钱包增加待结算金额
        if (distributionUserWalletService.updateWalletAmount(parentDistributionUserWallet) < 1) {
            // 更新推广员钱包信息失败
            throw new LuckException("更新推广员钱包信息失败");
        }
    }

    /**
     * 直推奖励
     *
     * @param orderItem               订单项
     * @param finalDistributionUser   分销员
     * @param distributionAwardDataVO 奖励参数
     * @param distributionUserIncome  收入参数
     */
    private void insertAwardNumber(OrderItemVO orderItem, DistributionUser finalDistributionUser, DistributionAwardDataVO distributionAwardDataVO, DistributionUserIncome distributionUserIncome) {
        // 查询该推广员钱包信息
        DistributionUserWallet distributionUserWallet = distributionUserWalletService.getByDistributionUserId(finalDistributionUser.getDistributionUserId());
        distributionUserIncome.setDistributionUserId(finalDistributionUser.getDistributionUserId());
        distributionUserIncome.setWalletId(distributionUserWallet.getWalletId());
        distributionUserIncome.setIncomeAmount(distributionAwardDataVO.getAwardNumber());
        distributionUserIncome.setUserId(orderItem.getUserId());
        // 若佣金大于实付金额改收入改为失效订单
        setDistributionIncome(orderItem, distributionAwardDataVO, distributionUserIncome, 1);

        // 收入类型为一级奖励
        distributionUserIncome.setIncomeType(DistributionUserIncomeTypeEnum.AWARD_ONE.value());
        distributionUserIncomeService.save(distributionUserIncome);

        // 订单项添加分佣奖励
        orderItem.setDistributionAmount(distributionUserIncome.getIncomeAmount());

        if (distributionUserIncome.getState().equals(DistributionUserIncomeStateEnum.UN_COMMISSION.value())) {
            // 给钱包增加待结算金额
            distributionUserWallet.setUnsettledAmount(distributionUserWallet.getUnsettledAmount() + distributionAwardDataVO.getAwardNumber());
            distributionUserWalletBillService.save(new DistributionUserWalletBill(distributionUserWallet, "客户支付获取待结算金额", "Customer payment to obtain the amount to be settled", distributionAwardDataVO.getAwardNumber(), 0L, 0L, 0L, 0));
        } else {
            logger.info("增加失效佣金");
            // 给钱包增加待失效金额
            distributionUserWallet.setInvalidAmount(distributionUserWallet.getInvalidAmount() + distributionUserIncome.getIncomeAmount());
            if (distributionUserIncome.getIncomeAmount() != 0) {
                distributionUserWalletBillService.save(new DistributionUserWalletBill(distributionUserWallet, "客户支付小于佣金失效增加金额", "The client pays less than the increase in commission lapse", 0L, 0L, distributionUserIncome.getIncomeAmount(), 0L, 0));
            }
            // 佣金失效后，订单中分销金额要清除（如果不清除，失效的分销金额会插入到订单项中，就参与了订单金额的计算）
            orderItem.setDistributionAmount(0L);
        }
        // 给钱包增加待结算金额
        if (distributionUserWalletService.updateWalletAmount(distributionUserWallet) < 1) {
            // 更新推广员钱包信息失败
            throw new LuckException("更新推广员钱包信息失败");
        }
    }

    /**
     * 检查分销金额是否超出订单项金额
     *
     * @param orderItem
     * @return
     */
    private boolean checkAmountOver(OrderItemVO orderItem) {
        // 获取该分销商品的设置数据
        DistributionSpuVO distributionSpuVo = distributionSpuService.getBySpuId(orderItem.getSpuId());
        DistributionSpuBO distributionSpuBO = BeanUtil.map(distributionSpuVo, DistributionSpuBO.class);
        // 这件商品原本是分销商品被加入了购物车，后来又不是了
        if (distributionSpuBO == null) {
            return true;
        } else {
            distributionSpuBO.setShopId(orderItem.getShopId());
            // 计算佣金，用实付金额计算
            distributionSpuBO.setPrice(orderItem.getActualTotal());
        }
        return false;
    }

    /**
     * 根据分销商品设置、分享人id，计算奖励数据
     *
     * @param distributionSpuBO 分销商品
     * @param orderItem         订单项
     * @return
     */
    private DistributionAwardDataVO getAwardDataVO(DistributionSpuBO distributionSpuBO, OrderItemVO orderItem) {
        DistributionAwardDataVO distributionAwardDataVO = new DistributionAwardDataVO();
        distributionAwardDataVO.setAwardNumber(Constant.ZERO_LONG);
        distributionAwardDataVO.setParentAwardNumber(Constant.ZERO_LONG);
        // distributionConfig
        // 奖励比例或数额
        distributionAwardDataVO.setAwardMode(distributionSpuBO.getAwardMode());
        if (Objects.isNull(distributionSpuBO.getAwardMode())) {
            return distributionAwardDataVO;
        }
        // 上级奖励设置(0 关闭 1开启)
        Integer parentAwardSet = distributionSpuBO.getParentAwardSet();
        Long price = distributionSpuBO.getPrice();
        BigDecimal awardNumbers = new BigDecimal(distributionSpuBO.getAwardNumbers().toString());
        BigDecimal parentAwardNumbers = new BigDecimal(distributionSpuBO.getParentAwardNumbers().toString());
        // 如果计算为按比例计算，则转化为具体金额
        if (Objects.equals(distributionAwardDataVO.getAwardMode(), 0)) {
            // 根据商品价格,计算得到的佣金 订单实际金额 * (奖励金额 / 100) 奖励比例
            // DistributionSpu.awardNumbers 查看解释，这个比例还需要除以100（awardNumbers = 1 则实际的奖励比例为 0.01%）
            awardNumbers = awardNumbers
                    .divide(new BigDecimal(PriceUtil.ONE_HUNDRED), 2, RoundingMode.HALF_UP)
                    .divide(new BigDecimal(PriceUtil.ONE_HUNDRED), 4, RoundingMode.HALF_UP);
            // 订单实际金额 * 奖励比例
            long awardAmount = new BigDecimal(price.toString())
                    .multiply(awardNumbers)
                    .longValue();
            distributionAwardDataVO.setAwardNumber(awardAmount);
            // 查看是否开启邀请人奖励 订单实际金额 * (奖励金额 / 100) 奖励比例
            if (Objects.equals(1, parentAwardSet)) {
                // 邀请人奖励
                // DistributionSpu.parentAwardNumbers 查看解释，这个比例还需要除以100（parentAwardNumbers = 1 则实际的奖励比例为 0.01%）
                parentAwardNumbers = parentAwardNumbers
                        .divide(new BigDecimal(PriceUtil.ONE_HUNDRED), 2, RoundingMode.HALF_UP)
                        .divide(new BigDecimal(PriceUtil.ONE_HUNDRED), 4, RoundingMode.HALF_UP);
                // 订单实际金额 * 奖励比例
                long parentAwardNumber = new BigDecimal(price.toString())
                        .multiply(parentAwardNumbers)
                        .longValue();
                distributionAwardDataVO.setParentAwardNumber(parentAwardNumber);
            }
        } else {
            // 按照固定值奖励
            distributionAwardDataVO.setAwardNumber(awardNumbers.multiply(new BigDecimal(orderItem.getCount())).longValue());
            if (Objects.equals(1, parentAwardSet)) {
                distributionAwardDataVO.setParentAwardNumber(parentAwardNumbers.multiply(new BigDecimal(orderItem.getCount())).longValue());
            }
        }
        return distributionAwardDataVO;
    }


    /**
     * 实付金额小于佣金，修改收入订单为失效
     *
     * @param orderItem
     * @param distributionAwardDataVO
     * @param distributionUserIncome
     * @param type                    1直推 2间推
     */
    private void setDistributionIncome(OrderItemVO orderItem, DistributionAwardDataVO distributionAwardDataVO, DistributionUserIncome distributionUserIncome, int type) {
        // 计算出商家这个订单项收入的金额，因为商家的营销活动不可能会负收入，所以在小于分销的金额时，改为失效订单
        long changeAmount = orderItem.getActualTotal() + orderItem.getPlatformShareReduce() - orderItem.getPlatformCommission() - orderItem.getItemPurchaseAmount();
        if (type == DistributionAmountEnum.DIRECT_PUSH.value()) {
            if (distributionAwardDataVO.getAwardNumber() >= changeAmount) {
                logger.info("直推 分销金额比实付金额要大，分销佣金收入记录改为失效订单");
                distributionUserIncome.setState(DistributionUserIncomeStateEnum.INVALID.value());
                distributionUserIncome.setReson(DistributionAudit.INCOME_ONE.value());
                return;
            }
        } else if (type == DistributionAmountEnum.INTERPENETRATION.value()) {
            if ((distributionAwardDataVO.getAwardNumber() + distributionAwardDataVO.getParentAwardNumber()) >= changeAmount) {
                logger.info("间推 分销金额比实付金额要大，分销佣金收入记录改为失效订单");
                distributionUserIncome.setState(DistributionUserIncomeStateEnum.INVALID.value());
                distributionUserIncome.setReson(DistributionAudit.INCOME_ONE.value());
                return;
            }
        }

        double incomeAmount = Arith.round(distributionUserIncome.getIncomeAmount(), 2);
        // 分销佣金小于0.01
        if (incomeAmount < Constant.MIN_SPU_AMOUNT) {
            if (Objects.nonNull(distributionUserIncome.getReson())) {
                return;
            }
            distributionUserIncome.setIncomeAmount(Constant.ZERO_LONG);
            distributionUserIncome.setReson(DistributionAudit.INCOME_THREE.value());
            distributionUserIncome.setState(DistributionUserIncomeStateEnum.INVALID.value());
            return;
        }
        // 如果系统设置为交易完毕后结算，则记录为结算状态，否则为未结算状态
        distributionUserIncome.setState(1);
        distributionUserIncome.setReson(0);
    }
}
