package com.buy507.mall.portal.service.impl;


import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONUtil;
import com.buy507.mall.mapper.*;
import com.buy507.mall.model.*;
import com.buy507.mall.portal.service.MemberCommissionService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
public class MemberSplitProfitService{

    @Resource
    private UmsMemberMapper memberMapper;
    /**
     * 会员分成流水
     */
    @Resource
    private UmsMemberAccountTransactionMapper umsMemberAccountTransactionMapper;
    /**
     * 订单队列
     */
    @Resource
    private UmsMemberOrderQueueMapper umsMemberOrderQueueMapper;

    /**
     * 会员上下关系
     */
    @Resource
    private UmsMemberRelationTreeMapper umsMemberRelationTreeMapper;
    /**
     * 会员等级
     */
    @Resource
    private UmsMemberLevelMapper umsMemberLevelMapper;

    /**
     * 计算会员等级升级
     */
    @Resource
    private MemberCommissionService memberCommissionService;


    @Value("${becomeVipAmount}")
    private String becomeVipAmount;

    @Value("${sameLevelProfit}")
    private String sameLevelProfit;

    public void updateOderAndMemberInfo(OmsOrder order) {

        UmsMember member = memberMapper.selectByPrimaryKey(order.getMemberId());
        //找到上级会员
        UmsMember higherLevelMember = this.findInOrderQueueMember(member.getId());;
        /**
         * 先验证该订单是否是五联单加速，如果不是则普通计算上级提成
         * 如果是提成，则全额给上级
         */
        boolean splitForFiveQueue = fiveQuickQueueBusiness(order, member, higherLevelMember);
        log.info("aqaq01");
        //未进行满5联单分润，开始进行普通分润流程
        if(!splitForFiveQueue && higherLevelMember != null){
            //进行订单分润
            this.splitProfitFroMember(member, higherLevelMember, order);
        }
        log.info("aqaq02");
        //计算会员等级
        UmsMemberRelationTree  relationTree = this.getUpLevelRelationTreeById(member.getId());
        if(relationTree == null){
            return;
        }
        log.info("aqaq03");
        //上级为空或者为普通用户
        UmsMember higherMember = memberMapper.selectByPrimaryKey(relationTree.getHigherLevelId());
        if(higherMember == null && higherMember.getMemberLevel().equals(MemberLevel.Member)){
            return;
        }
        memberCommissionService.computeCommission(higherMember);

    }


    /**
     * 为订单上级进行分润
     * @param member
     * @param higherLevelMember
     * @param order
     */
    private void splitProfitFroMember(UmsMember member, UmsMember higherLevelMember, OmsOrder order) {

        //新订单及直属上级分润,返回的分润金额
        BigDecimal revenueAmount = this.newMemberSplitProfit(member, higherLevelMember, order);
        //退出排队逻辑
        this.quitOrderQueue(order);

        UmsMember moreHigherMember;
        //如果上级是vip会员
        if(higherLevelMember.getMemberLevel().equals(MemberLevel.Consumer)) {
            moreHigherMember = this.findNextHigherLevelMemberByType(higherLevelMember.getId(), MemberLevel.Consumer);
        }else {
            moreHigherMember = this.findInOrderQueueMember(higherLevelMember.getId());
        }
        //没有更高的上级退出分润
        if(moreHigherMember == null){
            return;
        }
        //给三个级别代理分润
        this.twoLevelSplitProfit(higherLevelMember, moreHigherMember, order, revenueAmount);

        this.threeLevelSplitProfit(higherLevelMember, moreHigherMember, order, revenueAmount);

        this.fourLevelSplitProfit(higherLevelMember, moreHigherMember, order, revenueAmount);
    }


    private static Integer FIVE_MODE = 5;

