package cn.newfeifan.mall.module.distri.service.partitioncrash;

import cn.newfeifan.mall.framework.common.util.json.JsonUtils;
import cn.newfeifan.mall.framework.mybatis.core.query.LambdaQueryWrapperX;
import cn.newfeifan.mall.module.distri.controller.admin.integral.vo.IntegralSaveReqVO;
import cn.newfeifan.mall.module.distri.controller.admin.partitionbrothers.vo.PartitionBrothersSaveReqVO;
import cn.newfeifan.mall.module.distri.controller.admin.partitionson.vo.PartitionSonSaveReqVO;
import cn.newfeifan.mall.module.distri.controller.admin.ptprofit.vo.PtProfitSaveReqVO;
import cn.newfeifan.mall.module.distri.dal.dataobject.duser.DuserDO;
import cn.newfeifan.mall.module.distri.dal.dataobject.integral.IntegralDO;
import cn.newfeifan.mall.module.distri.dal.dataobject.ordercalc.OrderCalcDO;
import cn.newfeifan.mall.module.distri.dal.dataobject.orderpercentage.OrderPercentageDO;
import cn.newfeifan.mall.module.distri.dal.dataobject.ptprofit.PtProfitDO;
import cn.newfeifan.mall.module.distri.dal.dataobject.ptprofitdailystatisticslog.PtProfitDailyStatisticsLogDO;
import cn.newfeifan.mall.module.distri.dal.mysql.ptprofit.PtProfitMapper;
import cn.newfeifan.mall.module.distri.dal.mysql.ptprofitdailystatisticslog.PtProfitDailyStatisticsLogMapper;
import cn.newfeifan.mall.module.distri.enums.CaclEnum;
import cn.newfeifan.mall.module.distri.service.dailyawardrecords.DailyAwardRecordsService;
import cn.newfeifan.mall.module.distri.service.duser.DuserService;
import cn.newfeifan.mall.module.distri.service.integral.IntegralService;
import cn.newfeifan.mall.module.distri.service.orderpercentage.OrderPercentageService;
import cn.newfeifan.mall.module.distri.service.partitionbrothers.PartitionBrothersService;
import cn.newfeifan.mall.module.distri.service.partitionson.PartitionSonService;
import cn.newfeifan.mall.module.distri.service.ptprofit.PtProfitService;
import cn.newfeifan.mall.module.distri.service.ptprofitlog.PtProfitLogService;
import cn.newfeifan.mall.module.member.dal.dataobject.user.MemberUserDO;
import cn.newfeifan.mall.module.member.service.user.MemberUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import cn.newfeifan.mall.module.distri.service.sharepath.SharePathService;

import javax.annotation.Resource;

import org.springframework.validation.annotation.Validated;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.*;
import java.util.stream.Collectors;

import cn.newfeifan.mall.module.distri.controller.admin.partitioncrash.vo.*;
import cn.newfeifan.mall.module.distri.dal.dataobject.partitioncrash.PartitionCrashDO;
import cn.newfeifan.mall.framework.common.pojo.PageResult;
import cn.newfeifan.mall.framework.common.util.object.BeanUtils;

import cn.newfeifan.mall.module.distri.dal.mysql.partitioncrash.PartitionCrashMapper;

import static cn.newfeifan.mall.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.newfeifan.mall.module.distri.constant.DistriConstants.PT_ID;
import static cn.newfeifan.mall.module.distri.enums.ErrorCodeConstants.*;

/**
 * 分区碰撞 Service 实现类
 *
 * @author 非繁人
 */
@Service
@Validated
@Slf4j
public class PartitionCrashServiceImpl implements PartitionCrashService {

    @Resource
    private PartitionCrashMapper partitionCrashMapper;

    @Resource
    @Lazy
    private SharePathService sharePathService;

    @Resource
    private PartitionSonService partitionSonService;

    @Resource
    private PartitionBrothersService partitionBrothersService;

    @Resource
    @Lazy
    private DuserService duserService;

    @Resource
    private PtProfitLogService ptProfitLogService;

    @Resource
    @Lazy
    private IntegralService integralService;

