MonthTaskServiceImpl.java 35.7 KB
Newer Older
1 2
package cn.wisenergy.service.app.impl;

licc's avatar
licc committed
3 4 5
import cn.wisenergy.common.utils.DateUtil;
import cn.wisenergy.common.utils.R;
import cn.wisenergy.mapper.*;
6

licc's avatar
licc committed
7 8 9 10 11
import cn.wisenergy.model.app.*;
import cn.wisenergy.model.enums.MemberPercentEnum;
import cn.wisenergy.model.enums.TradeRecordEnum;
import cn.wisenergy.model.enums.TradeStatusEnum;
import cn.wisenergy.model.enums.UserLevelEnum;
licc's avatar
licc committed
12
import cn.wisenergy.model.vo.TeamPerformanceSortVo;
licc's avatar
licc committed
13 14
import cn.wisenergy.service.Manager.AccountManager;
import cn.wisenergy.service.Manager.PublicManager;
licc's avatar
licc committed
15
import cn.wisenergy.service.app.DayTaskService;
16
import cn.wisenergy.service.app.MonthTaskService;
licc's avatar
licc committed
17
import com.xxl.job.core.handler.annotation.XxlJob;
licc's avatar
licc committed
18 19 20 21 22 23
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
licc's avatar
licc committed
24
import java.math.RoundingMode;
licc's avatar
licc committed
25
import java.util.*;
26 27 28 29

/**
 * @author 86187
 */
licc's avatar
licc committed
30 31
@Slf4j
@Service
32
public class MonthTaskServiceImpl implements MonthTaskService {
licc's avatar
licc committed
33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61

    @Autowired
    private LastAccountMapper lastAccountMapper;

    @Autowired
    private UsersMapper usersMapper;

    @Autowired
    private AccountMapper accountMapper;

    @Autowired
    private MemberPercentMapper memberPercentMapper;

    @Autowired
    private AccountManager accountManager;

    @Autowired
    private PublicManager publicManager;

    @Autowired
    private TradeRecordMapper tradeRecordMapper;

    @Autowired
    private TeamPerformanceMapper teamPerformanceMapper;

    @Autowired
    private ProgressPrizeMapper progressPrizeMapper;

    @Autowired
licc's avatar
licc committed
62
    private DayTaskService dayTaskService;
licc's avatar
licc committed
63 64 65 66

    @Autowired
    private MonthManureMapper monthManureMapper;

licc's avatar
licc committed
67 68 69
    @Autowired
    private MonthAwardMapper monthAwardMapper;

licc's avatar
licc committed
70 71 72 73 74 75 76 77

    @Autowired
    private OrderMapper orderMapper;

    private static final String PATTERN = "yyyy-MM";