    /**
     * 处理退出队列
     * @param order
     */
    private void quitOrderQueue(OmsOrder order) {
        //目前公排多少订单正在排队
        UmsMemberOrderQueueExample example1 = new UmsMemberOrderQueueExample();
        example1.createCriteria().andQuitQueueMarkEqualTo(UmsMemberOrderQueue.QUEUE_STATUS_WAIT).andQueueTypeEqualTo(UmsMemberOrderQueue.QUEUE_TYPE_ORDINARY);
        long allQueue = umsMemberOrderQueueMapper.countByExample(example1);


        //目前已经多少订单在公排上出局
        UmsMemberOrderQueueExample example2 = new UmsMemberOrderQueueExample();
        example2.createCriteria().andQuitQueueMarkEqualTo(UmsMemberOrderQueue.QUEUE_STATUS_QUIT).andQueueTypeEqualTo(UmsMemberOrderQueue.QUEUE_TYPE_ORDINARY);
        long allQuitQueue = umsMemberOrderQueueMapper.countByExample(example2);
        if(allQueue != 0){
            long count = FIVE_MODE*(allQuitQueue+1);
            long outIndex = allQueue % count; //mcoo
            if(outIndex > 0){
                return;
            }
            //获取目前公排未出局的首位订单
            List<UmsMemberOrderQueue> QueueList = umsMemberOrderQueueMapper.selectByExample(example1);
            UmsMemberOrderQueue orderQueue = QueueList.get(0);

            //此订单出局逻辑
            if(orderQueue != null){
                UmsMemberOrderQueueExample memberOrder = new UmsMemberOrderQueueExample();
                memberOrder.createCriteria().andQueueTypeEqualTo(UmsMemberOrderQueue.QUEUE_STATUS_WAIT).andMemberIdEqualTo(order.getMemberId());
                long memberOrderCount = umsMemberOrderQueueMapper.countByExample(memberOrder);
                UmsMember member = memberMapper.selectByPrimaryKey(orderQueue.getMemberId());
                if(memberOrderCount == 1){ //当前该用户如果只有一个排单 排队状态状态置为0
                    member.setOrderStatus(0);
                }
                member.setBalance(orderQueue.getOrderAmount().add(member.getBalance()));
                memberMapper.updateByPrimaryKey(member);

                orderQueue.setQuitQueueMark(UmsMemberOrderQueue.QUEUE_STATUS_QUIT);
                umsMemberOrderQueueMapper.updateByPrimaryKeySelective(orderQueue);
                UmsMemberAccountTransaction accountTransaction = new UmsMemberAccountTransaction();
                accountTransaction.setCommissionRatio(100);
                accountTransaction.setMemberId(member.getId());
                accountTransaction.setOrderId(orderQueue.getOrderId()); //mcoo  order.getId() 是退款给首位 而不是目前此订单
                accountTransaction.setRemarks("会员此订单退出队列到账");
                accountTransaction.setRevenueAmount(orderQueue.getOrderAmount());
                accountTransaction.setTransferPaymentTime(DateUtil.date());
                accountTransaction.setFlowType(1);
                umsMemberAccountTransactionMapper.insert(accountTransaction);

                //出局后订单状态置为2
                OmsOrder order1 = orderMapper.selectByPrimaryKey(orderQueue.getOrderId());
                order1.setDeleteStatus(2);
                orderMapper.updateByPrimaryKey(order1);
            }
        }

    }


    /**
     * 查询到下一个级别的上级会员
     * @param id
     * @param consumer
     * @return
     */
    private UmsMember findNextHigherLevelMemberByType(Long id, MemberLevel consumer) {
        //找到上级
        UmsMember moreHigherMember = this.findInOrderQueueMember(id);
        if(moreHigherMember == null){
            return null;
        }
        while (moreHigherMember != null){
            if(moreHigherMember.getMemberLevel().getValue() > consumer.getValue()){
                return moreHigherMember;
            }
            moreHigherMember = this.findInOrderQueueMember(moreHigherMember.getId());
            if(moreHigherMember == null){
                return null;
            }
        }
        return moreHigherMember;
    }

