From 8b74444e85757e588b234ef992a205271688795e Mon Sep 17 00:00:00 2001
From: KKSU <15274802129@163.com>
Date: Fri, 12 Jan 2024 16:22:19 +0800
Subject: [PATCH] 套餐

---
 src/main/java/cc/mrbird/febs/mall/service/impl/MemberProfitServiceImpl.java |  486 +++++++++++++++++++++++++++++++++++++++--------------
 1 files changed, 359 insertions(+), 127 deletions(-)

diff --git a/src/main/java/cc/mrbird/febs/mall/service/impl/MemberProfitServiceImpl.java b/src/main/java/cc/mrbird/febs/mall/service/impl/MemberProfitServiceImpl.java
index f087359..ca42d7a 100644
--- a/src/main/java/cc/mrbird/febs/mall/service/impl/MemberProfitServiceImpl.java
+++ b/src/main/java/cc/mrbird/febs/mall/service/impl/MemberProfitServiceImpl.java
@@ -1,10 +1,9 @@
 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.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;
@@ -13,10 +12,14 @@
 import cc.mrbird.febs.mall.service.IMemberProfitService;
 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 lombok.RequiredArgsConstructor;
@@ -45,23 +48,32 @@
     private final IMallMoneyFlowService moneyFlowService;
     private final DataDictionaryCustomMapper dataDictionaryCustomMapper;
     private final MallMoneyFlowMapper mallMoneyFlowMapper;
-    private final IMallAchieveService mallAchieveService;
+    private final MallAchieveRecordMapper mallAchieveRecordMapper;
+    private final RedisUtils redisUtils;
+    private final MallMemberWalletMapper mallMemberWalletMapper;
+    private final IApiMallMemberWalletService iApiMallMemberWalletService;
 
     @Override
     @Transactional(rollbackFor = Exception.class)
-    public void staticProfit() {
+    public void staticProfit(Date profitDate) {
         log.info("#####静态分红开始运行:{}#####", new Date());
         List<MallMember> members = mallMemberMapper.selectList(null);
         if (CollUtil.isEmpty(members)) {
             return;
         }
 
-        Date profitDate = DateUtil.offset(new Date(), DateField.DAY_OF_YEAR, -1);
+        /**
+         *
+         */
+        if (profitDate == null) {
+            profitDate = DateUtil.offset(new Date(), DateField.DAY_OF_YEAR, -1);
+        }
         // 套餐业绩
-        BigDecimal tcIncome = mallOrderInfoMapper.selectTotalAmountUnCostForDate(profitDate, null, "D", 2);
+//        BigDecimal tcIncome = mallOrderInfoMapper.selectTotalAmountUnCostForDate(profitDate, null, "D", 2);
         // 普通商品业绩
-        BigDecimal normalIncome = mallOrderInfoMapper.selectTotalAmountUnCostForDate(profitDate, null, "D", 1);
-        BigDecimal totalIncome = tcIncome.add(normalIncome);
+//        BigDecimal normalIncome = mallOrderInfoMapper.selectTotalAmountUnCostForDate(profitDate, null, "D", 1);
+        //今日总业绩
+        BigDecimal totalIncome = mallAchieveRecordMapper.selectAchieveTotal("D", profitDate);
 
         if (totalIncome.compareTo(BigDecimal.ZERO) == 0) {
             return;
@@ -106,19 +118,27 @@
                 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");
-
-                    int reduce = walletService.reduce(preStaticProfit, memberId, "score");
-                    if (reduce == 2) {
-                        break;
-                    }
-
-                    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());
+                    changeAllScoreAndCommission(preStaticProfit,orderNo);
+//                    int reduce = walletService.reduce(preStaticProfit, memberId, "score");
+//                    if (reduce == 2) {
+//                        break;
+//                    }
+//
+//                    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);
                 }
             }
+        }
+    }
+
+    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);
         }
     }
 
@@ -167,9 +187,9 @@
             }
 
             // 判断套餐或者普通商品,结算对应商品的动态分红
-            if (!Objects.equals(item.getIsNormal(), isNormal)) {
-                continue;
-            }
+//            if (!Objects.equals(item.getIsNormal(), isNormal)) {
+//                continue;
+//            }
 
             // =======直推返利== start =====
             // 直接奖励收益
