package com.zanxiang.game.back.serve.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.sd4324530.jtuple.Tuple2;
import com.github.sd4324530.jtuple.Tuple4;
import com.zanxiang.advertising.tencent.base.AdvertisingTencentServer;
import com.zanxiang.advertising.tencent.base.pojo.dto.DataReportOfAppIdRpcDTO;
import com.zanxiang.advertising.tencent.base.pojo.dto.UserActionRpcDTO;
import com.zanxiang.advertising.tencent.base.rpc.IUserActionSetRpc;
import com.zanxiang.erp.base.ErpServer;
import com.zanxiang.erp.base.rpc.ISysUserRpc;
import com.zanxiang.game.back.base.pojo.enums.OrderStatusEnum;
import com.zanxiang.game.back.serve.dao.mapper.GameTencentOrderMapper;
import com.zanxiang.game.back.serve.pojo.dto.GameTencentOrderDTO;
import com.zanxiang.game.back.serve.pojo.dto.OrderReportDTO;
import com.zanxiang.game.back.serve.pojo.entity.*;
import com.zanxiang.game.back.serve.pojo.enums.ActionTypeEnum;
import com.zanxiang.game.back.serve.pojo.enums.BackStatusEnum;
import com.zanxiang.game.back.serve.pojo.enums.BackUnitEnum;
import com.zanxiang.game.back.serve.pojo.vo.GameTencentOrderSplitLogVO;
import com.zanxiang.game.back.serve.pojo.vo.GameTencentOrderVO;
import com.zanxiang.game.back.serve.service.*;
import com.zanxiang.game.back.serve.utils.BackPolicyUtil;
import com.zanxiang.game.back.serve.utils.OrderUtil;
import com.zanxiang.game.module.base.ServerInfo;
import com.zanxiang.game.module.base.pojo.vo.AgentRpcVO;
import com.zanxiang.game.module.base.rpc.IAgentRpc;
import com.zanxiang.module.util.NumberUtil;
import com.zanxiang.module.util.ObjectUtil;
import com.zanxiang.module.util.bean.BeanUtil;
import com.zanxiang.module.util.exception.BaseException;
import com.zanxiang.module.util.pojo.ResultVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.*;
import java.util.concurrent.atomic.AtomicLong;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * <p>
 * 游戏腾讯订单表 服务实现类
 * </p>
 *
 * @author auto
 * @since 2023-06-01
 */