    @Autowired
    private OmsOrderMapper orderMapper;

    /***
     * 五联单排队分红逻辑，该订单支付后处理
     **/
    private boolean fiveQuickQueueBusiness(OmsOrder order, UmsMember member, UmsMember higherLevelMember) {
        //分润标识
        boolean splitMark = false;
        if(higherLevelMember != null){

            //查看上级所有排队订单
            UmsMemberOrderQueueExample higherQueueExample = new UmsMemberOrderQueueExample();
            higherQueueExample.createCriteria()
                    .andQuitQueueMarkEqualTo(UmsMemberOrderQueue.QUEUE_STATUS_WAIT)
                    .andMemberIdEqualTo(higherLevelMember.getId());

            List<UmsMemberOrderQueue> higherQueueList = umsMemberOrderQueueMapper.selectByExample(higherQueueExample); //上级排单

            //上级是否有加速单 higherQueue
            if(higherQueueList != null && !higherQueueList.isEmpty()){
                UmsMemberOrderQueue higherQueue = null;
                for (UmsMemberOrderQueue higherOrder: higherQueueList) {
                    if(UmsMemberOrderQueue.QUEUE_TYPE_FAST.equals(higherOrder.getQueueType())){ //mcoo
                        higherQueue = higherOrder;
                        break;
                    }
                }

                //如果没有加速单 退出
                if(higherQueue != null){
                    return splitMark;
                }

                //查找上级还有多少下级（查看同级别的用户）
                UmsMemberRelationTreeExample umrtExample = new UmsMemberRelationTreeExample();
                umrtExample.createCriteria().andHigherLevelIdEqualTo(higherLevelMember.getId());
                List<UmsMemberRelationTree>  memberRelationTreeList = umsMemberRelationTreeMapper.selectByExample(umrtExample);
                if(!memberRelationTreeList.isEmpty()) {
                    List<Long> teamIdList = memberRelationTreeList.stream().map(UmsMemberRelationTree::getMemberId).collect(Collectors.toList());
                    //订单加入队列
                    UmsMemberOrderQueueExample orderQueueExample = new UmsMemberOrderQueueExample();
                    orderQueueExample.createCriteria()
                            .andQuitQueueMarkEqualTo(UmsMemberOrderQueue.QUEUE_STATUS_WAIT)
                            .andAccelerateSwitchGreaterThan(UmsMemberOrderQueue.ACCELERATE_SWITCH_NO)
                            .andMemberIdIn(teamIdList);

                    //同级用户的排单
                    List<UmsMemberOrderQueue> orderQueueList = umsMemberOrderQueueMapper.selectByExample(orderQueueExample);

                    //此处整理出首单新用户（加速单出局是需要首次消费用户才能给上级加速）
                    if(orderQueueList != null) {
                        for (UmsMemberOrderQueue orderQueue : orderQueueList) {
                            UmsMemberOrderQueueExample orderQueueExample1 = new UmsMemberOrderQueueExample();
                            orderQueueExample1.createCriteria().andMemberIdEqualTo(orderQueue.getMemberId());
                            long memberOrderCount = umsMemberOrderQueueMapper.countByExample(orderQueueExample1);
                            if (memberOrderCount != 1) {
                                orderQueueList.remove(orderQueue);
                            }

                        }
                    }

                    //上级订单队列中是否有加速5联单
                    if(!orderQueueList.isEmpty()){
                        if(orderQueueList.size() >= 4){
                            if(higherQueueList.size() == 1){
                                higherLevelMember.setOrderStatus(0);
                            }
                            //上级加速单出局
                            higherLevelMember.setBalance(higherLevelMember.getBalance().add(higherQueue.getOrderAmount()));
                            //更新数据库
                            memberMapper.updateByPrimaryKeySelective(higherLevelMember);
                            higherQueue.setQuitQueueMark(UmsMemberOrderQueue.QUEUE_STATUS_QUIT);
                            umsMemberOrderQueueMapper.updateByPrimaryKeySelective(higherQueue);

                            UmsMemberAccountTransaction accountTransaction = new UmsMemberAccountTransaction();
                            accountTransaction.setCommissionRatio(100);
                            accountTransaction.setMemberId(higherQueue.getMemberId());
                            accountTransaction.setOrderId(higherQueue.getOrderId());
                            accountTransaction.setRemarks("满五单加速流水");
                            accountTransaction.setRevenueAmount(higherQueue.getOrderAmount());
                            //即时到账
                            accountTransaction.setTransferPaymentTime(DateUtil.date());
                            accountTransaction.setFlowType(1);
                            umsMemberAccountTransactionMapper.insert(accountTransaction);

                            //快速出局后将订单状态置为2
                            OmsOrder order1 = orderMapper.selectByPrimaryKey(higherQueue.getOrderId());
                            order1.setDeleteStatus(2);
                            orderMapper.updateByPrimaryKey(order1);

                            //更新这5个订单帮助上级加速成功的为已加速
                            for (int i = 0; i < 5; i++) {
                                UmsMemberOrderQueue orderQueue = orderQueueList.get(i);
                                orderQueue.setAccelerateSwitch(UmsMemberOrderQueue.ACCELERATE_SWITCH_YES);
                                umsMemberOrderQueueMapper.updateByPrimaryKeySelective(orderQueue);
                            }

                            //订单加入队列
                            orderQueueExample = new UmsMemberOrderQueueExample();
                            long allQueue = umsMemberOrderQueueMapper.countByExample(orderQueueExample);
                            UmsMemberOrderQueue record = new UmsMemberOrderQueue();
                            record.setOrderId(order.getId());
                            record.setMemberId(member.getId());
                            record.setOrderAmount(order.getPayAmount());
                            record.setQuitQueueMark(UmsMemberOrderQueue.QUEUE_STATUS_WAIT);
                            record.setQueueType(UmsMemberOrderQueue.QUEUE_TYPE_ORDINARY);
                            record.setAccelerateSwitch(UmsMemberOrderQueue.ACCELERATE_SWITCH_YES);
                            record.setQueueIndex(++allQueue);
                            umsMemberOrderQueueMapper.insert(record);
                            splitMark = true;
                        }
                    }
                }
            }

        }
        return splitMark;
    }