    private static final Integer TWENTY = 20;

licc's avatar
licc committed
78
    @XxlJob(value = "monthManureMonthTask")
licc's avatar
licc committed
79
    @Override
licc's avatar
licc committed
80 81 82 83
    public R<Boolean> performanceCount() {
        //获取上月订单
        Date lastMonth = DateUtil.getLastMonth(new Date());
        List<OrderInfo> list = orderMapper.getByCreateTime(lastMonth);
licc's avatar
licc committed
84
        log.info("shop-mall[]MonthTaskServiceImpl[]performanceCount[]input.param.list:{}", list.size());
licc's avatar
licc committed
85 86 87 88
        if (CollectionUtils.isEmpty(list)) {
            return R.ok(0, true);
        }

licc's avatar
licc committed
89
        String yearMonth = DateUtil.convertDateToStr(lastMonth, PATTERN);
licc's avatar
licc committed
90

licc's avatar
licc committed
91
        //计算上月所有订单成交额
licc's avatar
licc committed
92 93
        BigDecimal totalMoney = new BigDecimal(0);

licc's avatar
licc committed
94 95
        //统计出出每个用户上月订单成交额 key:userId  value:用户上月订单成交额
        Map<String, Double> map = new HashMap<>();
licc's avatar
licc committed
96
        for (OrderInfo orderInfo : list) {
codezwjava's avatar
codezwjava committed
97
            String userId = orderInfo.getUserId();
licc's avatar
licc committed
98 99 100 101
            double payMoney = orderInfo.getPayment().doubleValue();

            //key 存在  累加订单金额 到 value
            if (map.containsKey(userId)) {
codezwjava's avatar
codezwjava committed
102 103
                double money = payMoney + map.get(orderInfo.getUserId());
                map.put(orderInfo.getUserId(), money);
licc's avatar
licc committed
104 105 106
            } else {
                //key 不存在,加入集合
                map.put(userId, payMoney);
licc's avatar
licc committed
107
            }
licc's avatar
licc committed
108

licc's avatar
licc committed
109 110 111
            //累加所以订单成交额
            totalMoney = totalMoney.add(orderInfo.getPayment());
        }
licc's avatar
licc committed
112

licc's avatar
licc committed
113 114
        //累计用户和上级用户-团队业绩
        Map<String, Double> tempMap = new HashMap<>();
licc's avatar
licc committed
115

licc's avatar
licc committed
116 117 118 119 120
        //遍历订单
        for (Map.Entry<String, Double> entity : map.entrySet()) {
            String userId = entity.getKey();
            //1)、统计当前用户月度业绩
            double userCount = entity.getValue();
121 122 123 124 125 126 127 128
            //key 存在  当前用户团队绩效  + 上级用户团队绩效
            if (tempMap.containsKey(entity.getKey())) {
                double teamMoney = userCount + tempMap.get(entity.getKey());
                tempMap.put(entity.getKey(), teamMoney);
            } else {
                //key 不存在,加入集合 当前用户团队绩效
                tempMap.put(entity.getKey(), userCount);
            }
licc's avatar
licc committed
129

licc's avatar
licc committed
130
            //2)、获取当前用户的上级用户列表
licc's avatar
licc committed
131
            List<User> userList = dayTaskService.getByList(userId);
licc's avatar
licc committed
132 133 134
            if (CollectionUtils.isEmpty(userList)) {
                continue;
            }
licc's avatar
licc committed
135

licc's avatar
licc committed
136
            for (User user : userList) {
licc's avatar
licc committed
137 138
                //3)、统计当前用户的上级用户团队绩效
                //key 存在  当前用户团队绩效  + 上级用户团队绩效
licc's avatar
licc committed
139 140 141
                if (tempMap.containsKey(user.getUserId())) {
                    double teamMoney = userCount + tempMap.get(user.getUserId());
                    tempMap.put(user.getUserId(), teamMoney);
licc's avatar
licc committed
142 143
                } else {
                    //key 不存在,加入集合 当前用户团队绩效
licc's avatar
licc committed
144
                    tempMap.put(user.getUserId(), userCount);
licc's avatar
licc committed
145
                }
licc's avatar
licc committed
146
            }
licc's avatar
licc committed
147
        }
licc's avatar
licc committed
148

licc's avatar
licc committed
149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169
        //3、获取用户上月绩效信息   新增 or 更新
        List<TeamPerformance> addList = new ArrayList<>();
        List<TeamPerformance> updateList = new ArrayList<>();
        for (Map.Entry<String, Double> entity : tempMap.entrySet()) {
            //获取团队业绩信息
            TeamPerformance teamPerformance = teamPerformanceMapper.getByUserIdAndTime(entity.getKey(), yearMonth);
            if (null == teamPerformance) {
                //获取用户信息
                User user = usersMapper.getByUserId(entity.getKey());

                //添加用户团队业绩信息
                TeamPerformance performance = new TeamPerformance();
                performance.setUserId(user.getUserId());
                performance.setMonthTeamPerformance(BigDecimal.valueOf(entity.getValue()));
                performance.setUserLevel(user.getUserLevel());
                performance.setYearMonth(yearMonth);
                addList.add(performance);
            } else {
                teamPerformance.setMonthTeamPerformance(BigDecimal.valueOf(entity.getValue()));
                updateList.add(teamPerformance);
            }
licc's avatar
licc committed
170
        }
licc's avatar
licc committed
171 172

        //4、更新账户月度绩效
173 174
        boolean updateBool = accountManager.updateAccountPerformanceMonth(addList, updateList);
        if (!updateBool) {
licc's avatar
licc committed
175 176
            return R.ok(1, false);
        }
licc's avatar
licc committed
177

licc's avatar
licc committed
178 179 180
        //5、获取所有用户,如果会员等级是黄金以上,计算月度收益
        List<User> userList = usersMapper.getAllGoldUser();
        if (CollectionUtils.isEmpty(userList)) {
licc's avatar
licc committed
181 182 183 184 185
            //获取黄金以上等级月度肥料收益比列之和
            Double memberSum = memberPercentMapper.getGoldUpSum();

            //添加月度肥料剩余奖金   总业绩 /3980/12*3980*(黄金以上比列相加)
            double manureMoney = Math.floor(totalMoney.doubleValue() / 3980 / 12 * 3980 * memberSum);
licc's avatar
licc committed
186
            MonthManure monthManure = new MonthManure();
licc's avatar
licc committed
187
            monthManure.setManureAward(manureMoney);
licc's avatar
licc committed
188 189 190 191 192 193 194 195
            monthManure.setYearMonth(yearMonth);
            int count = monthManureMapper.add(monthManure);
            if (count == 0) {
                return R.ok(1, false);
            }
            return R.ok(0, true);
        }

licc's avatar
licc committed
196 197 198
        //6、如果用户的团队业绩不存在的,新增本月团队业绩
        addTeamPerformance(userList);

licc's avatar
licc committed
199
        //6、计算收益
licc's avatar
licc committed
200 201 202 203 204 205 206
        boolean bool = monthlyIncome(totalMoney, userList);
        if (!bool) {
            return R.ok(1, false);
        }
        return R.ok(0, true);
    }

licc's avatar
licc committed
207
    @XxlJob(value = "growthAwardMonthTask")
licc's avatar
licc committed
208 209
    @Override
    public R<Boolean> progressPrizeCount() {
licc's avatar
licc committed
210 211 212
        log.info("shop-mall[]MonthTaskServiceImpl[]performanceCount[]input.method");
        Date date = DateUtil.getLastMonth(new Date());
        String lastMonth = DateUtil.convertDateToStr(date, PATTERN);
licc's avatar
licc committed
213 214 215 216 217 218 219 220 221 222 223 224
        //获取当月所有人业绩总额
        List<OrderInfo> orderList = orderMapper.getByCreateTime(date);
        if (CollectionUtils.isEmpty(orderList)) {
            return R.ok(0, true);
        }
        //获取上月月所有人业绩总额

        BigDecimal totalMoney = new BigDecimal(0);
        for (OrderInfo orderInfo : orderList) {
            totalMoney = totalMoney.add(orderInfo.getPayment());
        }
        double number = Math.floor(totalMoney.doubleValue() / 3980 / 12);
licc's avatar
licc committed
225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240

        //1、判断上月是否是业绩开始的第一个月
        List<TeamPerformance> teamPerformances = teamPerformanceMapper.getByBeforeTime(lastMonth);
        //2、集合为空 是业绩开始的第一个月
        if (CollectionUtils.isEmpty(teamPerformances)) {
            if (number != 0) {
                //获取上月业绩前20用户
                List<TeamPerformance> list = teamPerformanceMapper.userTwenty(lastMonth);
                if (CollectionUtils.isEmpty(list)) {
                    return R.ok(0, true);
                }

                //获取20名进步最大的月业绩和
                Double twentyTotal = teamPerformanceMapper.countTwenty(lastMonth);
                List<AccountInfo> accountInfoList = new ArrayList<>();
                List<TradeRecord> tradeRecordList = new ArrayList<>();
licc's avatar
licc committed
241 242
                List<ProgressPrize> addPrizeList = new ArrayList<>();
                List<ProgressPrize> updatePrizeList = new ArrayList<>();
licc's avatar
licc committed
243 244 245 246 247 248 249
                for (TeamPerformance user : list) {
                    //获取最大进步奖 百分比
                    MemberPercent memberPercent = memberPercentMapper.getByLevelAndType(user.getUserLevel(), 3);

                    //计算收益
                    double userTeamPerformance = user.getMonthTeamPerformance().doubleValue();
                    double percent = memberPercent.getPercent().doubleValue();
250
                    double income = Math.floor(number * 3980 * percent * userTeamPerformance / twentyTotal);
licc's avatar
licc committed
251

licc's avatar
licc committed
252
                    //获取账户信息  用户月收益  =其他收益+最大进步奖收益
licc's avatar
licc committed
253
                    AccountInfo accountInfo = accountMapper.getByUserId(user.getUserId());
254
                    BigDecimal earningsMonth = accountInfo.getEarningsMonth().add(BigDecimal.valueOf(income));
licc's avatar
licc committed
255
                    accountInfo.setEarningsMonth(earningsMonth.setScale(2, RoundingMode.HALF_UP));
256 257 258

                    //用户总收益 =其他总收益 + earningsMonth
                    BigDecimal earningsTotal = accountInfo.getEarningsTotal().add(BigDecimal.valueOf(income));
licc's avatar
licc committed
259
                    accountInfo.setEarningsTotal(earningsTotal.setScale(2, RoundingMode.HALF_UP));
licc's avatar
licc committed
260 261
                    accountInfoList.add(accountInfo);

licc's avatar
licc committed
262
                    //添加最大进步奖信息  不存在:新增   存在,修改
licc's avatar
licc committed
263
                    BigDecimal awardMoney = new BigDecimal(income).setScale(2, RoundingMode.HALF_UP);
licc's avatar
licc committed
264 265 266 267 268 269 270 271 272 273 274 275 276
                    ProgressPrize progressPrize = progressPrizeMapper.getByUserIdYearMonth(user.getUserId(), lastMonth);
                    if (null == progressPrize) {
                        ProgressPrize prize = new ProgressPrize();
                        prize.setAwardMoney(awardMoney.doubleValue());
                        prize.setUserId(user.getUserId());
                        prize.setGrowthRate(0.0);
                        prize.setYearMonth(lastMonth);
                        addPrizeList.add(prize);
                    } else {
                        progressPrize.setYearMonth(lastMonth);
                        progressPrize.setAwardMoney(awardMoney.doubleValue());
                        updatePrizeList.add(progressPrize);
                    }
licc's avatar
licc committed
277

licc's avatar
licc committed
278 279 280 281 282 283
                    //添加交易流水记录
                    TradeRecord tradeRecord = new TradeRecord();
                    tradeRecord.setUserId(user.getUserId());
                    tradeRecord.setTradeType(TradeRecordEnum.PROGRESS_PRIZE.getCode());
                    tradeRecord.setTradeNo(null);
                    tradeRecord.setStatus(TradeStatusEnum.ALREADY_SETTLE_ACCOUNTS.getCode());
licc's avatar
licc committed
284
                    tradeRecord.setMoney(BigDecimal.valueOf(income).setScale(2, RoundingMode.HALF_UP));
licc's avatar
licc committed
285 286 287 288
                    tradeRecordList.add(tradeRecord);
                }

                //更新账户信息,添加交易流水记录
licc's avatar
licc committed
289
                boolean bool = accountManager.updateAccountAddRecordAddPrize(accountInfoList, tradeRecordList,
290
                        addPrizeList, updatePrizeList);
licc's avatar
licc committed
291 292 293 294 295 296 297 298 299
                if (!bool) {
                    return R.ok(1, false);
                }
            }
            return R.ok(0, true);
        }

        //3、集合不为空 不是业绩开始的第一个月
        //获取用户列表
licc's avatar
licc committed
300
        List<User> userList = usersMapper.findAllNotZeroUser();
licc's avatar
licc committed
301 302 303 304
        if (CollectionUtils.isEmpty(userList)) {
            return R.ok(0, true);
        }

licc's avatar
licc committed
305
        //4计算每个用户本月的业绩增长率  如果集合大于20 ,取前二十名,小于,取全部
licc's avatar
licc committed
306 307 308
        List<TeamPerformanceSortVo> listVo = progressPrizeStatistics(userList);
        if (listVo.size() >= TWENTY) {
            listVo.subList(0, TWENTY);
licc's avatar
licc committed
309
        }
licc's avatar
licc committed
310

licc's avatar
licc committed
311 312 313 314 315
        //5、计算前20的总业绩
        double total = listVo.stream().mapToDouble(TeamPerformanceSortVo::getMonthPerformance).sum();
        boolean bool = totalPerformanceIncome(listVo, number, total);
        if (!bool) {
            return R.ok(1, false);
licc's avatar
licc committed
316 317
        }
        return R.ok(0, true);
licc's avatar
licc committed
318 319
    }

licc's avatar
licc committed
320
    @XxlJob(value = "mirrorImageMonthTask")
licc's avatar
licc committed
321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342
    @Override
    public void mirrorImage() {
        //1、把账户表account_info复制给表account_image  CREATE TABLE table_2  SELECT * FROM table_1;
        lastAccountMapper.copyTable("account_info", "account_image");

        //删除上月备份
        lastAccountMapper.deleteTable("account_backup");

        //备份
        lastAccountMapper.copyTable("account_info", "account_backup");

        //2、把上月账户表last_month_account 复制给month_account_image
        lastAccountMapper.copyTable("last_month_account", "month_account_image");

        //3、删除last_month_account
        lastAccountMapper.deleteTable("last_month_account");

        //4、把account_image 更名为 last_month_account  rename table table_2 to table_1;
        lastAccountMapper.updateTableName("account_image", "last_month_account");

        //5、删除month_account_image   DROP table table_2;
        lastAccountMapper.deleteTable("month_account_image");
licc's avatar
licc committed
343 344 345 346

        //6、把account_info的月度收益改为0,yearMoney 改为本月
        String yearMonth = DateUtil.convertDateToStr(new Date(), "yyyy-MM");
        accountMapper.updateMoneyAndEarningsMonth(yearMonth);
licc's avatar
licc committed
347 348
    }

licc's avatar
licc committed
349
    @XxlJob(value = "runCenterSubsidyMonthTask")
350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408
    @Override
    public R<Boolean> runCenterSubsidy() {
        log.info("shop-mall[]MonthTaskServiceImpl[]runCenterSubsidy[]input.method");
        //1、获取所有等级是西田森合伙人的用户
        List<User> list = usersMapper.getByLevel(UserLevelEnum.PARTNER.getCode());
        if (CollectionUtils.isEmpty(list)) {
            return R.ok(0, true);
        }

        //2、获取每个用户上月的团队业绩
        Date date = DateUtil.getLastMonth(new Date());
        String yearMonth = DateUtil.convertDateToStr(date, "yyyy-MM");

        //获取运营中心补贴比例
        MemberPercent memberPercent = memberPercentMapper.getByLevelAndType(UserLevelEnum.PARTNER.getCode(),
                MemberPercentEnum.RUN_CENTER_SUBSIDY.getCode());
        if (null == memberPercent) {
            return R.error("无运营中心补贴比例,请联系管理员添加!");
        }

        List<AccountInfo> accountInfoList = new ArrayList<>();
        List<TradeRecord> tradeRecordList = new ArrayList<>();
        for (User user : list) {
            //获取团队业绩
            TeamPerformance teamPerformance = teamPerformanceMapper.getByUserIdAndTime(user.getUserId(), yearMonth);
            if (null == teamPerformance) {
                continue;
            }

            //获取账户信息
            AccountInfo accountInfo = accountMapper.getByUserId(user.getUserId());
            if (null == accountInfo) {
                continue;
            }

            //计算运营中心补贴
            BigDecimal money = teamPerformance.getMonthTeamPerformance().multiply(memberPercent.getPercent());
            BigDecimal resultMoney = money.setScale(2, RoundingMode.HALF_UP);

            BigDecimal extractMoney = accountInfo.getExtractMoney().add(resultMoney);
            accountInfo.setExtractMoney(extractMoney);

            BigDecimal earningsMonth = accountInfo.getEarningsMonth().add(resultMoney);
            accountInfo.setExtractMoney(earningsMonth);

            BigDecimal earningsTotal = accountInfo.getEarningsTotal().add(resultMoney);
            accountInfo.setEarningsTotal(earningsTotal);
            accountInfoList.add(accountInfo);

            //添加交易流水记录
            TradeRecord tradeRecord = new TradeRecord();
            tradeRecord.setUserId(user.getUserId());
            tradeRecord.setTradeType(TradeRecordEnum.RUN_CENTER_SUBSIDY.getCode());
            tradeRecord.setTradeNo(null);
            tradeRecord.setStatus(TradeStatusEnum.ALREADY_SETTLE_ACCOUNTS.getCode());
            tradeRecordList.add(tradeRecord);
        }

        //修改账户信息和保存交易记录
licc's avatar
licc committed
409
        boolean bool = accountManager.runCenterUpdateAccountAddRecord(accountInfoList, tradeRecordList);
410 411 412 413 414 415
        if (!bool) {
            return R.ok(1, false);
        }
        return R.ok(0, true);
    }

licc's avatar
licc committed
416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509
    @XxlJob(value = "monthAwardCountTask")
    @Override
    public R<Boolean> monthAwardCount() {
        MonthAward result = new MonthAward();
        //1、获取本月新增奖金
        Double monthGrow = tradeRecordMapper.queryMonthGrow(new Date());
        result.setMonthIncreased(monthGrow);

        //2、获取历史奖金金额
        Double awardTotal = tradeRecordMapper.queryAllAward(new Date());
        result.setAwardTotal(awardTotal);

        //3、本月累计奖金 =本月新增奖金+上月剩余月度肥料奖金
        //获取上月剩余月度肥料奖金
        Double monthAwardTotal;
        Date date = DateUtil.getLastMonth(new Date());
        String yearMonth = DateUtil.convertDateToStr(date, "yyyy-MM");
        MonthManure monthManure = monthManureMapper.queryByTime(yearMonth);
        if (null == monthManure) {
            monthAwardTotal = monthGrow;
        } else {
            monthAwardTotal = monthGrow + monthManure.getManureAward();
        }
        result.setMonthAwardTotal(monthAwardTotal);

        //4、较上月增长奖金  本月累计奖金-上月累计奖金
        //本月
        String currentMonth = DateUtil.convertDateToStr(new Date(), "yyyy-MM");

        Date lastDate = DateUtil.getLastMonth(new Date());
        String lastMonth = DateUtil.convertDateToStr(lastDate, "yyyy-MM");
        Double growthAward;

        //获取上月 累计奖金
        MonthAward monthAward = monthAwardMapper.getByTime(lastMonth);
        if (null == monthAward) {
            growthAward = monthAwardTotal;
        } else {
            growthAward = monthAwardTotal - monthAward.getMonthAwardTotal();
        }
        result.setGrowthAward(growthAward);

        //5、获取黄金树本月奖金
        Double goldAward = tradeRecordMapper.queryByUserLevel(UserLevelEnum.GOLD_TREE.getCode(), new Date());
        if (null == goldAward) {
            result.setGoldAward(0.00);
        } else {
            result.setGoldAward(goldAward);
        }

        //6、获取农场主本月奖金
        Double farmerAward = tradeRecordMapper.queryByUserLevel(UserLevelEnum.FARMER.getCode(), new Date());
        if (null == farmerAward) {
            result.setFarmerAward(0.00);
        } else {
            result.setFarmerAward(farmerAward);
        }

        //7、森林之星月奖金
        Double startAward = tradeRecordMapper.queryByUserLevel(UserLevelEnum.FOREST_START.getCode(), new Date());
        if (null == startAward) {
            result.setForestStartAward(0.00);
        } else {
            result.setForestStartAward(startAward);
        }

        //8、森田合伙人月奖金
        Double partnerAward = tradeRecordMapper.queryByUserLevel(UserLevelEnum.PARTNER.getCode(), new Date());
        if (null == partnerAward) {
            result.setPartnerAward(0.00);
        } else {
            result.setPartnerAward(partnerAward);
        }

        //9、 判断是否有本月奖金这条数据,没有,新增,有更新值
        MonthAward currentMonthAward = monthAwardMapper.getByTime(currentMonth);
        if (null == currentMonthAward) {
            int count = monthAwardMapper.add(result);
            log.info(result.getYearMonth() + "插入一条月度奖励数据!");
            if (count == 0) {
                return R.ok(1, false);
            }
        } else {
            result.setId(currentMonthAward.getId());
            int count = monthAwardMapper.edit(result);
            log.info("更新" + result.getYearMonth() + "月度奖励数据!");
            if (count == 0) {
                return R.ok(1, false);
            }
        }

        return R.ok(0, true);
    }

licc's avatar
licc committed
510 511 512 513 514 515