@@ -179,15 +199,18 @@
                 continue;
             }
 
-            int reduce = walletService.reduce(dynamicProfit, parent.getId(), "score");
-            if (reduce == 2) {
+//            int reduce = walletService.reduce(dynamicProfit, parent.getId(), "score");
+//            if (reduce == 2) {
+//                continue;
+//            }
+//            walletService.add(dynamicProfit, parent.getId(), "commission");
+//            moneyFlowService.addMoneyFlow(parent.getId(), dynamicProfit, MoneyFlowTypeEnum.DYNAMIC_ACHIEVE.getValue(), orderInfo.getOrderNo(), FlowTypeEnum.COMMISSION.getValue());
+//            moneyFlowService.addMoneyFlow(parent.getId(), dynamicProfit.negate(), MoneyFlowTypeEnum.DYNAMIC_ACHIEVE.getValue(), orderInfo.getOrderNo(), FlowTypeEnum.SCORE.getValue());
+
+            dynamicProfit = changeScoreAndCommission(parent.getId(), dynamicProfit, MoneyFlowTypeEnum.DYNAMIC_ACHIEVE.getValue(), orderInfo.getOrderNo());
+            if (dynamicProfit.compareTo(BigDecimal.ZERO) < 1) {
                 continue;
             }
-
-            walletService.add(dynamicProfit, parent.getId(), "commission");
-
-            moneyFlowService.addMoneyFlow(parent.getId(), dynamicProfit, MoneyFlowTypeEnum.DYNAMIC_ACHIEVE.getValue(), orderInfo.getOrderNo(), FlowTypeEnum.COMMISSION.getValue());
-            moneyFlowService.addMoneyFlow(parent.getId(), dynamicProfit.negate(), MoneyFlowTypeEnum.DYNAMIC_ACHIEVE.getValue(), orderInfo.getOrderNo(), FlowTypeEnum.SCORE.getValue());
             // =======直推返利== end =====
 
             // =======隔代奖== start =====
@@ -211,7 +234,7 @@
                 Integer directCnt = mallMemberMapper.selectOwnCntByInviteId(parentMember.getInviteId());
                 List<DataDictionaryCustom> dataDices = dataDictionaryCustomMapper.selectDicByType(DataDictionaryEnum.INDIRECT_BONUS_SETTING.getType());
 
-                directCnt = directCnt == null ? 0 :directCnt;
+                directCnt = directCnt == null ? 0 : directCnt;
 
                 // 隔代比例
                 BigDecimal indrectDicProp = BigDecimal.ZERO;
@@ -229,15 +252,15 @@
                 if (direct.compareTo(BigDecimal.ONE) < 1) {
                     break;
                 }
-
-                int reduceResult =  walletService.reduce(direct, parentMember.getId(), "score");
-                if (reduceResult == 2) {
-                    continue;
-                }
-
-                walletService.add(direct, parentMember.getId(), "commission");
-                moneyFlowService.addMoneyFlow(parentMember.getId(), direct, MoneyFlowTypeEnum.RECOMMEND_BONUS.getValue(), orderInfo.getOrderNo(), FlowTypeEnum.COMMISSION.getValue());
-                moneyFlowService.addMoneyFlow(parentMember.getId(), direct.negate(), MoneyFlowTypeEnum.RECOMMEND_BONUS.getValue(), orderInfo.getOrderNo(), FlowTypeEnum.SCORE.getValue());
+//                int reduceResult = walletService.reduce(direct, parentMember.getId(), "score");
+//                if (reduceResult == 2) {
+//                    continue;
+//                }
+//
+//                walletService.add(direct, parentMember.getId(), "commission");
+//                moneyFlowService.addMoneyFlow(parentMember.getId(), direct, MoneyFlowTypeEnum.RECOMMEND_BONUS.getValue(), orderInfo.getOrderNo(), FlowTypeEnum.COMMISSION.getValue());
+//                moneyFlowService.addMoneyFlow(parentMember.getId(), direct.negate(), MoneyFlowTypeEnum.RECOMMEND_BONUS.getValue(), orderInfo.getOrderNo(), FlowTypeEnum.SCORE.getValue());
+                changeScoreAndCommission(parentMember.getId(), direct, MoneyFlowTypeEnum.RECOMMEND_BONUS.getValue(), orderInfo.getOrderNo());
             }
             // =======隔代奖== end =====
         }