    @Resource
    private OrderPercentageService orderPercentageService;

    @Resource
    private PtProfitService ptProfitService;

    @Resource
    private PtProfitDailyStatisticsLogMapper ptProfitDailyStatisticsLogMapper;

    @Resource
    private PtProfitMapper ptProfitMapper;

    @Resource
    private DailyAwardRecordsService dailyAwardRecordsService;
    @Resource
    private MemberUserService memberUserService;


    @Override
    public Long createPartitionCrash(PartitionCrashSaveReqVO createReqVO) {
        // 插入
        PartitionCrashDO partitionCrash = BeanUtils.toBean(createReqVO, PartitionCrashDO.class);
        partitionCrashMapper.insert(partitionCrash);
        // 返回
        return partitionCrash.getId();
    }

    @Override
    public void updatePartitionCrash(PartitionCrashSaveReqVO updateReqVO) {
        // 校验存在
        validatePartitionCrashExists(updateReqVO.getId());
        // 更新
        PartitionCrashDO updateObj = BeanUtils.toBean(updateReqVO, PartitionCrashDO.class);
        partitionCrashMapper.updateById(updateObj);
    }

    @Override
    public void deletePartitionCrash(Long id) {
        // 校验存在
        validatePartitionCrashExists(id);
        // 删除
        partitionCrashMapper.deleteById(id);
    }

    private void validatePartitionCrashExists(Long id) {
        if (partitionCrashMapper.selectById(id) == null) {
            throw exception(PARTITION_CRASH_NOT_EXISTS);
        }
    }

    @Override
    public PartitionCrashDO getPartitionCrash(Long id) {
        return partitionCrashMapper.selectById(id);
    }

    @Override
    public PageResult<PartitionCrashDO> getPartitionCrashPage(PartitionCrashPageReqVO pageReqVO) {
        return partitionCrashMapper.selectPage(pageReqVO);
    }