    /**
     * 会员分润
     * @param currentMember
     * @param higherLevelMember
     * @param order
     */
    private BigDecimal newMemberSplitProfit(UmsMember currentMember, UmsMember higherLevelMember, OmsOrder order){
        /**
         * 新增用户位普通用户，订单支付成功后满一定金额，成为vip普通会员
         * 当前订单金额 大于等于 vip门槛金额
         */
        log.info("aqaq0331");
        if(currentMember.getMemberLevel().equals(MemberLevel.Member)  &&
                order.getPayAmount().compareTo(new BigDecimal(becomeVipAmount)) >= 0 ){
            log.info("new order member {}" , JSONUtil.toJsonStr(currentMember));
            currentMember.setMemberLevelId((long)MemberLevel.Consumer.getValue());
            currentMember.setMemberLevel(MemberLevel.Consumer);
        }
        log.info("aqaq033");
        //更新改会员为排队中
        currentMember.setOrderStatus(1);
        memberMapper.updateByPrimaryKeySelective(currentMember);
        //订单加入队列
        UmsMemberOrderQueueExample example = new UmsMemberOrderQueueExample();
        long allQueue = umsMemberOrderQueueMapper.countByExample(example);
        UmsMemberOrderQueue record = new UmsMemberOrderQueue();
        record.setOrderId(order.getId());
        record.setMemberId(currentMember.getId());
        record.setOrderAmount(order.getPayAmount());
        record.setQuitQueueMark(UmsMemberOrderQueue.QUEUE_STATUS_WAIT);
        record.setQueueType(UmsMemberOrderQueue.QUEUE_TYPE_ORDINARY);
        record.setAccelerateSwitch(UmsMemberOrderQueue.ACCELERATE_SWITCH_NO);
        record.setQueueIndex(++allQueue);
        record.setCreateTime(new Date());
        record.setNick(currentMember.getNickname());
        record.setPhone(currentMember.getPhone());
        record.setHighMemberId(higherLevelMember.getId());

        //在此判断是否是首单新用户
        UmsMemberOrderQueueExample orderQueueExample1 = new UmsMemberOrderQueueExample();
        orderQueueExample1.createCriteria().andMemberIdEqualTo(order.getMemberId());
        long memberOrderCount = umsMemberOrderQueueMapper.countByExample(orderQueueExample1);
        if(memberOrderCount == 0){
            //查看上级所有加速单
            UmsMemberOrderQueueExample higherQueueExample = new UmsMemberOrderQueueExample();
            higherQueueExample.createCriteria()
                    .andQuitQueueMarkEqualTo(UmsMemberOrderQueue.QUEUE_STATUS_WAIT)
                    .andQueueTypeEqualTo(UmsMemberOrderQueue.QUEUE_TYPE_FAST)
                    .andMemberIdEqualTo(higherLevelMember.getId());
            List<UmsMemberOrderQueue> higherQueueList = umsMemberOrderQueueMapper.selectByExample(higherQueueExample);
            //上级目前第一位加速单
            if(!higherQueueList.isEmpty()){
                record.setAccelerateOrderId(higherQueueList.get(0).getOrderId());
            }
        }

        umsMemberOrderQueueMapper.insert(record);
        log.info("new Order Queue {}" , JSONUtil.toJsonStr(record));

        String ratio = "0."+ 2;
        BigDecimal revenueAmount = order.getPayAmount().multiply(new BigDecimal(ratio)).setScale(2, RoundingMode.HALF_UP);
        UmsMemberAccountTransaction accountTransaction = new UmsMemberAccountTransaction();
        // accountTransaction.setCommissionRatio(higherLevel.getCommissionRatio()); mcoo
        accountTransaction.setMemberId(higherLevelMember.getId());
        accountTransaction.setOrderId(order.getId());
        accountTransaction.setRemarks("直推会员分润");
        accountTransaction.setTransactionState(UmsMemberAccountTransaction.TRANSACTION_STATE_YES);
        accountTransaction.setRevenueAmount(revenueAmount);
        //
        accountTransaction.setTransferPaymentTime(DateUtil.date());
        accountTransaction.setFlowType(1);
        umsMemberAccountTransactionMapper.insert(accountTransaction);
        log.info("new Account Transaction {}" , JSONUtil.toJsonStr(accountTransaction));

        //会员金额到账
        higherLevelMember.setBalance(revenueAmount.add(higherLevelMember.getBalance() == null ? BigDecimal.ZERO : higherLevelMember.getBalance()));
        memberMapper.updateByPrimaryKey(higherLevelMember);


        return revenueAmount;
    }