    /**
     * 如果会员等级是黄金以上,计算月度收益
     *
     * @param totalMoney 月金额总额
     * @param userList   用户列表
licc's avatar
licc committed
516
     * @return true or false
licc's avatar
licc committed
517 518
     */
    private boolean monthlyIncome(BigDecimal totalMoney, List<User> userList) {
licc's avatar
licc committed
519 520
        //上月
        Date date = DateUtil.getLastMonth(new Date());
licc's avatar
licc committed
521
        String lastMonth = DateUtil.convertDateToStr(date, PATTERN);
licc's avatar
licc committed
522

licc's avatar
licc committed
523 524 525 526 527 528
        //上上月
        String time = DateUtil.convertDateToStr(date, "yyyy-MM-dd");
        Date timeString = DateUtil.convertStrToDate(time, "yyyy-MM-dd");
        Date lastAndLast = DateUtil.getLastMonth(timeString);
        String yearMonthTime = DateUtil.convertDateToStr(lastAndLast, PATTERN);

licc's avatar
licc committed
529
        //当月所有人订单成交总金额/3980/12  向下取整
licc's avatar
licc committed
530
        double total = totalMoney.doubleValue();
licc's avatar
licc committed
531 532
        double moneyMonth = Math.floor(total / 3980 / 12);

licc's avatar
licc committed
533
        //获取上上月未分配完的奖金
licc's avatar
licc committed
534 535 536 537 538 539 540 541
        double lastMonthAward;
        MonthManure monthManure = monthManureMapper.queryByTime(yearMonthTime);
        if (null == monthManure) {
            lastMonthAward = 0.00;
        } else {
            lastMonthAward = monthManure.getManureAward();
        }

licc's avatar
licc committed
542
        //1、判断每个等级是否都有用户,没有用户的,记录下剩余奖金
licc's avatar
licc committed
543
        MonthManure manure = checkUserLevel(moneyMonth, lastMonthAward);
licc's avatar
licc committed
544 545
        //获取上月是否有月度剩余奖金信息
        MonthManure lastMonthManure = monthManureMapper.queryByTime(lastMonth);
licc's avatar
licc committed
546

licc's avatar
licc committed
547 548
        List<AccountInfo> accountInfoList = new ArrayList<>();
        List<TradeRecord> tradeRecordList = new ArrayList<>();
licc's avatar
licc committed
549 550 551 552
        if (moneyMonth == 0) {
            return true;
        }

licc's avatar
licc committed
553 554 555 556 557 558
        for (User user : userList) {
            if (moneyMonth != 0) {
                //获取等级优惠百分比
                MemberPercent memberPercent = memberPercentMapper.getByLevelAndType(user.getUserLevel(),
                        MemberPercentEnum.MONTH_MANURE.getCode());
                if (null != memberPercent) {
licc's avatar
licc committed
559 560
                    //获取上月月团队总金额
                    TeamPerformance teamPerformance = teamPerformanceMapper.getByUserIdAndTime(user.getUserId(), lastMonth);
licc's avatar
licc committed
561

licc's avatar
licc committed
562 563
                    //获取上月该等级团队总金额
                    Double teamTotal = teamPerformanceMapper.countTeamMoney(user.getUserLevel(), lastMonth);
licc's avatar
licc committed
564
                    if (null != teamPerformance && null != teamTotal && teamTotal != 0) {
licc's avatar
licc committed
565 566 567
                        double month = teamPerformance.getMonthTeamPerformance().doubleValue();
                        double percent = memberPercent.getPercent().doubleValue();
                        //计算收益
licc's avatar
licc committed
568
                        double income = ((moneyMonth * 3980) + lastMonthAward) * percent * month / teamTotal;
licc's avatar
licc committed
569 570 571
                        if (income == 0) {
                            continue;
                        }
licc's avatar
licc committed
572 573
                        //获取账户信息
                        AccountInfo accountInfo = accountMapper.getByUserId(user.getUserId());
574
                        BigDecimal bigDecimal = new BigDecimal(income).setScale(2, RoundingMode.HALF_UP);
licc's avatar
licc committed
575

licc's avatar
licc committed
576 577 578 579 580 581 582 583 584 585 586 587 588 589 590
                        //获取用户上月月收益=可提现金额+ 上月肥料收益
                        BigDecimal performanceMonth = accountInfo.getExtractMoney().add(bigDecimal);
                        accountInfo.setEarningsMonth(performanceMonth);

                        //获取用户上上月总收益
                        LastMonthAccount lastMonthAccount = lastAccountMapper.getByUserIdAndTime(user.getUserId(), yearMonthTime);
                        BigDecimal lastTotalMonth;
                        if (null == lastMonthAccount || null == lastMonthAccount.getEarningsTotal()) {
                            lastTotalMonth = new BigDecimal("0.00");
                        } else {
                            lastTotalMonth = lastMonthAccount.getEarningsTotal();
                        }

                        //用户总收益=上上月总收益+上月收益
                        BigDecimal performanceTotal = lastTotalMonth.add(performanceMonth);
licc's avatar
licc committed
591
                        accountInfo.setEarningsTotal(performanceTotal.setScale(2, RoundingMode.HALF_UP));
licc's avatar
licc committed
592 593 594 595 596 597 598 599
                        accountInfoList.add(accountInfo);


                        //5、添加交易流水记录
                        TradeRecord tradeRecord = new TradeRecord();
                        tradeRecord.setUserId(user.getUserId());
                        tradeRecord.setTradeType(TradeRecordEnum.MONTHLY_FERTILIZER.getCode());
                        tradeRecord.setTradeNo(null);
licc's avatar
licc committed
600 601
                        BigDecimal big = new BigDecimal(income);
                        tradeRecord.setMoney(big.setScale(2, RoundingMode.HALF_UP));
licc's avatar
licc committed
602 603 604 605 606 607 608
                        tradeRecord.setStatus(TradeStatusEnum.ALREADY_SETTLE_ACCOUNTS.getCode());
                        tradeRecordList.add(tradeRecord);
                    }
                }
            }
        }
        //更新账户信息,新增交易流水记录
licc's avatar
licc committed
609
        return accountManager.updateAccountAddRecordAndManure(accountInfoList, tradeRecordList, manure, lastMonthManure);
licc's avatar
licc committed
610 611 612 613 614 615 616 617
    }