    @Override
    public void calcCrash(List<Long> userId) {

        Map<Long, Long> userHighQuotaMap = new HashMap<>();

        // 获取所有的营销用户
        List<DuserDO> duserDOS = duserService.selectAllUser();
        if (duserDOS.isEmpty()) {
            return;
        }
        //记录所有用户的id和积分
        List<HashMap<Long, Long>> afterCrashMap = new ArrayList<>();
        // 获取当前合赢奖百分比
        OrderPercentageDO orderPercentageDO = orderPercentageService.queryStatus();

        // 获取当前所有用户的父亲
        Map<Long, Long> sonAndParent = new HashMap<>();
        List<Long> userIds = duserDOS.stream().map(DuserDO::getUserId).collect(Collectors.toList());

        userIds.forEach(k -> {
            Long parent = sharePathService.queryParentBySonUserId(k);
            sonAndParent.put(k, parent);
        });

        List<PartitionSonSaveReqVO> partitionSonSaveReqVOS = new ArrayList<>();
        List<PartitionBrothersSaveReqVO> partitionBrothersSaveReqVOS = new ArrayList<>();
        List<PartitionCrashSaveReqVO> partitionCrashSaveReqVOS = new ArrayList<>();

        // 本来在下面,搬上来,因为游客收益要扣减
        IntegralDO ptIntegralDO = integralService.selectByUser(PT_ID);

        duserDOS.forEach(k -> {

            // 获取当前用户的钱包
            IntegralDO integralDO = integralService.selectByUser(k.getUserId());
            // 获取当前用户信息
            MemberUserDO user = memberUserService.getUser(k.getUserId());

            // 获取当前父亲的钱包
            Long parent = sonAndParent.get(k.getUserId());
            IntegralDO parentIntegralDo = integralService.selectByUser(parent);
            if (parentIntegralDo != null) {

                // 创建一个分区编号
                String todayNo = crashTodayNo(k.getUserId());

                PartitionSonSaveReqVO.PartitionSonSaveReqVOBuilder sonBuilder = PartitionSonSaveReqVO.builder();
                PartitionBrothersSaveReqVO.PartitionBrothersSaveReqVOBuilder brotherBuilder = PartitionBrothersSaveReqVO.builder();
                PartitionCrashSaveReqVO.PartitionCrashSaveReqVOBuilder crashSaveReqVOBuilder = PartitionCrashSaveReqVO.builder();
                sonBuilder.partNo(todayNo);
                sonBuilder.userId(k.getUserId());
                sonBuilder.name(k.getName());
                sonBuilder.nickName(k.getNickName());
                sonBuilder.hasHit(1);

                brotherBuilder.partNo(todayNo);
                brotherBuilder.userId(k.getUserId());
                brotherBuilder.name(k.getName());
                brotherBuilder.nickName(k.getNickName());
                brotherBuilder.hasHit(1);


                crashSaveReqVOBuilder.partNo(todayNo);
                crashSaveReqVOBuilder.userId(k.getUserId());
                crashSaveReqVOBuilder.nickName(k.getNickName());
                crashSaveReqVOBuilder.userName(k.getName());

                // 获取当前用户的后代分区 , 并且该分区存在有下单的用户
                List<OrderCalcDO> sonOrderCalcDOS = sharePathService.selectSons(k.getUserId(), userId);
                if (sonOrderCalcDOS.isEmpty()) {
                    // 插入空数据
                    sonBuilder = addSonEmpty(sonBuilder, k);
                    crashSaveReqVOBuilder.sonPrice(0L);
                }
                // 合计儿子分支额度
                double grossProfitBonusQuotaPerc = Double.parseDouble(orderPercentageDO.getGrossProfitBonusQuotaPerc());
                Long sonSumPrice = (long) (sonOrderCalcDOS.stream().mapToLong(OrderCalcDO::getGrossProfit).sum() * grossProfitBonusQuotaPerc);
                sonBuilder.price(sonSumPrice);

                // 获取当前用户的兄弟分区
                List<OrderCalcDO> brothersOrderCalcDOS = sharePathService.selectBrothers(k.getUserId(), userId, user);
                if (brothersOrderCalcDOS.isEmpty()) {
                    // 插入空数据
                    brotherBuilder = addBrotherEmpty(brotherBuilder, k);
                    crashSaveReqVOBuilder.brotherPrice(0L);
                }

                // 合并兄弟分支额度
                Long brotherSumPrice = (long) (brothersOrderCalcDOS.stream().mapToLong(OrderCalcDO::getGrossProfit).sum() * grossProfitBonusQuotaPerc);
                brotherBuilder.price(brotherSumPrice);


                // 判断，昨天是否有存余的分支
                PartitionCrashDO yesterdayCrash = crashYesterdayNo(k.getUserId(),1);
                // 如果不为空， 则判断增加到哪个分支中
                if (yesterdayCrash != null) {
                    if (yesterdayCrash.getSonPrice() >= yesterdayCrash.getBrotherPrice()) {
                        sonSumPrice = sonSumPrice + yesterdayCrash.getSonPrice();
                    } else {
                        brotherSumPrice = brotherSumPrice + yesterdayCrash.getBrotherPrice();
                    }
                }

                Long afterCrash = 0L;
                Long smallQuota = 0L;
                // 碰撞计算
                if (sonSumPrice >= brotherSumPrice) {
                    sonBuilder.size(1);
                    brotherBuilder.size(0);
                    afterCrash = sonSumPrice - brotherSumPrice;
                    smallQuota = brotherSumPrice;

                } else {
                    sonBuilder.size(0);
                    brotherBuilder.size(1);
                    afterCrash = brotherSumPrice - sonSumPrice;
                    smallQuota = sonSumPrice;
                }


                crashSaveReqVOBuilder.brotherPrice(brotherSumPrice);
                crashSaveReqVOBuilder.sonPrice(sonSumPrice);
                crashSaveReqVOBuilder.afterHitQuota(afterCrash);

                // 积分添加 添加的时候， 需要注意当前用户是否有足够的积分可以获取
                // 碰撞后的额度的
                Long highQuota = integralDO.getHighQuota() + new BigDecimal(orderPercentageDO.getBaseMaxQuota()).longValue();       //加上基础的最大额度值
                Long parentHighQuota = parentIntegralDo.getHighQuota() + new BigDecimal(orderPercentageDO.getBaseMaxQuota()).longValue();

                BigDecimal smallBigDecimal = new BigDecimal(String.valueOf(smallQuota));
                BigDecimal multiply = smallBigDecimal.divide(new BigDecimal("2.0"), 4, RoundingMode.DOWN);
                //直推人的本次添加积分
                Long amount = 0L;
                //平台需要补回的收益(也可以理解为用户溢出)
                Long ptReplenish = multiply.longValue();

                //直推人
                if (multiply.longValue() != 0) {
                    if (highQuota.compareTo(0L) > 0) {

                        if (highQuota.compareTo(multiply.longValue()) > 0) {
                            amount = multiply.longValue();
                            ptReplenish = 0L;
                        } else {
                            amount = highQuota;
                            ptReplenish = multiply.longValue() - highQuota;
                        }
                        addHighQuota(userHighQuotaMap, integralDO.getUserId(), amount);
                    }
                    integralDO.setFreezeQuota(integralDO.getFreezeQuota() + amount);
                    integralDO.setHighQuota(integralDO.getHighQuota() - amount);


                    integralDO.setAccumulatedQuota(integralDO.getAccumulatedQuota() + amount);
                    // 碰撞后的额度添加到日志中 增加日志模块
                    integralService.updateIntegral(BeanUtils.toBean(integralDO, IntegralSaveReqVO.class));
                    Long logId = ptProfitLogService.addMessageFreeze(integralDO.getUserId(), integralDO.getUserId(), CaclEnum.SMALL_QUOTA_CRASH, amount,
                            integralDO.getFreezeQuota(), JsonUtils.toJsonString(orderPercentageDO), ptReplenish, -amount, highQuota - amount);

                    //记录每日用户有合赢将的记录，后面用来结算的
                    dailyAwardRecordsService.addDailyAwardRecords(integralDO.getUserId(), integralDO.getUserId(), amount, logId, ptReplenish);
                }
                if (!ptReplenish.equals(0L)) {
                    calcIntegral(ptReplenish, integralDO.getUserId(), JsonUtils.toJsonString(orderPercentageDO));
                }

                // 获取计算后积分, Long为userId, Integer为碰撞后额度
                HashMap<Long, Long> map = new HashMap<>();

                // 当用户为游客的时候上级不参与合赢奖
                if (!user.getVisitor()) {
                    //直推人的上级的本次添加积分
                    Long parentAmount = 0L;
                    //平台需要补回的收益(也可以理解为用户溢出)
                    Long parentPtReplenish = multiply.longValue();
                    //直推人的父级
                    if (multiply.longValue() != 0) {
                        if (parentHighQuota.compareTo(0L) > 0) {
                            if (parentHighQuota.compareTo(multiply.longValue()) > 0) {
                                parentAmount = multiply.longValue();
                                parentPtReplenish = 0L;
                            } else {
                                parentAmount = highQuota;
                                parentPtReplenish = multiply.longValue() - highQuota;
                            }
                            addHighQuota(userHighQuotaMap, parentIntegralDo.getUserId(), parentAmount);
                        }
                        // 减去最高额度
                        parentIntegralDo.setHighQuota(parentIntegralDo.getHighQuota() - parentAmount);
                        parentIntegralDo.setFreezeQuota(parentIntegralDo.getFreezeQuota() + parentAmount);

                        parentIntegralDo.setAccumulatedQuota(parentIntegralDo.getAccumulatedQuota() + parentAmount);
                        // 碰撞后的额度添加到日志中 增加日志模块
                        integralService.updateIntegral(BeanUtils.toBean(parentIntegralDo, IntegralSaveReqVO.class));
                        Long logId = ptProfitLogService.addMessageFreeze(parentIntegralDo.getUserId(), integralDO.getUserId(), CaclEnum.SMALL_QUOTA_CRASH, parentAmount,
                                parentIntegralDo.getFreezeQuota(), JsonUtils.toJsonString(orderPercentageDO), parentPtReplenish, -parentAmount, parentHighQuota - parentAmount);

                        //记录每日用户有合赢将的记录，后面用来结算的
                        dailyAwardRecordsService.addDailyAwardRecords(parentIntegralDo.getUserId(), integralDO.getUserId(), parentAmount, logId, parentPtReplenish);
                    }

                    if (!parentPtReplenish.equals(0L)) {
                        calcIntegral(parentPtReplenish, parentIntegralDo.getUserId(), JsonUtils.toJsonString(orderPercentageDO));
                    }

                    if (!parentIntegralDo.getUserId().equals(PT_ID)) {
                        map.put(parentIntegralDo.getUserId(), parentAmount);
                    }
                } else if (multiply.longValue() != 0) {
                    // 如果当前用户是游客,将上级推荐将加入到游客收益中,不算入到翁总的合赢奖
                    Long visitorEarnings = multiply.longValue();        //单笔收益

                    // 获取平台的游客收益
                    PtProfitDO ptProfit = ptProfitService.getPtProfit();
                    ptProfit.setVisitorEarnings(ptProfit.getVisitorEarnings() + visitorEarnings);
                    ptProfit.setPtGrossAdd(ptProfit.getPtGrossAdd() - visitorEarnings);
                    ptProfitService.updatePtProfit(BeanUtils.toBean(ptProfit, PtProfitSaveReqVO.class));
                    ptIntegralDO.setCurrentQuota(ptIntegralDO.getCurrentQuota() - visitorEarnings);

                    ptProfitLogService.addMessage(parent, CaclEnum.AFTER_CRASH_CALC_PT_TOTAL_QUOTA
                            , -visitorEarnings, ptProfit.getPtTotalAdd() - visitorEarnings, JsonUtils.toJsonString(orderPercentageDO), null, null, null);
                    ptProfitLogService.addMessage(parent, CaclEnum.AFTER_CRASH_CALC_PT_TOTAL_GROSS_QUOTA
                            , -visitorEarnings, ptProfit.getPtGrossAdd(), JsonUtils.toJsonString(orderPercentageDO), null, null, null);

                    // 记录平台游客收益log
                    ptProfitLogService.addMessage(k.getUserId(), null ,CaclEnum.SMALL_QUOTA_CRASH_SETTLE, visitorEarnings, ptProfit.getVisitorEarnings()
                    , null, null, JsonUtils.toJsonString(orderPercentageDO),null, null);
                }

                // 如果为当前用户为平台,则不需要存入这个地方
                if (!k.getUserId().equals(PT_ID)) {
                    map.put(k.getUserId(), amount);
                }

                afterCrashMap.add(map);

                log.info(k.getNickName() + "用户合赢奖已经计算: 该用户合赢奖为: \t" +
                        "兄弟分区为: " + brotherBuilder.build() + "\t" +
                        "后代分区为: " + sonBuilder.build() + "\t" +
                        "碰撞分区为: " + crashSaveReqVOBuilder.build() + "\t");

                partitionSonSaveReqVOS.add(sonBuilder.build());
                partitionBrothersSaveReqVOS.add(brotherBuilder.build());
                partitionCrashSaveReqVOS.add(crashSaveReqVOBuilder.build());


            }
        });

        partitionSonService.saveBatch(partitionSonSaveReqVOS);
        partitionBrothersService.saveBatch(partitionBrothersSaveReqVOS);
        saveBatch(partitionCrashSaveReqVOS);

        // 计算平台积分
        // 获取当前平台的额度
        PtProfitDO ptProfit = ptProfitService.getPtProfit();

        // 遍历hashMap
        for (HashMap<Long, Long> longIntegerHashMap : afterCrashMap) {
            for (Map.Entry<Long, Long> entry : longIntegerHashMap.entrySet()) {
                //暂时不设限制扣减
//                if (ptProfit.getPtGrossAdd() <= 0) {
//                    break;
//                }

                if (entry.getValue() == 0) {
                    continue;
                }

                // 获取当前用户的钱包
                IntegralDO integralDO = integralService.selectByUser(entry.getKey());
                // 获取当前父亲的钱包
                Long highQuota = integralDO.getHighQuota() + new BigDecimal(orderPercentageDO.getBaseMaxQuota()).longValue();       //加上基础的最大额度值

                for (Long key : userHighQuotaMap.keySet()) {
                    if (key.equals(entry.getKey())) {
                        if (userHighQuotaMap.get(key) > 0L) {
                            highQuota = highQuota + entry.getValue();
                            userHighQuotaMap.put(key, userHighQuotaMap.get(key) - entry.getValue());
                            break;
                        }
                    }
                }


                //amount用于记录本次添加的值
                Long amount = 0L;
                //平台需要补回的收益
//                Long ptReplenish = entry.getValue();

                //如果直推人的可获取额度大于0,则能够获取
                if (highQuota.compareTo(0L) > 0) {
                    if (highQuota.compareTo(entry.getValue()) > 0) {
                        //如果最大额度 > 直推人可获取额度,则直接获取
                        amount = entry.getValue();
                        //平台没有需要补回的收益
//                        ptReplenish = 0L;
                    } else {
                        //如果最大额度 < 直推人可获取额度,则获取自己的最大额度
                        amount = highQuota;
                        //用户本次没有拿到的直推奖
//                        ptReplenish = entry.getValue() - highQuota;
                    }

                    integralService.updateIntegral(BeanUtils.toBean(integralDO, IntegralSaveReqVO.class));


                    // 扣除平台收益
                    log.info("扣除平台收益[合赢奖] " + "用户: " + entry.getKey() + "额度: " + amount);
                    ptProfit.setPtGrossAdd(ptProfit.getPtGrossAdd() - amount);
                    ptIntegralDO.setCurrentQuota(ptIntegralDO.getCurrentQuota() - amount);
                    // 平台扣除积分
                    ptProfit.setPtTotalAdd(ptProfit.getPtTotalAdd() - amount);
                    // 碰撞后的额度添加到日志中 增加日志模块
                    ptProfitLogService.addMessage(entry.getKey(), CaclEnum.AFTER_CRASH_CALC_PT_TOTAL_QUOTA
                            , -entry.getValue(), ptProfit.getPtTotalAdd(), JsonUtils.toJsonString(orderPercentageDO), null, null, null);
                    ptProfitLogService.addMessage(entry.getKey(), CaclEnum.AFTER_CRASH_CALC_PT_TOTAL_GROSS_QUOTA
                            , -entry.getValue(), ptProfit.getPtGrossAdd(), JsonUtils.toJsonString(orderPercentageDO), null, null, null);
                }
            }
        }

        integralService.updateIntegral(BeanUtils.toBean(ptIntegralDO, IntegralSaveReqVO.class));
        ptProfitService.updatePtProfit(PtProfitSaveReqVO.builder().id(ptProfit.getId())
                .ptAdd(ptProfit.getPtAdd())
                .ptGrossAdd(ptProfit.getPtGrossAdd())
                .ptTotalAdd(ptProfit.getPtTotalAdd()).build());

        // 计算平台当日的碰撞支出
        Long sum = 0L;
        for (HashMap<Long, Long> hashMap : afterCrashMap) {
            for (Map.Entry<Long, Long> entry : hashMap.entrySet()) {
                if (entry.getValue() != 0) {
                    sum += entry.getValue();
                }
            }
        }

        createPtProfitDailyStatisticsLog(sum);
    }