    /**
     * 二级店长分润
     * @param lowerMember
     * @param higherMember
     * @param order
     */
    private void twoLevelSplitProfit(UmsMember lowerMember, UmsMember higherMember, OmsOrder order,
                                     BigDecimal revenueAmount){
        if(higherMember.getMemberLevel().equals(MemberLevel.Partner)){
            //上下级关系
            if(higherMember.getMemberLevel().getValue() > lowerMember.getMemberLevel().getValue()){

                UmsMemberLevel lowerLevel = umsMemberLevelMapper.selectByPrimaryKey(lowerMember.getMemberLevelId());
                UmsMemberLevel higherLevel = umsMemberLevelMapper.selectByPrimaryKey(higherMember.getMemberLevelId());

                Integer profitRatio = 0;
                if(higherLevel.getCommissionRatio() != null && lowerLevel.getCommissionRatio() != null){
                    profitRatio = higherLevel.getCommissionRatio() - lowerLevel.getCommissionRatio();
                }
                String ratioStr = profitRatio < 10 ? "0.0" + profitRatio : "0."+profitRatio;
                //查看上级的分润比例
                BigDecimal payAmountPercent = order.getPayAmount().multiply(new BigDecimal(ratioStr)).setScale(2, RoundingMode.HALF_UP);

                UmsMemberAccountTransaction accountTransaction = new UmsMemberAccountTransaction();
                accountTransaction.setCommissionRatio(profitRatio);
                accountTransaction.setMemberId(higherMember.getId());
                accountTransaction.setOrderId(order.getId());
                accountTransaction.setRemarks("二级店长上级分润");
                accountTransaction.setRevenueAmount(payAmountPercent);
                //即时到账
                accountTransaction.setTransferPaymentTime(DateUtil.date());
                accountTransaction.setFlowType(1);
                umsMemberAccountTransactionMapper.insert(accountTransaction);

                //会员金额到账
                higherMember.setBalance(payAmountPercent.add(higherMember.getBalance() == null ? BigDecimal.ZERO : higherMember.getBalance()));
                memberMapper.updateByPrimaryKeySelective(higherMember);

                //查询上级
                UmsMember next = this.findInOrderQueueMember(higherMember.getId());

                if(next != null){
                    if (next.getMemberLevel().equals(higherMember.getMemberLevel())){
                        twoLevelSplitProfit(higherMember, next, order, payAmountPercent);
                    }else {
                        threeLevelSplitProfit(higherMember, next, order, payAmountPercent);
                        fourLevelSplitProfit(higherMember, next, order, payAmountPercent);
                    }
                }
                //平级关系
            }else if(lowerMember.getMemberLevel().equals(lowerMember.getMemberLevel())){
                BigDecimal tenPercent = revenueAmount.multiply(new BigDecimal("0."+sameLevelProfit)).setScale(2, RoundingMode.HALF_UP);

                UmsMemberAccountTransaction accountTransaction = new UmsMemberAccountTransaction();
                accountTransaction.setCommissionRatio(Integer.valueOf(sameLevelProfit));
                accountTransaction.setMemberId(higherMember.getId());
                accountTransaction.setOrderId(order.getId());
                accountTransaction.setRemarks("二级店长平级分润");
                accountTransaction.setRevenueAmount(tenPercent);
                //即时到账
                accountTransaction.setTransferPaymentTime(DateUtil.date());
                accountTransaction.setFlowType(1);
                umsMemberAccountTransactionMapper.insert(accountTransaction);

                //会员金额到账
                higherMember.setBalance(tenPercent.add(higherMember.getBalance() == null ? BigDecimal.ZERO : higherMember.getBalance()));
                memberMapper.updateByPrimaryKeySelective(higherMember);

                //查询比当前级别大的会员
                UmsMember next = this.findNextHigherLevelMemberByType(higherMember.getId(), MemberLevel.Partner);
                if(next != null){
                    threeLevelSplitProfit(higherMember, next, order, tenPercent);
                    fourLevelSplitProfit(higherMember, next, order, tenPercent);
                }
            }
        }
    }


