fix
Hentua
2023-04-23 fc093b0724b0c8979c0896f2bdc4cf8c4af27a1f
src/main/java/cc/mrbird/febs/mall/service/impl/MemberProfitServiceImpl.java
@@ -1,27 +1,28 @@
package cc.mrbird.febs.mall.service.impl;
import cc.mrbird.febs.common.enumerates.AgentLevelEnum;
import cc.mrbird.febs.common.enumerates.DataDictionaryEnum;
import cc.mrbird.febs.common.enumerates.FlowTypeEnum;
import cc.mrbird.febs.common.enumerates.MoneyFlowTypeEnum;
import cc.mrbird.febs.common.enumerates.*;
import cc.mrbird.febs.common.utils.AppContants;
import cc.mrbird.febs.common.utils.MallUtils;
import cc.mrbird.febs.common.utils.RedisUtils;
import cc.mrbird.febs.mall.dto.ScorePoorDto;
import cc.mrbird.febs.mall.entity.*;
import cc.mrbird.febs.mall.mapper.*;
import cc.mrbird.febs.mall.service.IApiMallMemberWalletService;
import cc.mrbird.febs.mall.service.IMallAchieveService;
import cc.mrbird.febs.mall.service.IMallMoneyFlowService;
import cc.mrbird.febs.mall.service.IMemberProfitService;
import cc.mrbird.febs.mall.service.*;
import cc.mrbird.febs.mall.vo.AdminTeamEqualsPerkVo;
import cc.mrbird.febs.rabbit.producter.AgentProducer;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.models.auth.In;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
@@ -30,6 +31,7 @@
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.stream.Collectors;
/**
 * @author wzy
@@ -51,6 +53,15 @@
    private final MallAchieveRecordMapper mallAchieveRecordMapper;
    private final RedisUtils redisUtils;
    private final MallMemberWalletMapper mallMemberWalletMapper;
    private final IAgentService iAgentService;
    private final IMallMoneyFlowService mallMoneyFlowService;
    private final MallMqRecordMapper mallMqRecordMapper;
    private final AgentProducer agentProducer;
    private final MallScoreRecordMapper mallScoreRecordMapper;
    private final MallScoreAchieveReleaseMapper mallScoreAchieveReleaseMapper;
    private final MallScoreVoucherMapper mallScoreVoucherMapper;
    private final MallSystemSettingMapper mallSystemSettingMapper;
    @Override
    @Transactional(rollbackFor = Exception.class)
@@ -61,6 +72,9 @@
            return;
        }
        /**
         *
         */
        if (profitDate == null) {
            profitDate = DateUtil.offset(new Date(), DateField.DAY_OF_YEAR, -1);
        }
@@ -68,6 +82,7 @@
//        BigDecimal tcIncome = mallOrderInfoMapper.selectTotalAmountUnCostForDate(profitDate, null, "D", 2);
        // 普通商品业绩