@@ -251,43 +274,64 @@
             profitDate = DateUtil.offset(new Date(), DateField.DAY_OF_YEAR, -1);
         }
         // 套餐业绩
-        BigDecimal tcIncome = mallOrderInfoMapper.selectTotalAmountUnCostForDate(profitDate, null, "D", 2);
+//        BigDecimal tcIncome = mallOrderInfoMapper.selectTotalAmountUnCostForDate(profitDate, null, "D", 2);
         // 普通商品业绩
-        BigDecimal normalIncome = mallOrderInfoMapper.selectTotalAmountUnCostForDate(profitDate, null, "D", 1);
-        BigDecimal totalIncome = tcIncome.add(normalIncome);
+//        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.divide(new BigDecimal(dic.getValue()), 2, RoundingMode.HALF_UP);
-        BigDecimal preProfit = profit.divide(BigDecimal.valueOf(100), 2, RoundingMode.HALF_UP);
+        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;
         }
 
-        for (MallMember agentMember : agentMembers) {
-            DataDictionaryCustom agentDic = dataDictionaryCustomMapper.selectDicDataByTypeAndCode(AppContants.AGENT_LEVEL_REQUIRE, agentMember.getLevel());
-
-            if (agentDic == null) {
-                continue;
-            }
-
+        List<DataDictionaryCustom> dics = dataDictionaryCustomMapper.selectDicByType(AppContants.AGENT_LEVEL_REQUIRE);
+        for (DataDictionaryCustom agentDic : dics) {
             JSONObject jsonObject = JSONObject.parseObject(agentDic.getValue());
-            BigDecimal profitProp = jsonObject.getBigDecimal("profitProp");
-            BigDecimal income = preProfit.multiply(profitProp);
+            BigDecimal profitProp = jsonObject.getBigDecimal("profitProp").divide(new BigDecimal("100"), 2, RoundingMode.HALF_UP);
 
-            int reduce = walletService.reduce(income, agentMember.getId(), "score");
-            if (reduce == 2) {
+            List<MallMember> agentMemberList = mallMemberMapper.selectMemberWithLevel(agentDic.getCode());
+            if (CollUtil.isEmpty(agentMemberList)) {
                 continue;
             }
 
-            walletService.add(income, agentMember.getId(), "commission");
+            BigDecimal income = profit.multiply(profitProp).divide(BigDecimal.valueOf(agentMemberList.size()), 2, RoundingMode.HALF_UP);
+            if (income.compareTo(BigDecimal.ZERO) < 1) {
+                continue;
+            }
 
-            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());
+            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==#####");
+    }
+
+    private BigDecimal changeScoreAndCommission(Long memberId, BigDecimal income, Integer type, String orderNo) {
+        Map<String, BigDecimal> map = new HashMap<>();
+        map.put("amount", income);
+
+        int reduce = walletService.reduce(income, memberId, "score", map);
+        if (reduce == 2) {
+            return BigDecimal.ZERO;
         }
 
-        log.info("#####==代理分红==end==#####");
+        income = map.get("amount");
+        walletService.add(income, memberId, "commission");
+        moneyFlowService.addMoneyFlow(memberId, income, type, orderNo, FlowTypeEnum.COMMISSION.getValue());
+        moneyFlowService.addMoneyFlow(memberId, income.negate(), type, orderNo, FlowTypeEnum.SCORE.getValue());
+        return income;
     }
 
     @Override
@@ -296,6 +340,7 @@
         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);
@@ -306,84 +351,130 @@
         }
 
         // 套餐业绩
-        BigDecimal tcIncome = mallOrderInfoMapper.selectTotalAmountUnCostForDate(profitDate, null, "M", 2);
+//        BigDecimal tcIncome = mallOrderInfoMapper.selectTotalAmountUnCostForDate(profitDate, null, "M", 2);
         // 普通商品业绩
-        BigDecimal normalIncome = mallOrderInfoMapper.selectTotalAmountUnCostForDate(profitDate, null, "M", 1);
-        BigDecimal totalIncome = tcIncome.add(normalIncome);
+//        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);
+        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;
-            }
+//            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());
 