@Slf4j
@Service
public class GameTencentOrderServiceImpl extends ServiceImpl<GameTencentOrderMapper, GameTencentOrder>
        implements IGameTencentOrderService {
    @DubboReference(providedBy = AdvertisingTencentServer.SERVER_DUBBO_NAME)
    private IUserActionSetRpc userActionSetRpc;
    @DubboReference(providedBy = ErpServer.SERVER_DUBBO_NAME)
    private ISysUserRpc sysUserRpc;
    @Autowired
    private IGameTencentBackLogService gameTencentBackLogService;
    @Autowired
    private IGameBackPolicyService gameBackPolicyService;
    @DubboReference(providedBy = ServerInfo.SERVER_DUBBO_NAME)
    private IAgentRpc agentRpc;
    @Autowired
    private IGameTencentUserService gameTencentUserService;
    @Autowired
    private IGameTencentOrderSplitLogService gameTencentOrderSplitLogService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean orderBack(GameTencentOrder orderLog) {
        if (!Objects.equals(orderLog.getOrderStatus(), OrderStatusEnum.SUCCESS_PAY.getValue())) {
            // 只要回传 支付行为
            return false;
        }
        GameTencentUser userLog = gameTencentUserService.getOne(new LambdaQueryWrapper<GameTencentUser>()
                .eq(GameTencentUser::getGameId, orderLog.getGameId())
                .eq(GameTencentUser::getWechatAppId, orderLog.getWechatAppId())
                .eq(GameTencentUser::getWechatOpenid, orderLog.getWechatOpenid())
                .eq(GameTencentUser::getAdAccountId, orderLog.getAdAccountId())
                .orderByDesc(GameTencentUser::getCreateTime)
                .last("limit 1")
        );
        if (userLog == null) {
            return update(new LambdaUpdateWrapper<GameTencentOrder>()
                    .set(GameTencentOrder::getIsBack, BackStatusEnum.FAILED.getBackStatus())
                    .set(GameTencentOrder::getBackMoney, orderLog.getRechargeMoney())
                    .set(GameTencentOrder::getBackMsg, "回传失败！找不到回传用户")
                    .eq(GameTencentOrder::getId, orderLog.getId())
            );
        }

        GameBackPolicy gameBackPolicy = gameBackPolicyService.getById(orderLog.getBackPolicyId());
        Tuple4<Boolean, Long, String, List<Tuple2<Long, LocalDateTime>>> backInfo = BackPolicyUtil.backOrder(orderLog.getOrderId(), gameBackPolicy, orderLog.getRechargeMoney(),
                orderLog.getIsFirstOrder(),
                orderLog.getPayTime(),
                // 此处使用用户最近一次的重新染色时间
                userLog.getCreateTime(),
                orderLog.getWechatOpenid(),
                new TencentOrderBackPolicyCheck(this, gameBackPolicy, userLog, orderLog));
        boolean doBack = backInfo.first;
        Long backMoney = backInfo.second;
        String backMsg = backInfo.third;
        if (!doBack) {
            return update(new LambdaUpdateWrapper<GameTencentOrder>()
                    .set(GameTencentOrder::getIsBack, BackStatusEnum.NO.getBackStatus())
                    .set(GameTencentOrder::getBackMoney, backMoney)
                    .set(GameTencentOrder::getBackMsg, backMsg)
                    .eq(GameTencentOrder::getId, orderLog.getId())
            );
        }
        // 拆单
        if (CollectionUtils.isNotEmpty(backInfo.fourth)) {
            // 需要拆单
            List<GameTencentOrderSplitLog> splitOrderLogList = new ArrayList<>(backInfo.fourth.size());
            for (int i = 0; i < backInfo.fourth.size(); i++) {
                Tuple2<Long, LocalDateTime> splitOrder = backInfo.fourth.get(i);
                splitOrderLogList.add(GameTencentOrderSplitLog.builder()
                        .backDay(splitOrder.second.toLocalDate())
                        .orderNo(orderLog.getOrderId())
                        .backIndex(i + 1)
                        .backCount(backInfo.fourth.size())
                        .splitMoney(splitOrder.first)
                        .backTime(splitOrder.second)
                        .backStatus(BackStatusEnum.NO.getBackStatus())
                        .createTime(LocalDateTime.now())
                        .build());
            }
            gameTencentOrderSplitLogService.saveBatch(splitOrderLogList);
            return update(new LambdaUpdateWrapper<GameTencentOrder>()
                    .set(GameTencentOrder::getIsBack, BackStatusEnum.NO.getBackStatus())
                    .set(GameTencentOrder::getBackMoney, backInfo.second)
                    .set(GameTencentOrder::getBackMsg, backMsg)
                    .eq(GameTencentOrder::getId, orderLog.getId())
            );
        }

        Tuple2<BackStatusEnum, String> backResult = doCallback(orderLog, orderLog.getPayTime(), backMoney);
        if (StringUtils.isNotBlank(backResult.second)) {
            backMsg = backMsg + ("回传失败：" + backResult.second);
        }
        return update(new LambdaUpdateWrapper<GameTencentOrder>()
                .set(GameTencentOrder::getIsBack, backResult.first.getBackStatus())
                .set(GameTencentOrder::getBackMoney, backMoney)
                .set(GameTencentOrder::getBackMsg, backMsg)
                .eq(GameTencentOrder::getId, orderLog.getId())
        );
    }


    @Override
    public IPage<GameTencentOrderVO> tencentOrderLogList(GameTencentOrderDTO dto) {
        IPage<GameTencentOrder> page = page(dto.toPage(), new LambdaQueryWrapper<GameTencentOrder>()
                .ge(dto.getRegTimeBegin() != null, GameTencentOrder::getRegisterTime, dto.getRegTimeBegin() == null ? null : LocalDateTime.of(dto.getRegTimeBegin(), LocalTime.MIDNIGHT))
                .le(dto.getRegTimeEnd() != null, GameTencentOrder::getRegisterTime, dto.getRegTimeEnd() == null ? null : LocalDateTime.of(dto.getRegTimeEnd(), LocalTime.MAX))
                .eq(StringUtils.isNotBlank(dto.getChannel()), GameTencentOrder::getChannel, dto.getChannel())
                .eq(null != dto.getGameId(), GameTencentOrder::getGameId, dto.getGameId())
                .eq(null != dto.getAdAccountId(), GameTencentOrder::getAdAccountId, dto.getAdAccountId())
                .eq(StringUtils.isNotBlank(dto.getWechatAppId()), GameTencentOrder::getWechatAppId, dto.getWechatAppId())
                .eq(StringUtils.isNotBlank(dto.getWechatOpenid()), GameTencentOrder::getWechatOpenid, dto.getWechatOpenid())
                .eq(StringUtils.isNotBlank(dto.getOrderId()), GameTencentOrder::getOrderId, dto.getOrderId())
                .eq(null != dto.getIsBack(), GameTencentOrder::getIsBack, dto.getIsBack())
                .eq(null != dto.getOrderStatus(), GameTencentOrder::getOrderStatus, dto.getOrderStatus())
                .eq(dto.getIsFirstOrder() != null, GameTencentOrder::getIsFirstOrder, dto.getIsFirstOrder())
                .like(StringUtils.isNotBlank(dto.getRoleName()), GameTencentOrder::getRoleName, dto.getRoleName())
                .apply(dto.getRegPayIntervalTimeMin() != null, "if(pay_time is not null, TIMESTAMPDIFF(minute, register_time, pay_time), null) >= {0}", dto.getRegPayIntervalTimeMin())
                .apply(dto.getRegPayIntervalTimeMax() != null, "if(pay_time is not null, TIMESTAMPDIFF(minute, register_time, pay_time), null) <= {0}", dto.getRegPayIntervalTimeMax())
                .orderByDesc(GameTencentOrder::getCreateTime)
        );
        IPage<GameTencentOrderVO> result = new Page<>(page.getCurrent(), page.getSize(), page.getTotal());
        if (CollectionUtils.isEmpty(page.getRecords())) {
            return result;
        }
        result.setRecords(toVOBatch(page.getRecords()));
        return result;
    }

    private List<GameTencentOrderVO> toVOBatch(List<GameTencentOrder> logList) {
        if (CollectionUtils.isEmpty(logList)) {
            return Collections.emptyList();
        }
        List<GameTencentOrderSplitLogVO> orderSplitList = gameTencentOrderSplitLogService.listByOrderNo(logList.stream().map(GameTencentOrder::getOrderId).collect(Collectors.toList()));
        Set<String> agentKeys = logList.stream().map(GameTencentOrder::getChannel).filter(StringUtils::isNotBlank).collect(Collectors.toSet());
        Map<String, AgentRpcVO> agentMap = CollectionUtils.isEmpty(agentKeys) ? Collections.emptyMap() : agentRpc.getByAgentKeys(new ArrayList<>(agentKeys))
                .getData().stream().collect(Collectors.toMap(AgentRpcVO::getAgentKey, Function.identity()));
        return logList.stream().map(log -> {
            GameTencentOrderVO vo = toVOSimple(log);
            if (StringUtils.isNotBlank(log.getChannel())) {
                AgentRpcVO agent = agentMap.get(log.getChannel());
                if (agent != null) {
                    vo.setAgentName(agent.getAgentName());
                }
            }
            List<GameTencentOrderSplitLogVO> splitList = orderSplitList.stream().filter(obj -> obj.getOrderNo().equals(log.getOrderId())).collect(Collectors.toList());
            vo.setSplitOrderList(splitList);
            return vo;
        }).collect(Collectors.toList());
    }

    private GameTencentOrderVO toVOSimple(GameTencentOrder log) {
        if (log == null) {
            return null;
        }
        GameTencentOrderVO vo = BeanUtil.copy(log, GameTencentOrderVO.class);
        vo.setRegPayIntervalTime(OrderUtil.regPayIntervalTime(log.getPayTime(), log.getRegisterTime()));
        return vo;
    }

    @Override
    public boolean tencentOrderReport(OrderReportDTO dto) {
        listByIds(dto.getOrderIds()).stream()
                .filter(order -> !Objects.equals(order.getIsBack(), BackStatusEnum.SUCCESS.getBackStatus()))
                .forEach(orderLog -> {
                    if (dto.getSplitOrder()) {
                        AtomicLong total = new AtomicLong(0);
                        dto.getSplitMoney().forEach(money -> {
                            total.addAndGet(NumberUtil.multiply100(money).longValue());
                        });
                        if (!orderLog.getRechargeMoney().equals(total.get())) {
                            throw new BaseException("订单充值金额和回传金额对不上");
                        }
                        log.error("手动拆单回传：{}-{}", orderLog.getId(), StringUtils.join(dto.getSplitMoney(), ","));
                        List<GameTencentOrderSplitLog> splitOrderLogList = new ArrayList<>(dto.getSplitMoney().size());
                        LocalDateTime beginTime = LocalDateTime.now();
                        long backMoneyTotal = 0L;
                        for (int i = 0; i < dto.getSplitMoney().size(); i++) {
                            long backMoney = NumberUtil.multiply100(dto.getSplitMoney().get(i)).longValue();
                            LocalDateTime backTime = beginTime;
                            backMoneyTotal += backMoney;
                            splitOrderLogList.add(GameTencentOrderSplitLog.builder()
                                    .backDay(backTime.toLocalDate())
                                    .orderNo(orderLog.getOrderId())
                                    .backIndex(i + 1)
                                    .backCount(dto.getSplitMoney().size())
                                    .splitMoney(backMoney)
                                    .backTime(backTime)
                                    .backStatus(BackStatusEnum.NO.getBackStatus())
                                    .createTime(LocalDateTime.now())
                                    .build());
                            beginTime = beginTime.plusMinutes(RandomUtils.nextInt(dto.getBetweenMinuteMin(), dto.getBetweenMinuteMax()));
                        }
                        gameTencentOrderSplitLogService.saveBatch(splitOrderLogList);
                        update(new LambdaUpdateWrapper<GameTencentOrder>()
                                .set(GameTencentOrder::getIsBack, BackStatusEnum.NO.getBackStatus())
                                .set(GameTencentOrder::getBackMoney, backMoneyTotal)
                                .set(GameTencentOrder::getBackMsg, "手动触发回传（拆单回传）")
                                .eq(GameTencentOrder::getId, orderLog.getId())
                        );
                    } else {
                        log.error("手动直接回传：{}-{}", orderLog.getId(), dto.getBackMoney());
                        long backMoney = NumberUtil.multiply100(dto.getBackMoney()).longValue();
                        Tuple2<BackStatusEnum, String> backResult = doCallback(orderLog, orderLog.getPayTime(), backMoney);
                        String backMsg = "手动触发回传！";
                        if (StringUtils.isNotBlank(backResult.second)) {
                            backMsg += ("回传失败：" + backResult.second);
                        }
                        update(new LambdaUpdateWrapper<GameTencentOrder>()
                                .set(GameTencentOrder::getIsBack, backResult.first.getBackStatus())
                                .set(GameTencentOrder::getBackMoney, backMoney)
                                .set(GameTencentOrder::getBackMsg, backMsg)
                                .eq(GameTencentOrder::getId, orderLog.getId())
                        );
                    }
                });
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Tuple2<BackStatusEnum, String> doCallback(GameTencentOrder orderLog, LocalDateTime backTime, Long backMoney) {
        String actionType = orderLog.getOrderStatus().equals(OrderStatusEnum.SUCCESS_PAY.getValue()) ?
                ActionTypeEnum.PURCHASE.getActionType() : ActionTypeEnum.COMPLETE_ORDER.getActionType();
        Map<String, Object> actionParam = new HashMap<>(2);
        actionParam.put("claim_type", 0);
        actionParam.put("value", backMoney);
        DataReportOfAppIdRpcDTO dataReportOfAppIdRpcDTO = DataReportOfAppIdRpcDTO.builder()
                .appId(orderLog.getWechatAppId())
                .userActionSetId(orderLog.getUserActionSetId())
                .action(UserActionRpcDTO.builder()
                        .actionTime(backTime)
                        .actionType(actionType)
                        .userId(UserActionRpcDTO.UserIdRpcDTO.builder()
                                .wechatAppId(orderLog.getWechatAppId())
                                .wechatOpenid(orderLog.getWechatOpenid())
                                .build())
                        .actionParam(actionParam)
                        .build())
                .build();

        GameTencentBackLog gameTencentBackLog = GameTencentBackLog.builder()
                .gameId(orderLog.getGameId())
                .adAccountId(orderLog.getAdAccountId())
                .actionTime(backTime)
                .createTime(LocalDateTime.now())
                .actionType(actionType)
                .orderId(orderLog.getOrderId())
                .wechatAppId(orderLog.getWechatAppId())
                .wechatOpenid(orderLog.getWechatOpenid())
                .userActionSetId(orderLog.getUserActionSetId())
                .actionParam(actionParam.toString())
                .build();
        ResultVO<Boolean> result = userActionSetRpc.reportByAppId(dataReportOfAppIdRpcDTO);
        BackStatusEnum backStatus = BackStatusEnum.FAILED;
        if (result.isSuccess()) {
            backStatus = BackStatusEnum.SUCCESS;
            gameTencentBackLog.setBackLog("回传成功");
        } else {
            log.error("回传腾讯订单失败，失败原因：{}", result.getMsg());
            gameTencentBackLog.setBackLog(result.getMsg());
        }
        gameTencentBackLogService.save(gameTencentBackLog);
        return Tuple2.with(backStatus, gameTencentBackLog.getBackLog());
    }

    public static class TencentOrderBackPolicyCheck implements BackPolicyUtil.IBackPolicyCheck {
        private final IGameTencentOrderService gameTencentOrderService;
        private final GameBackPolicy gameBackPolicy;
        private final GameTencentUser userLog;
        private final GameTencentOrder orderLog;

        public TencentOrderBackPolicyCheck(IGameTencentOrderService gameTencentOrderService,
                                           GameBackPolicy gameBackPolicy,
                                           GameTencentUser userLog,
                                           GameTencentOrder orderLog) {
            this.gameTencentOrderService = gameTencentOrderService;
            this.gameBackPolicy = gameBackPolicy;
            this.userLog = userLog;
            this.orderLog = orderLog;

        }

        @Override
        public long backCountForFixedRate(int numberOfRound, BackUnitEnum backUnit, Boolean firstPolicy) {
            numberOfRound = numberOfRound - 1;
            if (backUnit == BackUnitEnum.UNIT_ONCE) {
                return gameTencentOrderService.list(new LambdaQueryWrapper<GameTencentOrder>()
                        .eq(GameTencentOrder::getGameId, orderLog.getGameId())
                        .eq(GameTencentOrder::getWechatAppId, orderLog.getWechatAppId())
                        .eq(GameTencentOrder::getAdAccountId, orderLog.getAdAccountId())
                        .eq(GameTencentOrder::getBackPolicyId, gameBackPolicy.getId())
                        .eq(GameTencentOrder::getOrderStatus, OrderStatusEnum.SUCCESS_PAY.getValue())
                        .eq(GameTencentOrder::getIsFirstOrder, firstPolicy)
                        .ne(GameTencentOrder::getOrderId, orderLog.getOrderId())
                        .orderByDesc(GameTencentOrder::getCreateTime)
                        .last("limit " + numberOfRound)
                ).stream().filter(log -> log.getIsBack().equals(BackStatusEnum.SUCCESS.getBackStatus())).count();
            } else if (backUnit == BackUnitEnum.UNIT_DAY) {
                return gameTencentOrderService.list(new LambdaQueryWrapper<GameTencentOrder>()
                        .eq(GameTencentOrder::getGameId, orderLog.getGameId())
                        .eq(GameTencentOrder::getWechatAppId, orderLog.getWechatAppId())
                        .eq(GameTencentOrder::getAdAccountId, orderLog.getAdAccountId())
                        .eq(GameTencentOrder::getBackPolicyId, gameBackPolicy.getId())
                        .eq(GameTencentOrder::getOrderStatus, OrderStatusEnum.SUCCESS_PAY.getValue())
                        .apply(firstPolicy, "date(recharge_time) = date(pay_time)")
                        .apply(!firstPolicy, "date(recharge_time) != date(pay_time)")
                        .ne(GameTencentOrder::getOrderId, orderLog.getOrderId())
                        .orderByDesc(GameTencentOrder::getCreateTime)
                        .last("limit " + numberOfRound)
                ).stream().filter(log -> log.getIsBack().equals(BackStatusEnum.SUCCESS.getBackStatus())).count();
            } else if (backUnit == BackUnitEnum.UNIT_TIME_DAY) {
                return gameTencentOrderService.list(new LambdaQueryWrapper<GameTencentOrder>()
                        .eq(GameTencentOrder::getGameId, orderLog.getGameId())
                        .eq(GameTencentOrder::getWechatAppId, orderLog.getWechatAppId())
                        .eq(GameTencentOrder::getAdAccountId, orderLog.getAdAccountId())
                        .eq(GameTencentOrder::getBackPolicyId, gameBackPolicy.getId())
                        .eq(GameTencentOrder::getOrderStatus, OrderStatusEnum.SUCCESS_PAY.getValue())
                        .apply(firstPolicy, "TIMESTAMPDIFF(HOUR, recharge_time, pay_time) < 24")
                        .apply(!firstPolicy, "TIMESTAMPDIFF(HOUR, recharge_time, pay_time) >= 24")
                        .ne(GameTencentOrder::getOrderId, orderLog.getOrderId())
                        .orderByDesc(GameTencentOrder::getCreateTime)
                        .last("limit " + numberOfRound)
                ).stream().filter(log -> log.getIsBack().equals(BackStatusEnum.SUCCESS.getBackStatus())).count();
            } else if (backUnit == BackUnitEnum.UNIT_TIME_2DAY) {
                return gameTencentOrderService.list(new LambdaQueryWrapper<GameTencentOrder>()
                        .eq(GameTencentOrder::getGameId, orderLog.getGameId())
                        .eq(GameTencentOrder::getWechatAppId, orderLog.getWechatAppId())
                        .eq(GameTencentOrder::getAdAccountId, orderLog.getAdAccountId())
                        .eq(GameTencentOrder::getBackPolicyId, gameBackPolicy.getId())
                        .eq(GameTencentOrder::getOrderStatus, OrderStatusEnum.SUCCESS_PAY.getValue())
                        .apply(firstPolicy, "TIMESTAMPDIFF(HOUR, recharge_time, pay_time) < 48")
                        .apply(!firstPolicy, "TIMESTAMPDIFF(HOUR, recharge_time, pay_time) >= 48")
                        .ne(GameTencentOrder::getOrderId, orderLog.getOrderId())
                        .orderByDesc(GameTencentOrder::getCreateTime)
                        .last("limit " + numberOfRound)
                ).stream().filter(log -> log.getIsBack().equals(BackStatusEnum.SUCCESS.getBackStatus())).count();
            } else if (backUnit == BackUnitEnum.LARGE_AMOUNT) {
                return gameTencentOrderService.list(new LambdaQueryWrapper<GameTencentOrder>()
                        .eq(GameTencentOrder::getGameId, orderLog.getGameId())
                        .eq(GameTencentOrder::getWechatAppId, orderLog.getWechatAppId())
                        .eq(GameTencentOrder::getAdAccountId, orderLog.getAdAccountId())
                        .eq(GameTencentOrder::getBackPolicyId, gameBackPolicy.getId())
                        .eq(GameTencentOrder::getOrderStatus, OrderStatusEnum.SUCCESS_PAY.getValue())
                        .ne(GameTencentOrder::getOrderId, orderLog.getOrderId())
                        .orderByDesc(GameTencentOrder::getCreateTime)
                        .last("limit " + numberOfRound)
                ).stream().filter(log -> log.getIsBack().equals(BackStatusEnum.SUCCESS.getBackStatus())).count();
            } else {
                throw new RuntimeException("不支持的回传单位[" + backUnit.getValue() + "]");
            }
        }

        @Override
        public long backCountForUser(BackUnitEnum backUnit, String userId, Boolean firstPolicy) {
            if (backUnit == BackUnitEnum.UNIT_ONCE) {
                if (firstPolicy) {
                    // 首单直接返回 0，必定回传
                    return 0;
                }
                return gameTencentOrderService.count(new LambdaQueryWrapper<GameTencentOrder>()
                        .eq(GameTencentOrder::getGameId, orderLog.getGameId())
                        .eq(GameTencentOrder::getWechatAppId, orderLog.getWechatAppId())
                        .eq(GameTencentOrder::getAdAccountId, orderLog.getAdAccountId())
                        .eq(GameTencentOrder::getBackPolicyId, gameBackPolicy.getId())
                        .eq(GameTencentOrder::getOrderStatus, OrderStatusEnum.SUCCESS_PAY.getValue())
                        .eq(GameTencentOrder::getIsBack, BackStatusEnum.SUCCESS.getBackStatus())
                        .eq(GameTencentOrder::getWechatOpenid, userId)
                        .eq(GameTencentOrder::getIsFirstOrder, firstPolicy)
                        .ne(GameTencentOrder::getOrderId, orderLog.getOrderId())
                );
            } else if (backUnit == BackUnitEnum.UNIT_DAY) {
                return gameTencentOrderService.count(new LambdaQueryWrapper<GameTencentOrder>()
                        .eq(GameTencentOrder::getGameId, orderLog.getGameId())
                        .eq(GameTencentOrder::getWechatAppId, orderLog.getWechatAppId())
                        .eq(GameTencentOrder::getAdAccountId, orderLog.getAdAccountId())
                        .eq(GameTencentOrder::getBackPolicyId, gameBackPolicy.getId())
                        .eq(GameTencentOrder::getOrderStatus, OrderStatusEnum.SUCCESS_PAY.getValue())
                        .eq(GameTencentOrder::getIsBack, BackStatusEnum.SUCCESS.getBackStatus())
                        .eq(GameTencentOrder::getWechatOpenid, userId)
                        .apply(firstPolicy, "date(register_time) = date(pay_time)")
                        .apply(!firstPolicy, "date(register_time) != date(pay_time)")
                        .ne(GameTencentOrder::getOrderId, orderLog.getOrderId())
                );
            } else if (backUnit == BackUnitEnum.UNIT_TIME_DAY) {
                return gameTencentOrderService.count(new LambdaQueryWrapper<GameTencentOrder>()
                        .eq(GameTencentOrder::getGameId, orderLog.getGameId())
                        .eq(GameTencentOrder::getWechatAppId, orderLog.getWechatAppId())
                        .eq(GameTencentOrder::getAdAccountId, orderLog.getAdAccountId())
                        .eq(GameTencentOrder::getBackPolicyId, gameBackPolicy.getId())
                        .eq(GameTencentOrder::getOrderStatus, OrderStatusEnum.SUCCESS_PAY.getValue())
                        .eq(GameTencentOrder::getIsBack, BackStatusEnum.SUCCESS.getBackStatus())
                        .eq(GameTencentOrder::getWechatOpenid, userId)
                        .apply(firstPolicy, "TIMESTAMPDIFF(HOUR, recharge_time, pay_time) < 24")
                        .apply(!firstPolicy, "TIMESTAMPDIFF(HOUR, recharge_time, pay_time) >= 24")
                        .ne(GameTencentOrder::getOrderId, orderLog.getOrderId())
                );
            } else if (backUnit == BackUnitEnum.UNIT_TIME_2DAY) {
                return gameTencentOrderService.count(new LambdaQueryWrapper<GameTencentOrder>()
                        .eq(GameTencentOrder::getGameId, orderLog.getGameId())
                        .eq(GameTencentOrder::getWechatAppId, orderLog.getWechatAppId())
                        .eq(GameTencentOrder::getAdAccountId, orderLog.getAdAccountId())
                        .eq(GameTencentOrder::getBackPolicyId, gameBackPolicy.getId())
                        .eq(GameTencentOrder::getOrderStatus, OrderStatusEnum.SUCCESS_PAY.getValue())
                        .eq(GameTencentOrder::getIsBack, BackStatusEnum.SUCCESS.getBackStatus())
                        .eq(GameTencentOrder::getWechatOpenid, userId)
                        .apply(firstPolicy, "TIMESTAMPDIFF(HOUR, recharge_time, pay_time) < 48")
                        .apply(!firstPolicy, "TIMESTAMPDIFF(HOUR, recharge_time, pay_time) >= 48")
                        .ne(GameTencentOrder::getOrderId, orderLog.getOrderId())
                );
            } else if (backUnit == BackUnitEnum.LARGE_AMOUNT) {
                return gameTencentOrderService.count(new LambdaQueryWrapper<GameTencentOrder>()
                        .eq(GameTencentOrder::getGameId, orderLog.getGameId())
                        .eq(GameTencentOrder::getWechatAppId, orderLog.getWechatAppId())
                        .eq(GameTencentOrder::getAdAccountId, orderLog.getAdAccountId())
                        .eq(GameTencentOrder::getBackPolicyId, gameBackPolicy.getId())
                        .eq(GameTencentOrder::getOrderStatus, OrderStatusEnum.SUCCESS_PAY.getValue())
                        .eq(GameTencentOrder::getIsBack, BackStatusEnum.SUCCESS.getBackStatus())
                        .eq(GameTencentOrder::getWechatOpenid, userId)
                        .ne(GameTencentOrder::getOrderId, orderLog.getOrderId())
                );
            } else {
                throw new RuntimeException("不支持的回传单位[" + backUnit.getValue() + "]");
            }
        }

        @Override
        public long markUpOfFixedRate(int numberOfRound, Long markUpTime) {
            numberOfRound = numberOfRound - 1;
            return gameTencentOrderService.list(new LambdaQueryWrapper<GameTencentOrder>()
                    .eq(GameTencentOrder::getGameId, orderLog.getGameId())
                    .eq(GameTencentOrder::getWechatAppId, orderLog.getWechatAppId())
                    .eq(GameTencentOrder::getAdAccountId, orderLog.getAdAccountId())
                    .eq(GameTencentOrder::getBackPolicyId, gameBackPolicy.getId())
                    .eq(GameTencentOrder::getOrderStatus, OrderStatusEnum.SUCCESS_PAY.getValue())
                    .apply("TIMESTAMPDIFF(MINUTE, recharge_time, pay_time) > {0}", markUpTime)
                    .ne(GameTencentOrder::getOrderId, orderLog.getOrderId())
                    .orderByDesc(GameTencentOrder::getCreateTime)
                    .last("limit " + numberOfRound)
            ).stream().filter(log -> log.getIsBack().equals(BackStatusEnum.SUCCESS.getBackStatus())).count();
        }

        @Override
        public long markUpForUser(String userId, Long markUpTime) {
            return gameTencentOrderService.count(new LambdaQueryWrapper<GameTencentOrder>()
                    .eq(GameTencentOrder::getGameId, orderLog.getGameId())
                    .eq(GameTencentOrder::getWechatAppId, orderLog.getWechatAppId())
                    .eq(GameTencentOrder::getAdAccountId, orderLog.getAdAccountId())
                    .eq(GameTencentOrder::getBackPolicyId, gameBackPolicy.getId())
                    .eq(GameTencentOrder::getOrderStatus, OrderStatusEnum.SUCCESS_PAY.getValue())
                    .eq(GameTencentOrder::getIsBack, BackStatusEnum.SUCCESS.getBackStatus())
                    .eq(GameTencentOrder::getWechatOpenid, userId)
                    .apply("TIMESTAMPDIFF(MINUTE, recharge_time, pay_time) > {0}", markUpTime)
                    .ne(GameTencentOrder::getOrderId, orderLog.getOrderId())
            );
        }

        @Override
        public Long totalRechargeAmount() {
            Map<String, Object> data = gameTencentOrderService.getMap(new QueryWrapper<GameTencentOrder>()
                    .select("ifnull(sum(recharge_money), 0) as recharge_money").lambda()
                    .eq(GameTencentOrder::getGameId, orderLog.getGameId())
                    .eq(GameTencentOrder::getWechatAppId, orderLog.getWechatAppId())
                    .eq(GameTencentOrder::getAdAccountId, orderLog.getAdAccountId())
                    .eq(GameTencentOrder::getBackPolicyId, gameBackPolicy.getId())
                    .eq(GameTencentOrder::getOrderStatus, OrderStatusEnum.SUCCESS_PAY.getValue())
                    .eq(GameTencentOrder::getWechatOpenid, orderLog.getWechatOpenid())
                    .ne(GameTencentOrder::getOrderId, orderLog.getOrderId())
            );
            return ObjectUtil.objToLong(data.get("recharge_money"), 0L);
        }
    }
}