    /**
     * 计算上月未分配完的月度肥料奖金
     *
     * @param moneyMonth 奖金总额
     * @return 月度肥料奖金
     */
licc's avatar
licc committed
618
    private MonthManure checkUserLevel(double moneyMonth, double lastMonthAward) {
licc's avatar
licc committed
619 620 621 622 623 624 625 626 627 628 629 630 631
        MonthManure monthManure = new MonthManure();
        double total = 0.00;
        //1、判断是否有黄金等级的用户
        List<User> goldList = usersMapper.getByLevel(UserLevelEnum.GOLD_TREE.getCode());
        if (CollectionUtils.isEmpty(goldList)) {
            //获取等级优惠百分比
            MemberPercent memberPercent = memberPercentMapper.getByLevelAndType(UserLevelEnum.GOLD_TREE.getCode(),
                    MemberPercentEnum.MONTH_MANURE.getCode());
            double percent = memberPercent.getPercent().doubleValue();

            //计算该等级剩余奖金
            double goldAward;
            if (moneyMonth != 0) {
licc's avatar
licc committed
632
                goldAward = ((moneyMonth * 3980) + lastMonthAward) * percent;
licc's avatar
licc committed
633 634 635 636 637 638 639 640 641 642 643 644 645 646 647
                total = total + goldAward;
            }
        }

        //2、判断是否有农场主等级的用户
        List<User> farmerList = usersMapper.getByLevel(UserLevelEnum.FARMER.getCode());
        if (CollectionUtils.isEmpty(farmerList)) {
            //获取等级优惠百分比
            MemberPercent memberPercent = memberPercentMapper.getByLevelAndType(UserLevelEnum.FARMER.getCode(),
                    MemberPercentEnum.MONTH_MANURE.getCode());
            double percent = memberPercent.getPercent().doubleValue();

            //计算该等级剩余奖金
            double goldAward;
            if (moneyMonth != 0) {
licc's avatar
licc committed
648
                goldAward = ((moneyMonth * 3980) + lastMonthAward) * percent;
licc's avatar
licc committed
649 650 651 652 653 654
                total = total + goldAward;
            }
        }

        //3、判断是否有森林之星等级的用户
        List<User> startList = usersMapper.getByLevel(UserLevelEnum.FOREST_START.getCode());
licc's avatar
licc committed
655
        if (!CollectionUtils.isEmpty(startList)) {
licc's avatar
licc committed
656 657 658 659 660 661 662 663
            //获取等级优惠百分比
            MemberPercent memberPercent = memberPercentMapper.getByLevelAndType(UserLevelEnum.FOREST_START.getCode(),
                    MemberPercentEnum.MONTH_MANURE.getCode());
            double percent = memberPercent.getPercent().doubleValue();

            //计算该等级剩余奖金
            double goldAward;
            if (moneyMonth != 0) {
licc's avatar
licc committed
664
                goldAward = ((moneyMonth * 3980) + lastMonthAward) * percent;
licc's avatar
licc committed
665 666 667 668 669 670 671 672 673 674 675 676 677 678 679
                total = total + goldAward;
            }
        }

        //4、判断是否有西田森等级的用户
        List<User> partnerList = usersMapper.getByLevel(UserLevelEnum.PARTNER.getCode());
        if (CollectionUtils.isEmpty(partnerList)) {
            //获取等级优惠百分比
            MemberPercent memberPercent = memberPercentMapper.getByLevelAndType(UserLevelEnum.FOREST_START.getCode(),
                    MemberPercentEnum.MONTH_MANURE.getCode());
            double percent = memberPercent.getPercent().doubleValue();

            //计算该等级剩余奖金
            double goldAward;
            if (moneyMonth != 0) {
licc's avatar
licc committed
680
                goldAward = ((moneyMonth * 3980) + lastMonthAward) * percent;
licc's avatar
licc committed
681 682 683 684 685 686 687 688 689 690 691
                total = total + goldAward;
            }
        }

        //获取当前时间上一月
        Date date = DateUtil.getLastMonth(new Date());
        String yearMonth = DateUtil.convertDateToStr(date, PATTERN);
        monthManure.setYearMonth(yearMonth);
        monthManure.setManureAward(total);
        return monthManure;
    }
licc's avatar
licc committed
692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754