-            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() {
+    public void thankfulProfit(Date date) {
         log.info("######==感恩奖==start==####");
-        List<MallMember> mallMembers = mallMemberMapper.selectMemberListHasChild();
-        if (CollUtil.isEmpty(mallMembers)) {
+        List<MallAchieveRecord> mallAchieveRecordList = mallAchieveRecordMapper.selectListByCostAmountAndIsNorMal(BigDecimal.ZERO,2);
+        if(CollUtil.isEmpty(mallAchieveRecordList)){
             return;
         }
+        DataDictionaryCustom yiPositionDic = dataDictionaryCustomMapper.selectDicDataByTypeAndCode(
+                DataDictionaryEnum.YI_POSITION.getType(),
+                DataDictionaryEnum.YI_POSITION.getCode()
+        );
+        BigDecimal yiPosition = new BigDecimal(yiPositionDic.getValue());
+        DataDictionaryCustom yiPositionPercentDic = dataDictionaryCustomMapper.selectDicDataByTypeAndCode(
+                DataDictionaryEnum.YI_POSITION_PERCENT.getType(),
+                DataDictionaryEnum.YI_POSITION_PERCENT.getCode()
+        );
+        BigDecimal yiPositionPercent = new BigDecimal(yiPositionPercentDic.getValue()).multiply(new BigDecimal("0.01"));
 
-        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);
+        DataDictionaryCustom erPositionDic = dataDictionaryCustomMapper.selectDicDataByTypeAndCode(
+                DataDictionaryEnum.ER_POSITION.getType(),
+                DataDictionaryEnum.ER_POSITION.getCode()
+        );
+        BigDecimal erPosition = new BigDecimal(erPositionDic.getValue());
+        DataDictionaryCustom erPositionPercentDic = dataDictionaryCustomMapper.selectDicDataByTypeAndCode(
+                DataDictionaryEnum.ER_POSITION_PERCENT.getType(),
+                DataDictionaryEnum.ER_POSITION_PERCENT.getCode()
+        );
+        BigDecimal erPositionPercent = new BigDecimal(erPositionPercentDic.getValue()).multiply(new BigDecimal("0.01"));
 
-        Date date = DateUtil.offset(new Date(), DateField.DAY_OF_YEAR, -1);
-        for (MallMember mallMember : mallMembers) {
-            BigDecimal income = mallMoneyFlowMapper.selectThankfulCommission(date, mallMember.getId());
-            List<MallMember> children = mallMemberMapper.selectMemberDirectForHasLevel(mallMember.getInviteId());
-            if (CollUtil.isEmpty(children)) {
+        DataDictionaryCustom sanPositionDic = dataDictionaryCustomMapper.selectDicDataByTypeAndCode(
+                DataDictionaryEnum.SAN_POSITION.getType(),
+                DataDictionaryEnum.SAN_POSITION.getCode()
+        );
+        BigDecimal sanPosition = new BigDecimal(sanPositionDic.getValue());
+        DataDictionaryCustom sanPositionPercentDic = dataDictionaryCustomMapper.selectDicDataByTypeAndCode(
+                DataDictionaryEnum.SAN_POSITION_PERCENT.getType(),
+                DataDictionaryEnum.SAN_POSITION_PERCENT.getCode()
+        );
+        BigDecimal sanPositionPercent = new BigDecimal(sanPositionPercentDic.getValue()).multiply(new BigDecimal("0.01"));
+
+        DataDictionaryCustom siPositionDic = dataDictionaryCustomMapper.selectDicDataByTypeAndCode(
+                DataDictionaryEnum.SI_POSITION.getType(),
+                DataDictionaryEnum.SI_POSITION.getCode()
+        );
+        BigDecimal siPosition = new BigDecimal(siPositionDic.getValue());
+        DataDictionaryCustom siPositionPercentDic = dataDictionaryCustomMapper.selectDicDataByTypeAndCode(
+                DataDictionaryEnum.SI_POSITION_PERCENT.getType(),
+                DataDictionaryEnum.SI_POSITION_PERCENT.getCode()
+        );
+        BigDecimal siPositionPercent = new BigDecimal(siPositionPercentDic.getValue()).multiply(new BigDecimal("0.01"));
+        for(MallAchieveRecord mallAchieveRecord : mallAchieveRecordList){
+            Long orderId = mallAchieveRecord.getOrderId();
+            MallOrderInfo mallOrderInfo = mallOrderInfoMapper.selectById(orderId);
+            if(OrderStatusEnum.FINISH.getValue() != mallOrderInfo.getStatus()){
                 continue;
             }
-
-            BigDecimal reduceProfit = income.multiply(prop);
-            if (reduceProfit.compareTo(BigDecimal.ZERO) < 1) {
+            BigDecimal percent = BigDecimal.ZERO;//比例
+            BigDecimal amount = mallAchieveRecord.getAmount();//总业绩
+            BigDecimal costAmount = mallAchieveRecord.getCostAmount();//剩余业绩
+            if(amount.compareTo(yiPosition) < 0){
+                continue;
+            }else if(amount.compareTo(yiPosition) >= 0 && amount.compareTo(erPosition) < 0){
+                percent = yiPositionPercent;
+            }else if(amount.compareTo(erPosition) >= 0 && amount.compareTo(sanPosition) < 0){
+                percent = erPositionPercent;
+            }else if(amount.compareTo(sanPosition) >= 0 && amount.compareTo(siPosition) < 0){
+                percent = sanPositionPercent;
+            }else{
+                percent = siPositionPercent;
+            }
+            BigDecimal perk = amount.multiply(percent).setScale(2,BigDecimal.ROUND_DOWN);//实际发送的余额
+            if(BigDecimal.ZERO.compareTo(perk) >= 0){
                 continue;
             }
-
-            int reduce = walletService.reduce(reduceProfit, mallMember.getId(), "commission");
-            if (reduce == 2) {
-                continue;
+            if(perk.compareTo(costAmount) >= 0){
+                perk = costAmount;
             }
+            costAmount = costAmount.subtract(perk);
+            mallAchieveRecord.setCostAmount(costAmount);
+            mallAchieveRecordMapper.updateById(mallAchieveRecord);
+            //增加
+            iApiMallMemberWalletService.add(perk,mallAchieveRecord.getMemberId(),"balance");
+            //增加一个流水记录
+            moneyFlowService.addMoneyFlow(
+                    mallAchieveRecord.getMemberId(),
+                    perk,
+                    MoneyFlowTypeEnum.TC_TO_BALANCE.getValue(),
+                    mallOrderInfo.getOrderNo(),
+                    mallAchieveRecord.getMemberId(),
+                    FlowTypeEnum.BALANCE.getValue(),
+                    AppContants.IS_RETURN_YES);
 
-            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());
-            }
         }
         log.info("######==感恩奖==end==####");
     }
@@ -395,10 +486,10 @@
             profitDate = DateUtil.offset(new Date(), DateField.DAY_OF_YEAR, -1);
         }
         // 套餐业绩
-        BigDecimal tcIncome = mallOrderInfoMapper.selectTotalAmountUnCostForDate(profitDate, null, "D", 2);
+//        BigDecimal tcIncome = mallOrderInfoMapper.selectTotalAmountUnCostForDate(profitDate, null, "D", 2);
         // 普通商品业绩
-        BigDecimal normalIncome = mallOrderInfoMapper.selectTotalAmountUnCostForDate(profitDate, null, "D", 1);
-        BigDecimal totalIncome = tcIncome.add(normalIncome);
+//        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());
@@ -412,14 +503,14 @@
                     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());
+//                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);
             }
         }
 