//        BigDecimal normalIncome = mallOrderInfoMapper.selectTotalAmountUnCostForDate(profitDate, null, "D", 1);
        //今日总业绩
        BigDecimal totalIncome = mallAchieveRecordMapper.selectAchieveTotal("D", profitDate);
        if (totalIncome.compareTo(BigDecimal.ZERO) == 0) {
@@ -113,9 +128,9 @@
                BigDecimal preStaticProfit = staticProfit.divide(new BigDecimal(list.size()), 2, RoundingMode.HALF_UP);
                for (Map<String, Object> item : list) {
                    Long memberId = (Long) item.get("memberId");
//                    Long memberId = (Long) item.get("memberId");
                    String orderNo = (String) item.get("orderNo");
                    changeAllScoreAndCommission(preStaticProfit,orderNo);
//                    int reduce = walletService.reduce(preStaticProfit, memberId, "score");
//                    if (reduce == 2) {
//                        break;
@@ -124,15 +139,127 @@
//                    walletService.add(preStaticProfit, memberId, "commission");
//                    moneyFlowService.addMoneyFlow(memberId, preStaticProfit, MoneyFlowTypeEnum.STATIC_BONUS.getValue(), orderNo, FlowTypeEnum.COMMISSION.getValue());
//                    moneyFlowService.addMoneyFlow(memberId, preStaticProfit.negate(), MoneyFlowTypeEnum.STATIC_BONUS.getValue(), orderNo, FlowTypeEnum.SCORE.getValue());
                    changeScoreAndCommission(memberId, preStaticProfit, MoneyFlowTypeEnum.STATIC_BONUS.getValue(), orderNo);
//                    changeScoreAndCommission(memberId, preStaticProfit, MoneyFlowTypeEnum.STATIC_BONUS.getValue(), orderNo);
                }
            }
        }
    }
    public void changeAllScoreAndCommission(BigDecimal preStaticProfit,String orderNo){
        List<MallMember> members = mallMemberMapper.selectList(null);
        for(MallMember mallMember : members){
            changeScoreAndCommission(mallMember.getId(), preStaticProfit, MoneyFlowTypeEnum.STATIC_BONUS.getValue(), orderNo);
        }
    }
    @Override
    public void dynamicProfit(Long orderId) {
//        return;
        dynamicProfit(orderId, 2);
    }
    /**
     * 直推收益
     *
     * 1、直推收益 1:20;2:30;3:40 返利,隔代奖拿直推收益20%
     * 2、若非代理推代理,只拿10%,往上找代理给15%,再往上找代理给15%,往上找连续两层。股东套餐同理
     * 3、代理推代理按照第1点结算
     *
     * @param orderId
     */
    @Override
    public void directProfit(Long orderId) {
        log.info("######直推奖励, 订单ID:{}######", orderId);
        MallOrderInfo orderInfo = mallOrderInfoMapper.selectById(orderId);
        if (orderInfo.getOrderType() == 2) {
            log.info("积分订单无返利");
            return;
        }
        BigDecimal indirectPer = BigDecimal.valueOf(0.2);
        BigDecimal indirectPer2 = BigDecimal.valueOf(0.15);
        MallMember member = mallMemberMapper.selectById(orderInfo.getMemberId());
        // 父级会员
        MallMember parentMember = mallMemberMapper.selectInfoByInviteId(member.getReferrerId());
        // 父级会员直推人数
        Integer directCnt = mallMemberMapper.selectOwnCntByInviteId(parentMember.getInviteId());
        List<DataDictionaryCustom> dataDices = dataDictionaryCustomMapper.selectDicByType(DataDictionaryEnum.DIRECT_BONUS_SETTING.getType());
        directCnt = directCnt == null ? 0 : directCnt;
        List<MallOrderItem> items = mallOrderInfoMapper.getMallOrderItemByOrderId(orderId);
        if (CollUtil.isEmpty(items)) {
            return;
        }
        for (MallOrderItem item : items) {
            // 减去成本后算收益
            BigDecimal amount = item.getPrice().subtract(item.getCostPrice()).multiply(BigDecimal.valueOf(item.getCnt()));
            if (amount.compareTo(BigDecimal.ZERO) < 1) {
                continue;
            }
            // 直推返利比例
            BigDecimal profitPer = BigDecimal.ZERO;
            int isSameLevel = 0;
            // 普通商品 -- 直推上级可拿百分比直推奖励
            if (item.getIsNormal() == 1) {
                profitPer = new BigDecimal(item.getNormalPer());
                // 套餐商品
            } else {
                // 判断上级是否与自己购买的套餐符合,若符合则走3级直推逻辑,若不符合则另外一个
                if (parentMember.getAccountLevel().equals(item.getGoodsLevel()) || AccountLevelEnums.VIP.getLevel().equals(parentMember.getAccountLevel())) {
                    for (DataDictionaryCustom dataDic : dataDices) {
                        JSONObject jsonObject = JSONObject.parseObject(dataDic.getValue());
                        if (directCnt >= jsonObject.getInteger("pushCnt")) {
                            profitPer = jsonObject.getBigDecimal("prop");
                        }
                    }
                    isSameLevel = 1;
                    // 非代理推代理/非股东推股东
                } else {
                    profitPer = BigDecimal.valueOf(0.1);
                    isSameLevel = 2;
                }
            }
            // 直推奖
            BigDecimal profit = amount.multiply(profitPer.divide(new BigDecimal(100), 2, RoundingMode.HALF_UP));
            changeScoreAndCommission(parentMember.getId(), profit, MoneyFlowTypeEnum.DYNAMIC_ACHIEVE.getValue(), orderInfo.getOrderNo());
            // 代理推代理
            if (isSameLevel == 1) {
                MallMember doubleParentMember = mallMemberMapper.selectInfoByInviteId(parentMember.getReferrerId());
                if (doubleParentMember == null) {
                    continue;
                }
                BigDecimal doubleParentProfit = profit.multiply(indirectPer);
                changeScoreAndCommission(doubleParentMember.getId(), doubleParentProfit, MoneyFlowTypeEnum.RECOMMEND_BONUS.getValue(), orderInfo.getOrderNo());
            }
            // 非代理推代理
            if (isSameLevel == 2) {
                List<MallMember> mallMembers = mallMemberMapper.selectParentMemberList(StrUtil.split(parentMember.getReferrerIds(), ','), parentMember.getReferrerId(), 2);
                if (CollUtil.isEmpty(mallMembers)) {
                    continue;
                }
                for (MallMember mallMember : mallMembers) {
                    if (!item.getGoodsLevel().equals(mallMember.getAccountLevel())) {
                        break;
                    }
                    BigDecimal doubleParentProfit = profit.multiply(indirectPer2);
                    changeScoreAndCommission(mallMember.getId(), doubleParentProfit, MoneyFlowTypeEnum.RECOMMEND_BONUS.getValue(), orderInfo.getOrderNo());
                }
            }
        }
    }
    /**
@@ -144,7 +271,6 @@
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void dynamicProfit(Long orderId, Integer isNormal) {
        log.info("######直推奖励, 订单ID:{}######", orderId);
        MallOrderInfo orderInfo = mallOrderInfoMapper.selectById(orderId);
        if (orderInfo.getOrderType() == 2) {
            log.info("积分订单无返利");
@@ -175,9 +301,9 @@
            }
            // 判断套餐或者普通商品,结算对应商品的动态分红
            if (!Objects.equals(item.getIsNormal(), isNormal)) {
                continue;
            }
//            if (!Objects.equals(item.getIsNormal(), isNormal)) {
//                continue;
//            }
            // =======直推返利== start =====
            // 直接奖励收益
@@ -256,53 +382,9 @@
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void agentProfit(Date profitDate) {
    public void agentProfit() {
        log.info("#####==代理分红==start==#####");
        if (profitDate == null) {
            profitDate = DateUtil.offset(new Date(), DateField.DAY_OF_YEAR, -1);
        }
        // 套餐业绩
//        BigDecimal tcIncome = mallOrderInfoMapper.selectTotalAmountUnCostForDate(profitDate, null, "D", 2);
        // 普通商品业绩
//        BigDecimal normalIncome = mallOrderInfoMapper.selectTotalAmountUnCostForDate(profitDate, null, "D", 1);
        BigDecimal totalIncome = mallAchieveRecordMapper.selectAchieveTotal("D", profitDate);
        DataDictionaryCustom dic = dataDictionaryCustomMapper.selectDicDataByTypeAndCode(DataDictionaryEnum.AGENT_BONUS.getType(), DataDictionaryEnum.AGENT_BONUS.getCode());
        BigDecimal profit = totalIncome.multiply(new BigDecimal(dic.getValue()).divide(new BigDecimal("100"), 2, RoundingMode.HALF_UP));
        List<MallMember> agentMembers = mallMemberMapper.selectByIdAndNoLevel(null, AgentLevelEnum.FIRST_LEVEL.name());
        if (CollUtil.isEmpty(agentMembers)) {
            return;
        }
        List<DataDictionaryCustom> dics = dataDictionaryCustomMapper.selectDicByType(AppContants.AGENT_LEVEL_REQUIRE);
        for (DataDictionaryCustom agentDic : dics) {
            JSONObject jsonObject = JSONObject.parseObject(agentDic.getValue());
            BigDecimal profitProp = jsonObject.getBigDecimal("profitProp").divide(new BigDecimal("100"), 2, RoundingMode.HALF_UP);
            List<MallMember> agentMemberList = mallMemberMapper.selectMemberWithLevel(agentDic.getCode());
            if (CollUtil.isEmpty(agentMemberList)) {
                continue;
            }
            BigDecimal income = profit.multiply(profitProp).divide(BigDecimal.valueOf(agentMemberList.size()), 2, RoundingMode.HALF_UP);
            if (income.compareTo(BigDecimal.ZERO) < 1) {
                continue;
            }
            for (MallMember agentMember : agentMemberList) {
//                int reduce = walletService.reduce(income, agentMember.getId(), "score");
//                if (reduce == 2) {
//                    continue;
//                }
//
//                walletService.add(income, agentMember.getId(), "commission");
//
//                moneyFlowService.addMoneyFlow(agentMember.getId(), income, MoneyFlowTypeEnum.AGENT_BONUS.getValue(), null, FlowTypeEnum.COMMISSION.getValue());
//                moneyFlowService.addMoneyFlow(agentMember.getId(), income.negate(), MoneyFlowTypeEnum.AGENT_BONUS.getValue(), null, FlowTypeEnum.SCORE.getValue());
                changeScoreAndCommission(agentMember.getId(), income, MoneyFlowTypeEnum.AGENT_BONUS.getValue(), null);
            }
        }
        log.info("#####==代理分红==end==#####");
    }
@@ -323,180 +405,32 @@
    }
    @Override
    public void rankProfit() {
        log.info("######==排名分红==####");
        Page<MallMember> page = new Page<>(1, 5);
        MallMember query = new MallMember();
        query.setQuery("2");
        Date profitDate = DateUtil.offset(new Date(), DateField.DAY_OF_YEAR, -1);
        query.setCreatedTime(profitDate);
        IPage<MallMember> rankListInPage = mallMemberMapper.selectRankListInPage(page, query);
        List<MallMember> rankList = rankListInPage.getRecords();
        if (CollUtil.isEmpty(rankList)) {
            return;
        }
        // 套餐业绩
//        BigDecimal tcIncome = mallOrderInfoMapper.selectTotalAmountUnCostForDate(profitDate, null, "M", 2);
        // 普通商品业绩
//        BigDecimal normalIncome = mallOrderInfoMapper.selectTotalAmountUnCostForDate(profitDate, null, "M", 1);
        BigDecimal totalIncome = mallAchieveRecordMapper.selectAchieveTotal("M", profitDate);
        List<DataDictionaryCustom> rankAward = dataDictionaryCustomMapper.selectDicByType("RANK_AWARD");
        DataDictionaryCustom dic = dataDictionaryCustomMapper.selectDicDataByTypeAndCode(DataDictionaryEnum.RANK_BONUS.getType(), DataDictionaryEnum.RANK_BONUS.getCode());
        BigDecimal rankBonusTotal = totalIncome.multiply(new BigDecimal(dic.getValue()).divide(new BigDecimal("100"), 2, RoundingMode.HALF_UP));
        BigDecimal preBonus = rankBonusTotal.divide(BigDecimal.valueOf(100), 2, RoundingMode.HALF_UP);
        int i = 0;
        for (MallMember member : rankList) {
            DataDictionaryCustom rank = rankAward.get(i);
            i++;
            BigDecimal bonus = preBonus.multiply(new BigDecimal(rank.getValue()));
//            int reduce = walletService.reduce(bonus, member.getId(), "score");
//            if (reduce == 2) {
//                continue;
//            }
//            walletService.add(bonus, member.getId(), "commission");
//            moneyFlowService.addMoneyFlow(member.getId(), bonus, MoneyFlowTypeEnum.RANK_BONUS.getValue(), null, FlowTypeEnum.COMMISSION.getValue());
//            moneyFlowService.addMoneyFlow(member.getId(), bonus.negate(), MoneyFlowTypeEnum.RANK_BONUS.getValue(), null, FlowTypeEnum.SCORE.getValue());
            changeScoreAndCommission(member.getId(), bonus, MoneyFlowTypeEnum.RANK_BONUS.getValue(), null);
        }
    }
    /**
     * 拿推荐人的收益(代理,直推,排名)的10%加权平分给下面直推
     */
    @Override
    public void thankfulProfit(Date date) {
        log.info("######==感恩奖==start==####");
        List<MallMember> mallMembers = mallMemberMapper.selectMemberListHasChild();
        if (CollUtil.isEmpty(mallMembers)) {
            return;
        }
        if (date == null) {
            date = DateUtil.offset(new Date(), DateField.DAY_OF_YEAR, -1);
        }
        DataDictionaryCustom dic = dataDictionaryCustomMapper.selectDicDataByTypeAndCode(DataDictionaryEnum.THANKFUL_BONUS.getType(), DataDictionaryEnum.THANKFUL_BONUS.getCode());
        // 感恩奖比例
        BigDecimal prop = new BigDecimal(dic.getValue()).divide(BigDecimal.valueOf(100), 2, RoundingMode.HALF_UP);
        for (MallMember mallMember : mallMembers) {
            BigDecimal income = mallMoneyFlowMapper.selectThankfulCommission(date, mallMember.getId());
            List<MallMember> children = mallMemberMapper.selectMemberDirectForHasLevel(mallMember.getInviteId());
            if (CollUtil.isEmpty(children)) {
                continue;
            }
            BigDecimal reduceProfit = income.multiply(prop);
            if (reduceProfit.compareTo(BigDecimal.ZERO) < 1) {
                continue;
            }
            int reduce = walletService.reduce(reduceProfit, mallMember.getId(), "commission");
            if (reduce == 2) {
                continue;
            }
            moneyFlowService.addMoneyFlow(mallMember.getId(), reduceProfit.negate(), MoneyFlowTypeEnum.THANKFUL.getValue(), null, FlowTypeEnum.COMMISSION.getValue());
            for (MallMember child : children) {
                BigDecimal preProfit = income.multiply(prop).divide(BigDecimal.valueOf(children.size()), 2, RoundingMode.HALF_DOWN);
                if (preProfit.compareTo(BigDecimal.ZERO) < 1) {
                    continue;
                }
//                int reduce1 = walletService.reduce(preProfit, child.getId(), "score");
//                if (reduce1 == 2) {
//                    continue;
//                }
//                walletService.add(preProfit, child.getId(), "commission");
//                moneyFlowService.addMoneyFlow(child.getId(), preProfit, MoneyFlowTypeEnum.THANKFUL.getValue(), null, mallMember.getId(), FlowTypeEnum.COMMISSION.getValue());
//                moneyFlowService.addMoneyFlow(child.getId(), preProfit.negate(), MoneyFlowTypeEnum.THANKFUL.getValue(), null, mallMember.getId(), FlowTypeEnum.SCORE.getValue());
                changeScoreAndCommission(child.getId(), preProfit, MoneyFlowTypeEnum.THANKFUL.getValue(), null);
            }
        }
        log.info("######==感恩奖==end==####");
    }
    @Override
    public void storeAndDirectorProfit(Date profitDate) {
        log.info("#####==店补/董事==start==######");
        if (profitDate == null) {
            profitDate = DateUtil.offset(new Date(), DateField.DAY_OF_YEAR, -1);
        }
        // 套餐业绩
//        BigDecimal tcIncome = mallOrderInfoMapper.selectTotalAmountUnCostForDate(profitDate, null, "D", 2);
        // 普通商品业绩
//        BigDecimal normalIncome = mallOrderInfoMapper.selectTotalAmountUnCostForDate(profitDate, null, "D", 1);
        BigDecimal totalIncome = mallAchieveRecordMapper.selectAchieveTotal("D", profitDate);
        // 董事
        DataDictionaryCustom dic = dataDictionaryCustomMapper.selectDicDataByTypeAndCode(DataDictionaryEnum.DIRECTOR_BONUS.getType(), DataDictionaryEnum.DIRECTOR_BONUS.getCode());
        List<MallMember> directors = mallMemberMapper.selectDirectorsOrStoreMaster(1);
        if (CollUtil.isNotEmpty(directors)) {
            BigDecimal total = totalIncome.multiply(new BigDecimal(dic.getValue()).divide(new BigDecimal("100"), 2, RoundingMode.HALF_UP));
            BigDecimal pre = total.divide(new BigDecimal(directors.size()), 2, RoundingMode.HALF_UP);
            for (MallMember director : directors) {
                if (pre.compareTo(BigDecimal.ZERO) < 1) {
                    continue;
                }
//                int reduce = walletService.reduce(pre, director.getId(), "score");
//                if (reduce == 2) {
//                    continue;
//                }
//                walletService.add(pre, director.getId(), "commission");
//                moneyFlowService.addMoneyFlow(director.getId(), pre, MoneyFlowTypeEnum.DIRECTOR_BONUS.getValue(), null, FlowTypeEnum.COMMISSION.getValue());
//                moneyFlowService.addMoneyFlow(director.getId(), pre.negate(), MoneyFlowTypeEnum.DIRECTOR_BONUS.getValue(), null, FlowTypeEnum.SCORE.getValue());
                changeScoreAndCommission(director.getId(), pre, MoneyFlowTypeEnum.DIRECTOR_BONUS.getValue(), null);
            }
        }
        // 店补
        dic = dataDictionaryCustomMapper.selectDicDataByTypeAndCode(DataDictionaryEnum.COMMUNITY_BONUS.getType(), DataDictionaryEnum.COMMUNITY_BONUS.getCode());
        List<MallMember> storeMasters = mallMemberMapper.selectDirectorsOrStoreMaster(2);
        if (CollUtil.isNotEmpty(storeMasters)) {
            BigDecimal total = totalIncome.multiply(new BigDecimal(dic.getValue()).divide(new BigDecimal("100"), 2, RoundingMode.HALF_UP));
            BigDecimal pre = total.divide(new BigDecimal(storeMasters.size()), 2, RoundingMode.HALF_UP);
            for (MallMember storeMaster : storeMasters) {
                if (pre.compareTo(BigDecimal.ZERO) < 1) {
                    continue;
                }
//                int reduce = walletService.reduce(pre, storeMaster.getId(), "score");
//                if (reduce == 2) {
//                    continue;
//                }
//                walletService.add(pre, storeMaster.getId(), "commission");
//                moneyFlowService.addMoneyFlow(storeMaster.getId(), pre, MoneyFlowTypeEnum.COMMUNITY_BONUS.getValue(), null, FlowTypeEnum.COMMISSION.getValue());
//                moneyFlowService.addMoneyFlow(storeMaster.getId(), pre.negate(), MoneyFlowTypeEnum.COMMUNITY_BONUS.getValue(), null, FlowTypeEnum.SCORE.getValue());
                changeScoreAndCommission(storeMaster.getId(), pre, MoneyFlowTypeEnum.COMMUNITY_BONUS.getValue(), null);
            }
        }
        log.info("#####==店补/董事==end==######");
    }
    @Override
    public void scorePool() {
        log.info("#####==积分池==start==######");
        String redisKey = "scorePool";
//        List<MallOrderInfo> mallOrderInfos = mallOrderInfoMapper.selectList(new QueryWrapper<>());
//        if(CollUtil.isEmpty(mallOrderInfos)){
//            redisUtils.set(redisKey,0,0L);
//            return;
//        }
        /**
         * 后一天2点,结算前一天的所有消费
         * 积分池增加每日消费的10%
         * 每天释放1%,给全体用户
         */
        //前一天的所有消费的10%
        DataDictionaryCustom dic = dataDictionaryCustomMapper.selectDicDataByTypeAndCode(DataDictionaryEnum.SCORE_POOR_RADIO.getType(), DataDictionaryEnum.SCORE_POOR_RADIO.getCode());
        if(ObjectUtil.isEmpty(dic)){
            return;
        }
        ScorePoorDto scorePoorDto = JSONUtil.toBean(dic.getValue(), ScorePoorDto.class);
        BigDecimal everydayRatio = scorePoorDto.getEverydayRatio().multiply(new BigDecimal(0.01));
        BigDecimal dividEquallyRatio = scorePoorDto.getDividEquallyRatio().multiply(new BigDecimal(0.01));
        Date date = DateUtil.offsetDay(new Date(), -1);
        BigDecimal totalAmount = mallOrderInfoMapper.selectTotalAmountByPayDoneAndDataString(1, date);
        BigDecimal multiplyTotalAmount = totalAmount.multiply(new BigDecimal(0.1));
        String redisKey = "scorePool";
        BigDecimal multiplyTotalAmount = totalAmount.multiply(everydayRatio);
        String scorePoolRedis = redisUtils.getString(redisKey);
        if(StrUtil.isBlank(scorePoolRedis)){
            redisUtils.set(redisKey,0,0L);
@@ -506,11 +440,14 @@
        BigDecimal scorePoolNew = scorePoolOld.add(multiplyTotalAmount);
        //每天释放1%给全体用户
        BigDecimal scorePoolToDay = scorePoolNew.multiply(new BigDecimal(0.01));
        BigDecimal scorePoolToDay = scorePoolNew.multiply(dividEquallyRatio);
        redisUtils.set(redisKey,scorePoolNew.subtract(scorePoolToDay).intValue(),0L);
        List<MallMember> mallMembers = mallMemberMapper.selectList(new QueryWrapper<>());
        QueryWrapper<MallMember> formalMember = new QueryWrapper<>();
        formalMember.ne("level", AgentLevelEnum.ZERO_LEVEL.name());
        List<MallMember> mallMembers = mallMemberMapper.selectList(formalMember);
        int cnt = 0;
        if(CollUtil.isNotEmpty(mallMembers)){
            BigDecimal income = new BigDecimal(scorePoolToDay.divide(new BigDecimal(mallMembers.size()), 2, RoundingMode.HALF_UP).intValue());
            if(income.compareTo(BigDecimal.ZERO) < 1){
@@ -523,6 +460,9 @@
                 */
                BigDecimal outCome = BigDecimal.ZERO;
                MallMemberWallet mallMemberWallet = mallMemberWalletMapper.selectWalletByMemberId(mallMember.getId());
                if(mallMemberWallet.getScore().compareTo(BigDecimal.ZERO) < 1){
                    continue;
                }
                if(mallMemberWallet.getScore().compareTo(income) < 0){
                    outCome = new BigDecimal(mallMemberWallet.getScore().intValue());
                }else{
@@ -532,9 +472,230 @@
                walletService.reduce(outCome, mallMember.getId(), "score");
                moneyFlowService.addMoneyFlow(mallMember.getId(), outCome, MoneyFlowTypeEnum.SCORE_POOL.getValue(), null, FlowTypeEnum.COMMISSION.getValue());
                moneyFlowService.addMoneyFlow(mallMember.getId(), outCome.negate(), MoneyFlowTypeEnum.SCORE_POOL.getValue(), null, FlowTypeEnum.SCORE.getValue());
                cnt ++;
            }
        }
        log.info("#####==积分池==end==######");
        log.info("#####==积分池==end==######;" +
                "今日新增积分:" + multiplyTotalAmount.setScale(2, RoundingMode.HALF_UP)
                +";平分积分数量:"+scorePoolToDay.setScale(2, RoundingMode.HALF_UP)
                +";人数:"+cnt);
    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void selaHalfVoucher(String price) {
        /**
         * 获取所有凭证大于0的用户
         * 当前价格卖出账户的一半凭证
         */
        BigDecimal scorePrice = new BigDecimal(price == null ? "0" : price);
        if(scorePrice.compareTo(BigDecimal.ZERO) <= 0){
            return;
        }
        List<MallMemberWallet> mallMemberWallets = mallMemberWalletMapper.selectList(null);
        if(CollUtil.isNotEmpty(mallMemberWallets)){
            List<MallMemberWallet> wallets = mallMemberWallets
                    .stream()
                    .filter(mallMemberWallet -> mallMemberWallet.getVoucherCnt().compareTo(BigDecimal.ZERO) > 0)
                    .collect(Collectors.toList());
            if(CollUtil.isNotEmpty(wallets)){
                BigDecimal scorePoolCntAdd = BigDecimal.ZERO;
                //绿色积分剩余数量
                for(MallMemberWallet mallMemberWallet : wallets){
                    //增加账户的凭证金额,减少当前的一半的凭证数量
                    BigDecimal voucherCnt = mallMemberWallet.getVoucherCnt().divide(new BigDecimal(2), 2, BigDecimal.ROUND_DOWN)
                            .setScale(2,BigDecimal.ROUND_DOWN);
                    BigDecimal voucherAmountAdd = scorePrice.multiply(voucherCnt)
                            .setScale(2,BigDecimal.ROUND_DOWN);
                    mallMemberWalletMapper.addVorCherAmountAndCntById(voucherAmountAdd,voucherCnt,mallMemberWallet.getId());
                    scorePoolCntAdd = scorePoolCntAdd.add(voucherCnt);
                    DataDictionaryCustom surplusCntDic = dataDictionaryCustomMapper.selectDicDataByTypeAndCode(
                            GreenScoreEnum.SURPLUS_CNT.getType(),
                            GreenScoreEnum.SURPLUS_CNT.getCode()
                    );
                    //增加绿色积分剩余数量
                    BigDecimal surplusCnt = new BigDecimal(surplusCntDic.getValue() == null ? "0" : surplusCntDic.getValue());
                    BigDecimal voucherCntAdd = surplusCnt.add(voucherCnt).setScale(2,BigDecimal.ROUND_DOWN);
                    surplusCntDic.setValue(voucherCntAdd.toString());
                    dataDictionaryCustomMapper.updateById(surplusCntDic);
                    /**
                     * 生成一条卖出记录
                     */
                    String voucherNo = MallUtils.getOrderNum("VS");
                    MallScoreVoucher mallScoreVoucher = new MallScoreVoucher();
                    mallScoreVoucher.setVoucherNo(voucherNo);
                    mallScoreVoucher.setMemberId(mallMemberWallet.getMemberId());
                    mallScoreVoucher.setVoucherCnt(voucherCnt);
                    mallScoreVoucher.setPrice(scorePrice);
                    mallScoreVoucher.setVoucherAmount(voucherAmountAdd);
                    mallScoreVoucher.setType("S");
                    mallScoreVoucherMapper.insert(mallScoreVoucher);
                    //产生一条流水记录
                    mallMoneyFlowService.addMoneyFlow(
                            mallMemberWallet.getMemberId(),
                            voucherAmountAdd,
                            MoneyFlowTypeEnum.VOUCHER_SALE.getValue(),
                            voucherNo,
                            FlowTypeEnum.BALANCE.getValue());
                }
                //增加积分凭证池的凭证数量
                DataDictionaryCustom scorePoolCntDic = dataDictionaryCustomMapper.selectDicDataByTypeAndCode(
                        GreenScoreEnum.SCORE_POOL_CNT.getType(),
                        GreenScoreEnum.SCORE_POOL_CNT.getCode()
                );
                //增加绿色积分剩余数量
                BigDecimal scorePoolCnt = new BigDecimal(scorePoolCntDic.getValue() == null ? "0" : scorePoolCntDic.getValue());
                scorePoolCnt = scorePoolCnt.add(scorePoolCntAdd);
                scorePoolCntDic.setValue(scorePoolCnt.toString());
                dataDictionaryCustomMapper.updateById(scorePoolCntDic);
            }
        }
    }
    /**
     * 给用户的增加凭证数据,并且增加流水
     * @param memberAchieveRelease 释放数量
     * @param memberId 用户ID
     * @param Type 流水类型
     * @param flowNo 流水编号
     */
    private void releaseToMemberAndAddFlow(BigDecimal memberAchieveRelease,Long memberId,int Type,String flowNo){
        //释放到用户的账户
        mallMemberWalletMapper.addVorCherCntByMemberId(memberAchieveRelease,memberId);
        //产生一条流水记录 TODO 需要去掉注释
        mallMoneyFlowService.addMoneyFlow(
                memberId,
                memberAchieveRelease,
                Type,
                flowNo,
                FlowTypeEnum.VOUCHER_CNT.getValue());
    }
    /**
     *  根据星级等级和占比,给该星级的用户释放凭证
     * @param levelAchieveRelease
     * @param level
     * @param percent
     * @return
     */
    private BigDecimal releaseByLevel(BigDecimal levelAchieveRelease,String level,BigDecimal percent,String scoreNo){
        //实际支付的凭证数量
        BigDecimal levelReleaseReal = BigDecimal.ZERO;
        //当前星级的人数
        List<MallMember> levelMembers = mallMemberMapper.selectMemberWithLevel(level);
        if(CollUtil.isNotEmpty(levelMembers)){
            //这个星级该获得的凭证数量 = 总数 * 比例
            BigDecimal levelReleaseCnt = levelAchieveRelease.multiply(percent).setScale(2, BigDecimal.ROUND_DOWN);
            if(levelReleaseCnt.compareTo(BigDecimal.ZERO) > 0){
                //每个人获得的数量
                BigDecimal levelRelease = levelReleaseCnt.divide(new BigDecimal(levelMembers.size()), 2, BigDecimal.ROUND_DOWN);
                if(levelRelease.compareTo(BigDecimal.ZERO) > 0){
                    for(MallMember mallMember : levelMembers){
                        releaseToMemberAndAddFlow(levelRelease,mallMember.getId(),MoneyFlowTypeEnum.ACHIEVE_RELEASE_SCORE_XJ.getValue(),scoreNo);
                        levelReleaseReal.add(levelRelease);
                    }
                }
            }
        }
        return levelReleaseReal;
    }
    /**
     * 获取每日最大产生的凭证数量
     * @return
     */
    private BigDecimal getAchieveDailyRelease(){
        DataDictionaryCustom achieveReleasePercentDic = dataDictionaryCustomMapper.selectDicDataByTypeAndCode(
                GreenScoreEnum.ACHIEVE_RELEASE_PERCENT.getType(),
                GreenScoreEnum.ACHIEVE_RELEASE_PERCENT.getCode()
        );
        BigDecimal achieveReleasePercent = new BigDecimal(achieveReleasePercentDic.getValue() == null ? "0" : achieveReleasePercentDic.getValue())
                .multiply(new BigDecimal(0.0001));
        DataDictionaryCustom totalCntDic = dataDictionaryCustomMapper.selectDicDataByTypeAndCode(
                GreenScoreEnum.TOTAL_CNT.getType(),
                GreenScoreEnum.TOTAL_CNT.getCode()
        );
        //总凭证数量
        BigDecimal totalCnt = new BigDecimal(totalCntDic.getValue() == null ? "0" : totalCntDic.getValue()).multiply(new BigDecimal(0.9));
        //获取每日最大产生的凭证数量
        BigDecimal achieveRelease = totalCnt.multiply(achieveReleasePercent);
        return achieveRelease;
    }
    @Override
    public void allInternetProfit() {
        log.info("###全网分红执行--start--###");
        MallSystemSetting systemSetting = mallSystemSettingMapper.selectById(1L);
        if (systemSetting == null) {
            log.info("没有系统配置");
            return;
        }
        BigDecimal hundred = BigDecimal.valueOf(100);
        DataDictionaryCustom dic = dataDictionaryCustomMapper.selectDicDataByTypeAndCode(DataDictionaryEnum.ALL_INTERNET_BONUS_RELEASE.getType(), DataDictionaryEnum.ALL_INTERNET_BONUS_RELEASE.getCode());
        if (dic == null || StrUtil.isBlank(dic.getValue()) || Integer.parseInt(dic.getValue()) == 0) {
            log.info("不进行全网分红");
            return;
        }
        // 全网分红
        BigDecimal waitToBonus = systemSetting.getAllBonus().multiply(new BigDecimal(dic.getValue()).divide(hundred, 2, RoundingMode.HALF_UP));
        List<MallMember> mallMembers = mallMemberMapper.selectMemberAfterLevelList(MemberLevelEnums.FIRST_LEVEL_Y.getCode());
        if (CollUtil.isEmpty(mallMembers) || waitToBonus.compareTo(BigDecimal.ZERO) < 1) {
            log.info("待分红金额不足或会员不足");
            return;
        }
        List<DataDictionaryCustom> dicList = dataDictionaryCustomMapper.selectDicByType(DataDictionaryEnum.INTERNET_LEVEL_BONUS.getType());
        if (CollUtil.isEmpty(dicList)) {
            return;
        }
        Map<String, BigDecimal> levelBonusMap = new HashMap<>();
        dicList.forEach(item -> {
            BigDecimal levelRatio = new BigDecimal(item.getValue()).divide(hundred, 2, RoundingMode.HALF_UP);
            levelBonusMap.put(item.getCode(), waitToBonus.multiply(levelRatio));
        });
        Map<String, List<MallMember>> levelMemberMap = new HashMap<>();
        // TODO 并发处理
        mallMembers.forEach(item -> {
            List<MallMember> memberList = levelMemberMap.get(item.getLevel());
            if (CollUtil.isEmpty(memberList)) {
                memberList = new ArrayList<>();
            }
            memberList.add(item);
            levelMemberMap.put(item.getLevel(), memberList);
        });
        if (levelMemberMap.isEmpty()) {
            return;
        }
        for (Map.Entry<String, List<MallMember>> entry : levelMemberMap.entrySet()) {
            BigDecimal levelBonus = levelBonusMap.get(entry.getKey());
            List<MallMember> memberList = entry.getValue();
            if (CollUtil.isEmpty(memberList) || levelBonus.compareTo(BigDecimal.ZERO) < 1) {
                continue;
            }
            BigDecimal perBonus = levelBonus.divide(BigDecimal.valueOf(memberList.size()), 2, RoundingMode.HALF_UP);
            memberList.forEach(item -> {
                changeScoreAndCommission(item.getId(), perBonus, 2, null);
            });
        }
        log.info("###全网分红执行--end--###");
    }
}