    //向集合中放用户获取的积分
    private void addHighQuota(Map<Long, Long> map, Long userId, Long value) {
        for (Long key : map.keySet()) {
            if (key.equals(userId)) {
                map.put(key, map.get(key) + value);
                break;
            }
        }
        map.put(userId, value);
    }

    private void calcIntegral(Long multiply, Long userId, String jsonString) {
        PtProfitDO ptProfit = ptProfitService.getPtProfit();
        ptProfitLogService.addMessage(userId, CaclEnum.GROSS_PROFIT_BONUS_QUOTA_PERC_EXCEED_MAXIMUM_LIMIT, multiply,
                ptProfit.getPtTotalAdd(), jsonString, null, null, null);
    }

    private void createPtProfitDailyStatisticsLog(Long sum) {
        LocalDate now = LocalDate.now();

        //确保每天只有一条记录
        PtProfitDailyStatisticsLogDO ptLog = ptProfitDailyStatisticsLogMapper.selectByEveryday(now);
        Long totalCollisionAmount = 0L;
        if (ptLog != null) {
            totalCollisionAmount = ptLog.getTotalCollisionAmount();
            ptProfitDailyStatisticsLogMapper.deleteById(ptLog.getId());
        }
        //获取平台总收益
        PtProfitDO ptProfitDO = ptProfitMapper.selectList().get(0);

        ptLog = new PtProfitDailyStatisticsLogDO();
        ptLog.setEveryday(now);
        if (!totalCollisionAmount.equals(0L)) {
            ptLog.setTotalCollisionAmount(sum + totalCollisionAmount);
        } else {
            ptLog.setTotalCollisionAmount(sum);
        }
        ptLog.setTotalRemainingAmount(ptProfitDO.getPtGrossAdd());

        ptProfitDailyStatisticsLogMapper.insert(ptLog);
    }