    /**
     * 统计每个用户本月业绩增长率
     *
     * @param userList 用户列表
     * @return 每个用户本月业绩增长率
     */
    private List<TeamPerformanceSortVo> progressPrizeStatistics(List<User> userList) {
        Date date = new Date();
        String yearMonth = DateUtil.convertDateToStr(date, PATTERN);

        //遍历 计算业绩增长率
        List<TeamPerformanceSortVo> listVo = new ArrayList<>();
        for (User user : userList) {
            TeamPerformanceSortVo teamVo = new TeamPerformanceSortVo();
            double growthRate;
            //获取当月业绩
            TeamPerformance teamPerformance = teamPerformanceMapper.getByUserIdAndTime(user.getUserId(), yearMonth);

            //获取上月业绩
            Calendar cal = Calendar.getInstance();
            cal.setTime(new Date());
            cal.add(Calendar.MONTH, -1);
            Date lastDate = cal.getTime();
            String lastMonthTime = DateUtil.convertDateToStr(lastDate, PATTERN);
            TeamPerformance lastMonth = teamPerformanceMapper.getByUserIdAndTime(user.getUserId(), lastMonthTime);
            if (null == teamPerformance || null == lastMonth) {
                growthRate = 0.00;
            } else {
                double month = teamPerformance.getMonthTeamPerformance().doubleValue();
                double last = lastMonth.getMonthTeamPerformance().doubleValue();
                if (last >= month) {
                    growthRate = 0.00;
                } else {
                    growthRate = (month - last) / month;
                }
            }
            teamVo.setGrowthRate(growthRate);
            double monthPerformance;
            assert teamPerformance != null;
            if (null == teamPerformance.getMonthTeamPerformance()) {
                monthPerformance = 0.00;
            } else {
                monthPerformance = teamPerformance.getMonthTeamPerformance().doubleValue();
            }
            teamVo.setMonthPerformance(monthPerformance);
            teamVo.setUserId(user.getUserId());
            teamVo.setTeamPerformance(teamPerformance);
            listVo.add(teamVo);
        }

        //对集合进行排序
        listVo.sort(Comparator.comparing(TeamPerformanceSortVo::getGrowthRate).reversed());
        return listVo;
    }