@@ -435,17 +526,158 @@
                     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());
+//                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(everydayRatio);
+        String scorePoolRedis = redisUtils.getString(redisKey);
+        if(StrUtil.isBlank(scorePoolRedis)){
+            redisUtils.set(redisKey,0,0L);
+        }
+
+        BigDecimal scorePoolOld = new BigDecimal(redisUtils.getString(redisKey));
+        BigDecimal scorePoolNew = scorePoolOld.add(multiplyTotalAmount);
+
+        //每天释放1%给全体用户
+        BigDecimal scorePoolToDay = scorePoolNew.multiply(dividEquallyRatio);
+
+        redisUtils.set(redisKey,scorePoolNew.subtract(scorePoolToDay).intValue(),0L);
+
+        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){
+                return;
+            }
+            for(MallMember mallMember : mallMembers){
+                /*
+                平分成佣金,一比一减少赠送积分
+                如果没有赠送积分,则平分0
+                 */
+                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{
+                    outCome = income;
+                }
+                walletService.add(outCome, mallMember.getId(), "commission");
+                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==######;" +
+                "今日新增积分:" + multiplyTotalAmount.setScale(2, RoundingMode.HALF_UP)
+                +";平分积分数量:"+scorePoolToDay.setScale(2, RoundingMode.HALF_UP)
+                +";人数:"+cnt);
+    }
+
+    @Override
+    public void fireJob(Object o) {
+        List<MallMemberWallet> mallMemberWallets = mallMemberWalletMapper.seleListByScore();
+        if(CollUtil.isEmpty(mallMemberWallets)){
+            return;
+        }
+        DataDictionaryCustom dataDictionaryCustom = dataDictionaryCustomMapper.selectDicDataByTypeAndCode(
+                DataDictionaryEnum.FIRE_SCORE_PERCENT.getType(),
+                DataDictionaryEnum.FIRE_SCORE_PERCENT.getCode()
+        );
+        BigDecimal fireScorePercent = new BigDecimal(dataDictionaryCustom.getValue()).multiply(new BigDecimal("0.01"));
+
+        BigDecimal totalReduce = BigDecimal.ZERO;
+        for(MallMemberWallet mallMemberWallet : mallMemberWallets){
+            BigDecimal score = mallMemberWallet.getScore();
+            BigDecimal multiply = score.multiply(fireScorePercent).setScale(2,BigDecimal.ROUND_DOWN);//每次需要燃烧的数量
+            if(BigDecimal.ZERO.compareTo(multiply) >= 0){
+                continue;
+            }
+            iApiMallMemberWalletService.reduce(multiply,mallMemberWallet.getMemberId(),"score");
+            //增加一个流水记录
+            moneyFlowService.addMoneyFlow(
+                    mallMemberWallet.getMemberId(),
+                    multiply.negate(),
+                    MoneyFlowTypeEnum.FIRE_SCORE.getValue(),
+                    null,
+                    mallMemberWallet.getMemberId(),
+                    FlowTypeEnum.SCORE.getValue(),
+                    AppContants.IS_RETURN_YES);
+            totalReduce = totalReduce.add(multiply);
+        }
+        if(BigDecimal.ZERO.compareTo(totalReduce) >= 0){
+            return;
+        }
+        /**
+         * H金劵减少,更新价格
+         */
+        DataDictionaryCustom poolCashDic = dataDictionaryCustomMapper.selectDicDataByTypeAndCode(
+                PerkEnum.POOL_CASH.getType(),
+                PerkEnum.POOL_CASH.getCode());
+        //当前现金池数量
+        BigDecimal poolCash = new BigDecimal(poolCashDic.getValue());
+        DataDictionaryCustom poolScoreDic = dataDictionaryCustomMapper.selectDicDataByTypeAndCode(
+                PerkEnum.POOL_SCORE.getType(),
+                PerkEnum.POOL_SCORE.getCode());
+        //当前H金劵池数量
+        BigDecimal poolScore = new BigDecimal(poolScoreDic.getValue());
+        poolScore = poolScore.subtract(totalReduce).setScale(2,BigDecimal.ROUND_DOWN);
+        dataDictionaryCustomMapper.updateDicValueByTypeAndCode(
+                PerkEnum.POOL_SCORE.getType(),
+                PerkEnum.POOL_SCORE.getCode(),
+                poolScore.toString()
+        );
+
+        if(poolScore.compareTo(BigDecimal.ZERO) > 0 && poolCash.compareTo(BigDecimal.ZERO) > 0){
+            BigDecimal divide = poolCash.divide(poolScore, 8, BigDecimal.ROUND_DOWN);
+            dataDictionaryCustomMapper.updateDicValueByTypeAndCode(
+                    PerkEnum.POOL_SCORE_PRICE.getType(),
+                    PerkEnum.POOL_SCORE_PRICE.getCode(),
+                    divide.toString()
+            );
+        }
+    }
+
 }

--
Gitblit v1.9.1