    public Boolean compare(Long highQuota, BigDecimal afterCrash) {
        BigDecimal high = new BigDecimal(String.valueOf(highQuota));
        int i = high.compareTo(afterCrash);
        return i >= 0;
    }

    public void saveBatch(List<PartitionCrashSaveReqVO> partitionCrashSaveReqVOS) {

        List<PartitionCrashDO> ptProfit = BeanUtils.toBean(partitionCrashSaveReqVOS, PartitionCrashDO.class);
        partitionCrashMapper.insertBatch(ptProfit);
    }

    private PartitionBrothersSaveReqVO.PartitionBrothersSaveReqVOBuilder addBrotherEmpty(PartitionBrothersSaveReqVO.PartitionBrothersSaveReqVOBuilder brotherBuilder, DuserDO duserDO) {

        return brotherBuilder.name(duserDO.getName())
                .nickName(duserDO.getNickName())
                .size(0)
                .price(0L)
                .afterHitQuota(0L)
                .hasHit(0);
    }

    private PartitionSonSaveReqVO.PartitionSonSaveReqVOBuilder addSonEmpty(
            PartitionSonSaveReqVO.PartitionSonSaveReqVOBuilder sonBuilder,
            DuserDO duserDO) {
        return sonBuilder.name(duserDO.getName())
                .nickName(duserDO.getNickName())
                .size(0)
                .price(0L)
                .afterHitQuota(0L)
                .hasHit(0);
    }