    /**
     * 三级代理分润
     * @param lowerMember
     * @param higherMember
     * @param order
     */
    private void threeLevelSplitProfit(UmsMember lowerMember, UmsMember higherMember, OmsOrder order, BigDecimal revenueAmount){
        if(higherMember.getMemberLevel().equals(MemberLevel.Diamond)){
            //上下级关系
            if(higherMember.getMemberLevel().getValue() > lowerMember.getMemberLevel().getValue()){

                UmsMemberLevel lowerLevel = umsMemberLevelMapper.selectByPrimaryKey(lowerMember.getMemberLevelId());
                UmsMemberLevel higherLevel = umsMemberLevelMapper.selectByPrimaryKey(higherMember.getMemberLevelId());

                Integer profitRatio = 0;
                if(higherLevel.getCommissionRatio() != null && lowerLevel.getCommissionRatio() != null){
                    profitRatio = higherLevel.getCommissionRatio() - lowerLevel.getCommissionRatio();
                }

                String ratioStr = profitRatio < 10 ? "0.0" + profitRatio : "0."+profitRatio;
                //查看上级的分润比例
                BigDecimal payAmountPercent = order.getPayAmount().multiply(new BigDecimal(ratioStr)).setScale(2, RoundingMode.HALF_UP);
                UmsMemberAccountTransaction accountTransaction = new UmsMemberAccountTransaction();
                accountTransaction.setCommissionRatio(profitRatio);
                accountTransaction.setMemberId(higherMember.getId());
                accountTransaction.setOrderId(order.getId());
                accountTransaction.setRemarks("三级代理上级分润");
                accountTransaction.setRevenueAmount(payAmountPercent);
                accountTransaction.setTransferPaymentTime(DateUtil.date());
                accountTransaction.setFlowType(1);
                umsMemberAccountTransactionMapper.insert(accountTransaction);

                //会员金额到账
                higherMember.setBalance(payAmountPercent.add(higherMember.getBalance() == null ? BigDecimal.ZERO : higherMember.getBalance()));
                memberMapper.updateByPrimaryKeySelective(higherMember);

                //查询上级
                UmsMember next = this.findInOrderQueueMember(higherMember.getId());

                if(next != null){
                    if (next.getMemberLevel().equals(higherMember.getMemberLevel())){
                        threeLevelSplitProfit(higherMember, next, order, payAmountPercent);
                    }else {
                        fourLevelSplitProfit(higherMember, next, order, payAmountPercent);
                    }
                }
                //平级关系
            }else if(lowerMember.getMemberLevel().equals(lowerMember.getMemberLevel())){
                BigDecimal tenPercent = revenueAmount.multiply(new BigDecimal("0."+sameLevelProfit)).setScale(2, RoundingMode.HALF_UP);
                UmsMemberAccountTransaction accountTransaction = new UmsMemberAccountTransaction();
                accountTransaction.setCommissionRatio(Integer.valueOf(sameLevelProfit));
                accountTransaction.setMemberId(higherMember.getId());
                accountTransaction.setOrderId(order.getId());
                accountTransaction.setRemarks("三级代理平级分润");
                accountTransaction.setRevenueAmount(tenPercent);
                //24小时后到账
                accountTransaction.setTransferPaymentTime(DateUtil.tomorrow());
                accountTransaction.setFlowType(1);
                umsMemberAccountTransactionMapper.insert(accountTransaction);

                //会员金额到账
                higherMember.setBalance(tenPercent.add(higherMember.getBalance() == null ? BigDecimal.ZERO : higherMember.getBalance()));
                memberMapper.updateByPrimaryKeySelective(higherMember);

                UmsMember next = this.findNextHigherLevelMemberByType(higherMember.getId(), MemberLevel.Diamond);
                if(next != null){
                    fourLevelSplitProfit(higherMember, next, order, tenPercent);
                }
            }
        }

    }
    /**
     * 四级市代分润
     * @param lowerMember
     * @param higherMember
     * @param order
     */
    private void fourLevelSplitProfit(UmsMember lowerMember, UmsMember higherMember, OmsOrder order, BigDecimal revenueAmount){
        if(higherMember.getMemberLevel().equals(MemberLevel.OneDiamond)){
            //上下级关系
            if(higherMember.getMemberLevel().getValue() > lowerMember.getMemberLevel().getValue()){

                UmsMemberLevel lowerLevel = umsMemberLevelMapper.selectByPrimaryKey(lowerMember.getMemberLevelId());
                UmsMemberLevel higherLevel = umsMemberLevelMapper.selectByPrimaryKey(higherMember.getMemberLevelId());

                Integer profitRatio = 0;
                if(higherLevel.getCommissionRatio() != null && lowerLevel.getCommissionRatio() != null){
                    profitRatio = higherLevel.getCommissionRatio() - lowerLevel.getCommissionRatio();
                }
                String ratioStr = profitRatio < 10 ? "0.0" + profitRatio : "0."+profitRatio;
                //查看上级的分润比例
                BigDecimal payAmountPercent = order.getPayAmount().multiply(new BigDecimal(ratioStr)).setScale(2, RoundingMode.HALF_UP);

                UmsMemberAccountTransaction accountTransaction = new UmsMemberAccountTransaction();
                accountTransaction.setCommissionRatio(profitRatio);
                accountTransaction.setMemberId(higherMember.getId());
                accountTransaction.setOrderId(order.getId());
                accountTransaction.setRemarks("四级市代上级分润");
                accountTransaction.setRevenueAmount(payAmountPercent);
                //24小时后到账
                accountTransaction.setTransferPaymentTime(DateUtil.date());
                accountTransaction.setFlowType(1);
                umsMemberAccountTransactionMapper.insert(accountTransaction);

                //会员金额到账
                higherMember.setBalance(payAmountPercent.add(higherMember.getBalance() == null ? BigDecimal.ZERO : higherMember.getBalance()));
                memberMapper.updateByPrimaryKeySelective(higherMember);

                //查询上级
                UmsMember next = this.findInOrderQueueMember(higherMember.getId());

                if(next != null && next.getMemberLevel().equals(higherMember.getMemberLevel())){
                    fourLevelSplitProfit(higherMember, next, order, payAmountPercent);
                }
                //平级关系
            }else if(lowerMember.getMemberLevel().equals(lowerMember.getMemberLevel())){
                BigDecimal tenPercent = revenueAmount.multiply(new BigDecimal("0."+sameLevelProfit)).setScale(2, RoundingMode.HALF_UP);

                UmsMemberAccountTransaction accountTransaction = new UmsMemberAccountTransaction();
                accountTransaction.setCommissionRatio(Integer.valueOf(sameLevelProfit));
                accountTransaction.setMemberId(higherMember.getId());
                accountTransaction.setOrderId(order.getId());
                accountTransaction.setRemarks("四级市代平级分润");
                accountTransaction.setRevenueAmount(tenPercent);

                //会员金额到账
                higherMember.setBalance(tenPercent.add(higherMember.getBalance() == null ? BigDecimal.ZERO : higherMember.getBalance()));
                memberMapper.updateByPrimaryKeySelective(higherMember);

                //24小时后到账
                accountTransaction.setTransferPaymentTime(DateUtil.tomorrow());
                accountTransaction.setFlowType(1);
                umsMemberAccountTransactionMapper.insert(accountTransaction);
            }
        }
    }


    /**
     * 寻找上级且在队列中,未在队列且返回null
     */
    private UmsMember findInOrderQueueMember(Long id) {
        UmsMemberRelationTree  relationTree = this.getUpLevelRelationTreeById(id);
        if(relationTree == null){
            return null;
        }
        UmsMember higherMember = memberMapper.selectByPrimaryKey(relationTree.getHigherLevelId());
        if(higherMember == null){
            return null;
        }
        if( higherMember.getOrderStatus() == 1){
            return higherMember;
        }


        return null;
    }

    private UmsMemberRelationTree getUpLevelRelationTreeById(Long id) {
        UmsMemberRelationTree relationTree = null;
        UmsMemberRelationTreeExample relationTreeExample = new UmsMemberRelationTreeExample();
        relationTreeExample.createCriteria().andMemberIdEqualTo(id);
        List<UmsMemberRelationTree> relationTreeList =  umsMemberRelationTreeMapper.selectByExample(relationTreeExample);
        if(!relationTreeList.isEmpty()) {
            //找到上级关系
            relationTree = relationTreeList.get(0);
        }
        return relationTree;
    }
}