    /**
     * 统计用户最大进步奖收益
     *
     * @param listVo 用户增长率列表
     * @param number 个人业绩
     * @param total  总业绩
     */
licc's avatar
licc committed
755
    private boolean totalPerformanceIncome(List<TeamPerformanceSortVo> listVo, double number, double total) {
licc's avatar
licc committed
756 757
        //要更新的账户列表
        List<AccountInfo> updateAccountList = new ArrayList<>();
licc's avatar
licc committed
758 759 760 761
        Date lastMonth = DateUtil.getLastMonth(new Date());
        String yearMonth = DateUtil.convertDateToStr(lastMonth, PATTERN);
        List<ProgressPrize> addList = new ArrayList<>();
        List<ProgressPrize> updateList = new ArrayList<>();
licc's avatar
licc committed
762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799
        if (number > 0) {
            for (TeamPerformanceSortVo teamPerformanceSortVo : listVo) {
                String userId = teamPerformanceSortVo.getTeamPerformance().getUserId();
                Integer userLevel = teamPerformanceSortVo.getTeamPerformance().getUserLevel();
                //获取最大进步奖 百分比
                MemberPercent memberPercent = memberPercentMapper.getByLevelAndType(userLevel, 3);

                //计算收益
                double userTeamPerformance = teamPerformanceSortVo.getTeamPerformance().getMonthTeamPerformance().doubleValue();
                double percent = memberPercent.getPercent().doubleValue();
                double income = number * 3980 * percent * userTeamPerformance / total;

                //获取账户信息
                AccountInfo accountInfo = accountMapper.getByUserId(userId);
                //用户月收益  =其他收益+最大进步奖收益
                BigDecimal earningsMonth = accountInfo.getEarningsMonth().add(BigDecimal.valueOf(income));
                accountInfo.setEarningsMonth(earningsMonth);

                //用户总收益 =其他总收益 + 最大进步奖收益
                BigDecimal earningsTotal = accountInfo.getEarningsTotal().add(BigDecimal.valueOf(income));
                accountInfo.setEarningsTotal(earningsTotal);
                updateAccountList.add(accountInfo);

                //最大进步奖信息
                ProgressPrize progressPrize = progressPrizeMapper.getByUserIdYearMonth(userId, yearMonth);
                if (null == progressPrize) {
                    //新增
                    ProgressPrize addPrize = new ProgressPrize();
                    addPrize.setAwardMoney(income);
                    addPrize.setYearMonth(yearMonth);
                    addPrize.setGrowthRate(0.0);
                    addPrize.setUserId(userId);
                    addList.add(addPrize);
                } else {
                    progressPrize.setGrowthRate(teamPerformanceSortVo.getGrowthRate());
                    progressPrize.setAwardMoney(income);
                    updateList.add(progressPrize);
                }
licc's avatar
licc committed
800 801
            }

licc's avatar
licc committed
802 803
            //获取本月存在的最大进步奖列表
            List<ProgressPrize> prizes = progressPrizeMapper.getByYearMonth(yearMonth);
licc's avatar
licc committed
804

licc's avatar
licc committed
805 806 807 808 809 810
            //修改或保存最大进步奖信息
            //  flag  1: 日定时任务  2:月定时任务
            int flag = 2;
            return accountManager.updateOrSavePrize(updateAccountList, prizes, addList, updateList, flag);
        }
        return true;
licc's avatar
licc committed
811
    }
licc's avatar
licc committed
812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830

    private void addTeamPerformance(List<User> userList) {
        Date lastMonth = DateUtil.getLastMonth(new Date());
        String yearMonth = DateUtil.convertDateToStr(lastMonth, "yyyy-MM");
        if (!CollectionUtils.isEmpty(userList)) {
            for (User user : userList) {
                //获取团队业绩信息
                TeamPerformance teamPerformance = teamPerformanceMapper.getByUserIdAndTime(user.getUserId(), yearMonth);
                if (null == teamPerformance) {
                    TeamPerformance addTeam = new TeamPerformance();
                    addTeam.setMonthTeamPerformance(new BigDecimal(0));
                    addTeam.setYearMonth(yearMonth);
                    addTeam.setUserLevel(user.getUserLevel());
                    addTeam.setUserId(user.getUserId());
                    teamPerformanceMapper.add(addTeam);
                }
            }
        }
    }
licc's avatar
licc committed
831
}