    // 创建编号 创建今天的编号
    public String crashTodayNo(Long userId) {
        LocalDateTime todayStart = LocalDateTime.of(LocalDate.now(), LocalTime.MIDNIGHT); // 今天的开始时间，即午夜12点
        String todayStartString = todayStart.toString();
        return "CRASH:" + userId + ":" + todayStartString;

    }

    // 获取昨天的编号
    public PartitionCrashDO crashYesterdayNo(Long userId, Integer yesterday) {
        LocalDateTime todayStart = LocalDateTime.of(LocalDate.now(), LocalTime.MIDNIGHT); // 今天的开始时间，即午夜12点
        LocalDateTime localDateTime = todayStart.minusDays(yesterday);
        String yesterdayString = "CRASH:" + userId + ":" + localDateTime;

        PartitionCrashDO partitionCrashDO = partitionCrashMapper.selectOne(new LambdaQueryWrapperX<PartitionCrashDO>().eqIfPresent(PartitionCrashDO::getPartNo, yesterdayString));
        List<PartitionCrashDO> partitionCrashDOS = partitionCrashMapper.selectList((new LambdaQueryWrapperX<PartitionCrashDO>()
                .eq(PartitionCrashDO::getUserId, userId))
                .apply("date(create_time) < date(now())")
        );
        //判断这个用户不是第一次碰撞并且没有查询到昨天的碰撞记录,有可能是昨天或者更早定时任务没有启动导致的,所以再往前查几天
        if (!partitionCrashDOS.isEmpty() && partitionCrashDO == null) {
            return crashYesterdayNo(userId, ++yesterday);
        }
//        return "CRASH:" + userId + ":" + "2024-06-20T00:00";
        return partitionCrashDO;

    }


}
