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.dataobject.sharepath.SharePathDO;
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.enums.IntegralEnum;
import cn.newfeifan.mall.module.distri.enums.ProfitTypeEnum;
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();

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

        // 平台钱包
        PtProfitDO ptProfit = ptProfitMapper.selectList().get(0);

        duserDOS.forEach(k -> {

            // 获取当前用户的钱包
            IntegralDO integralDO = integralService.selectByUser(k.getUserId());
            // 获取用户关系网
            SharePathDO sharePathDO = sharePathService.getSharePathByDescendant(k.getUserId());

            // 获取当前用户的钱包
            if (integralDO != null) {

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

                PartitionSonSaveReqVO.PartitionSonSaveReqVOBuilder leftBuilder = PartitionSonSaveReqVO.builder();
                PartitionBrothersSaveReqVO.PartitionBrothersSaveReqVOBuilder rightBuilder = PartitionBrothersSaveReqVO.builder();
                PartitionCrashSaveReqVO.PartitionCrashSaveReqVOBuilder crashSaveReqVOBuilder = PartitionCrashSaveReqVO.builder();
                leftBuilder.partNo(todayNo);
                leftBuilder.userId(k.getUserId());
                leftBuilder.userName(k.getUserName());
                leftBuilder.hasHit(1);

                rightBuilder.partNo(todayNo);
                rightBuilder.userId(k.getUserId());
                rightBuilder.userName(k.getUserName());
                rightBuilder.hasHit(1);


                crashSaveReqVOBuilder.partNo(todayNo);
                crashSaveReqVOBuilder.userId(k.getUserId());
                crashSaveReqVOBuilder.userName(k.getUserName());

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

                // 获取当前用户的右边分区
                List<OrderCalcDO> rightOrderCalcDOS = sharePathService.selectArea(sharePathDO.getRightChildId(), userId);
                if (rightOrderCalcDOS.isEmpty()) {
                    // 插入空数据
                    rightBuilder = addBrotherEmpty(rightBuilder, k);
                    crashSaveReqVOBuilder.brotherPrice(0L);
                }

                // 合并兄弟分支额度
                Long brotherSumPrice = (long) (rightOrderCalcDOS.stream().mapToLong(OrderCalcDO::getGrossProfit).sum() * grossProfitBonusQuotaPerc);
                rightBuilder.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) {
                    leftBuilder.size(1);
                    rightBuilder.size(0);
                    afterCrash = sonSumPrice - brotherSumPrice;
                    smallQuota = brotherSumPrice;

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

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

                // 积分添加 添加的时候， 需要注意当前用户是否有足够的积分可以获取
                // 碰撞后的额度的
                Long highQuota = integralDO.getHighQuota();

                BigDecimal smallBigDecimal = new BigDecimal(String.valueOf(smallQuota));

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

                //直推人的的本次添加积分
                Long amount = 0L;
                //平台需要补回的收益(也可以理解为用户溢出)
                Long ptReplenish = smallBigDecimal.longValue();
                //直推人
                if (smallBigDecimal.longValue() != 0) {
                    if (highQuota.compareTo(0L) > 0) {
                        if (highQuota.compareTo(smallBigDecimal.longValue()) > 0) {
                            amount = smallBigDecimal.longValue();
                            ptReplenish = 0L;
                        } else {
                            amount = highQuota;
                            ptReplenish = smallBigDecimal.longValue() - highQuota;
                        }
                        addHighQuota(userHighQuotaMap, integralDO.getUserId(), amount);
                    }
                    // 减去最高额度
                    integralDO.setHighQuota(integralDO.getHighQuota() - amount);
                    integralDO.setFreezeQuota(integralDO.getFreezeQuota() + amount);

                    integralDO.setAccumulatedQuota(integralDO.getAccumulatedQuota() + amount);
                    // 碰撞后的额度添加到日志中 增加日志模块
                    integralService.updateIntegral(BeanUtils.toBean(integralDO, IntegralSaveReqVO.class));

                    ptProfit.setPtGrossAdd(ptProfit.getPtGrossAdd() - amount);
                    ptProfit.setPtTotalAdd(ptProfit.getPtTotalAdd() - amount);

                    Long logId = ptProfitLogService.createPtProfitLog(integralDO.getUserId(), amount, ptProfit.getPtGrossAdd(),
                            JsonUtils.toJsonString(orderPercentageDO), IntegralEnum.TEAM_BONUS, ProfitTypeEnum.PT_PROFIT.getType());

                    //记录每日用户有团队奖的记录，后面用来结算的
                    dailyAwardRecordsService.addDailyAwardRecords(sharePathDO.getUserId(), integralDO.getUserId(), amount, logId, ptReplenish);

                    log.info("{}-用户获得了团队奖: ￥{}", integralDO.getUserName(), amount);
                }

                if (!sharePathDO.getUserId().equals(PT_ID)) {
                    map.put(sharePathDO.getUserId(), amount);
                }

                afterCrashMap.add(map);

                log.info("{}用户合赢奖已经计算: 该用户合赢奖为: \t兄弟分区为: {}\t后代分区为: {}\t碰撞分区为: {}\t", k.getUserName(), rightBuilder.build(), leftBuilder.build(), crashSaveReqVOBuilder.build());

                partitionSonSaveReqVOS.add(leftBuilder.build());
                partitionBrothersSaveReqVOS.add(rightBuilder.build());
                partitionCrashSaveReqVOS.add(crashSaveReqVOBuilder.build());


            }
        });

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

        // 计算平台积分
        ptProfitService.updatePtProfit(BeanUtils.toBean(ptProfit, PtProfitSaveReqVO.class));

        // 计算平台当日的碰撞支出
        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.userName(duserDO.getUserName())
                .size(0)
                .price(0L)
                .afterHitQuota(0L)
                .hasHit(0);
    }

    private PartitionSonSaveReqVO.PartitionSonSaveReqVOBuilder addSonEmpty(
            PartitionSonSaveReqVO.PartitionSonSaveReqVOBuilder sonBuilder,
            DuserDO duserDO) {
        return sonBuilder.userName(duserDO.getUserName())
                .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;

    }


}
