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.game.back.base.pojo.enums.OrderStatusEnum;
import com.zanxiang.game.back.serve.config.NacosDynamicParamConfig;
import com.zanxiang.game.back.serve.dao.mapper.GameOceanengineOrderLogMapper;
import com.zanxiang.game.back.serve.oceanengine.MiniGameCallback;
import com.zanxiang.game.back.serve.oceanengine.OceanengineCallbackException;
import com.zanxiang.game.back.serve.pojo.dto.GameOceanengineOrderLogDTO;
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.BackStatusEnum;
import com.zanxiang.game.back.serve.pojo.enums.BackUnitEnum;
import com.zanxiang.game.back.serve.pojo.vo.GameOceanengineOrderLogVO;
import com.zanxiang.game.back.serve.pojo.vo.GameOceanengineOrderSplitLogVO;
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 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;

@Slf4j
@Service
public class GameOceanengineOrderLogServiceImpl extends ServiceImpl<GameOceanengineOrderLogMapper, GameOceanengineOrderLog>
        implements IGameOceanengineOrderLogService {
    @Autowired
    private MiniGameCallback miniGameCallback;
    @Autowired
    private IGameBackPolicyService gameBackPolicyService;
    @Autowired
    private IGameOceanengineUserLogService gameOceanengineUserLogService;
    @Autowired
    private IGameOceanengineBackLogService gameOceanengineBackLogService;
    @DubboReference(providedBy = ServerInfo.SERVER_DUBBO_NAME)
    private IAgentRpc agentRpc;
    @Autowired
    private NacosDynamicParamConfig dynamicParamConfig;
    @Autowired
    private IGameOceanengineOrderSplitLogService gameOceanengineOrderSplitLogService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean callback(GameOceanengineOrderLog orderLog) {
        if (!Objects.equals(orderLog.getOrderStatus(), OrderStatusEnum.SUCCESS_PAY.getValue())) {
            // 头条只要回传支付订单
            return true;
        }
        GameOceanengineUserLog userLog = userLog(orderLog);
        if (userLog == null) {
            // 找不到用户
            return update(new LambdaUpdateWrapper<GameOceanengineOrderLog>()
                    .set(GameOceanengineOrderLog::getBackStatus, BackStatusEnum.NO.getBackStatus())
                    .set(GameOceanengineOrderLog::getBackMoney, orderLog.getAmount())
                    .set(GameOceanengineOrderLog::getBackMsg, "回传失败！找不到回传用户")
                    .eq(GameOceanengineOrderLog::getId, orderLog.getId())
            );
        }

        GameBackPolicy gameBackPolicy = gameBackPolicyService.getById(orderLog.getBackPolicyId());
        Tuple4<Boolean, Long, String, List<Tuple2<Long, LocalDateTime>>> backInfo = BackPolicyUtil.backOrder(orderLog.getOrderNo(), gameBackPolicy, orderLog.getAmount(),
                orderLog.getIsFirstOrder(),
                orderLog.getPayTime(),
                // 此处使用用户最近一次的重新染色时间
                userLog.getCreateTime(),
                orderLog.getOpenId(),
                new OceanengineOrderBackPolicyCheck(this, userLog, orderLog, gameBackPolicy)
        );
        boolean doBack = backInfo.first;
        Long backMoney = backInfo.second;
        String backMsg = backInfo.third;

        if (!doBack) {
            // 不回传
            return update(new LambdaUpdateWrapper<GameOceanengineOrderLog>()
                    .set(GameOceanengineOrderLog::getBackStatus, BackStatusEnum.NO.getBackStatus())
                    .set(GameOceanengineOrderLog::getBackMoney, backMoney)
                    .set(GameOceanengineOrderLog::getBackMsg, backMsg)
                    .eq(GameOceanengineOrderLog::getId, orderLog.getId())
            );
        }
        // 拆单
        if (CollectionUtils.isNotEmpty(backInfo.fourth)) {
            // 需要拆单
            List<GameOceanengineOrderSplitLog> 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(GameOceanengineOrderSplitLog.builder()
                        .backDay(splitOrder.second.toLocalDate())
                        .orderNo(orderLog.getOrderNo())
                        .backIndex(i + 1)
                        .backCount(backInfo.fourth.size())
                        .splitMoney(splitOrder.first)
                        .backTime(splitOrder.second)
                        .backStatus(BackStatusEnum.NO.getBackStatus())
                        .createTime(LocalDateTime.now())
                        .build()
                );
            }
            gameOceanengineOrderSplitLogService.saveBatch(splitOrderLogList);
            return update(new LambdaUpdateWrapper<GameOceanengineOrderLog>()
                    .set(GameOceanengineOrderLog::getBackStatus, BackStatusEnum.NO.getBackStatus())
                    .set(GameOceanengineOrderLog::getBackMoney, backInfo.second)
                    .set(GameOceanengineOrderLog::getBackMsg, backMsg)
                    .eq(GameOceanengineOrderLog::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<GameOceanengineOrderLog>()
                .set(GameOceanengineOrderLog::getBackStatus, backResult.first.getBackStatus())
                .set(GameOceanengineOrderLog::getBackMoney, backMoney)
                .set(GameOceanengineOrderLog::getBackMsg, backMsg)
                .eq(GameOceanengineOrderLog::getId, orderLog.getId())
        );
    }

    @Override
    public IPage<GameOceanengineOrderLogVO> oceanengineOrderLogList(GameOceanengineOrderLogDTO dto) {
        IPage<GameOceanengineOrderLog> page = page(dto.toPage(), new LambdaQueryWrapper<GameOceanengineOrderLog>()
                .eq(StringUtils.isNotBlank(dto.getAgentKey()), GameOceanengineOrderLog::getAgentKey, dto.getAgentKey())
                .ge(dto.getRegTimeBegin() != null, GameOceanengineOrderLog::getRegTime, dto.getRegTimeBegin() == null ? null : LocalDateTime.of(dto.getRegTimeBegin(), LocalTime.MIDNIGHT))
                .le(dto.getRegTimeEnd() != null, GameOceanengineOrderLog::getRegTime, dto.getRegTimeEnd() == null ? null : LocalDateTime.of(dto.getRegTimeEnd(), LocalTime.MAX))
                .eq(null != dto.getGameId(), GameOceanengineOrderLog::getGameId, dto.getGameId())
                .eq(null != dto.getAccountId(), GameOceanengineOrderLog::getAccountId, dto.getAccountId())
                .eq(StringUtils.isNotBlank(dto.getAppId()), GameOceanengineOrderLog::getAppId, dto.getAppId())
                .eq(StringUtils.isNotBlank(dto.getOpenId()), GameOceanengineOrderLog::getOpenId, dto.getOpenId())
                .eq(StringUtils.isNotBlank(dto.getOrderNo()), GameOceanengineOrderLog::getOrderNo, dto.getOrderNo())
                .eq(null != dto.getBackStatus(), GameOceanengineOrderLog::getBackStatus, dto.getBackStatus())
                .eq(dto.getIsFirstOrder() != null, GameOceanengineOrderLog::getIsFirstOrder, dto.getIsFirstOrder())
                .eq(null != dto.getOrderStatus(), GameOceanengineOrderLog::getOrderStatus, dto.getOrderStatus())
                .like(StringUtils.isNotBlank(dto.getRoleName()), GameOceanengineOrderLog::getRoleName, dto.getRoleName())
                .apply(dto.getRegPayIntervalTimeMin() != null, "if(pay_time is not null, TIMESTAMPDIFF(minute, reg_time, pay_time), null) >= {0}", dto.getRegPayIntervalTimeMin())
                .apply(dto.getRegPayIntervalTimeMax() != null, "if(pay_time is not null, TIMESTAMPDIFF(minute, reg_time, pay_time), null) <= {0}", dto.getRegPayIntervalTimeMax())
                .orderByDesc(GameOceanengineOrderLog::getCreateTime)
        );
        IPage<GameOceanengineOrderLogVO> result = new Page<>(page.getCurrent(), page.getSize(), page.getTotal());
        if (CollectionUtils.isEmpty(page.getRecords())) {
            return result;
        }
        result.setRecords(toVOBatch(page.getRecords()));
        return result;
    }

    @Override
    public boolean oceanengineOrderReport(OrderReportDTO dto) {
        listByIds(dto.getOrderIds()).stream()
                .filter(order -> !Objects.equals(order.getBackStatus(), 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.getAmount().equals(total.get())) {
                            throw new BaseException("订单充值金额和回传金额对不上");
                        }
                        log.error("手动拆单回传：{}-{}", orderLog.getId(), StringUtils.join(dto.getSplitMoney(), ","));
                        List<GameOceanengineOrderSplitLog> 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();
                            backMoneyTotal += backMoney;
                            LocalDateTime backTime = beginTime;
                            splitOrderLogList.add(GameOceanengineOrderSplitLog.builder()
                                    .backDay(backTime.toLocalDate())
                                    .orderNo(orderLog.getOrderNo())
                                    .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()));
                        }
                        gameOceanengineOrderSplitLogService.saveBatch(splitOrderLogList);
                        update(new LambdaUpdateWrapper<GameOceanengineOrderLog>()
                                .set(GameOceanengineOrderLog::getBackStatus, BackStatusEnum.NO.getBackStatus())
                                .set(GameOceanengineOrderLog::getBackMoney, backMoneyTotal)
                                .set(GameOceanengineOrderLog::getBackMsg, "手动触发回传（拆单回传）")
                                .eq(GameOceanengineOrderLog::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<GameOceanengineOrderLog>()
                                .set(GameOceanengineOrderLog::getBackStatus, backResult.first.getBackStatus())
                                .set(GameOceanengineOrderLog::getBackMoney, backMoney)
                                .set(GameOceanengineOrderLog::getBackMsg, backMsg)
                                .eq(GameOceanengineOrderLog::getId, orderLog.getId())
                        );
                    }
                });
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Tuple2<BackStatusEnum, String> doCallback(GameOceanengineOrderLog orderLog, LocalDateTime backTime, Long backMoney) {
        GameOceanengineUserLog userLog = userLog(orderLog);
        if (userLog == null) {
            gameOceanengineBackLogService.save(GameOceanengineBackLog.builder()
                    .appId(orderLog.getAppId())
                    .openId(orderLog.getOpenId())
                    .unionId(orderLog.getUnionId())
                    .gameId(orderLog.getGameId())
                    .accountId(orderLog.getAccountId())
                    .clueToken("")
                    .eventType(String.valueOf(MiniGameCallback.EventType.ACTIVE_PAY.getEventType()))
                    .eventLogId(orderLog.getId())
                    .createTime(LocalDateTime.now())
                    .backStatus(BackStatusEnum.FAILED.getBackStatus())
                    .errMsg("找不到用户注册信息")
                    .build());
            return Tuple2.with(BackStatusEnum.FAILED, "找不到用户注册信息");
        }
        Integer eventType = MiniGameCallback.EventType.ACTIVE_PAY.getEventType();
        MiniGameCallback.MiniGameCallbackRequest request = MiniGameCallback.MiniGameCallbackRequest.builder()
                .clue_token(userLog.getClueToken())
                .open_id(orderLog.getOpenId())
                .union_id(orderLog.getUnionId())
                .event_type(String.valueOf(eventType))
                .props(MiniGameCallback.MiniGameCallbackRequest.MiniGameCallbackRequestProps.builder()
                        .pay_amount(backMoney)
                        .build())
                .build();
        BackStatusEnum backStatus = BackStatusEnum.SUCCESS;
        String errMsg = null;
        try {
            miniGameCallback.doCallback(userLog.getAccountReportUrl(), userLog.getAccountReportToken(), request);
        } catch (OceanengineCallbackException e) {
            log.error(e.getMessage(), e);
            backStatus = BackStatusEnum.FAILED;
            errMsg = e.getMsg();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            backStatus = BackStatusEnum.FAILED;
            errMsg = "系统异常：" + e.getMessage();
        }
        gameOceanengineBackLogService.save(GameOceanengineBackLog.builder()
                .appId(orderLog.getAppId())
                .openId(orderLog.getOpenId())
                .unionId(orderLog.getUnionId())
                .gameId(orderLog.getGameId())
                .accountId(orderLog.getAccountId())
                .clueToken(userLog.getClueToken())
                .eventType(request.getEvent_type())
                .eventLogId(orderLog.getId())
                .createTime(LocalDateTime.now())
                .backStatus(backStatus.getBackStatus())
                .errMsg(errMsg)
                .build());
        return Tuple2.with(backStatus, errMsg);
    }

    private List<GameOceanengineOrderLogVO> toVOBatch(List<GameOceanengineOrderLog> logList) {
        if (CollectionUtils.isEmpty(logList)) {
            return Collections.emptyList();
        }
        List<GameOceanengineOrderSplitLogVO> orderSplitList = gameOceanengineOrderSplitLogService.listByOrderNo(logList.stream().map(GameOceanengineOrderLog::getOrderNo).collect(Collectors.toSet()));
        Set<String> agentKeys = logList.stream().map(GameOceanengineOrderLog::getAgentKey).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 -> {
            GameOceanengineOrderLogVO vo = toVOSimple(log);
            if (StringUtils.isNotBlank(log.getAgentKey())) {
                AgentRpcVO agent = agentMap.get(log.getAgentKey());
                if (agent != null) {
                    vo.setAgentName(agent.getAgentName());
                }

            }
            List<GameOceanengineOrderSplitLogVO> splitList = orderSplitList.stream().filter(obj -> obj.getOrderNo().equals(log.getOrderNo())).collect(Collectors.toList());
            vo.setSplitOrderList(splitList);
            return vo;
        }).collect(Collectors.toList());

    }

    private GameOceanengineOrderLogVO toVOSimple(GameOceanengineOrderLog log) {
        if (log == null) {
            return null;
        }
        GameOceanengineOrderLogVO vo = BeanUtil.copy(log, GameOceanengineOrderLogVO.class);
        vo.setRegPayIntervalTime(OrderUtil.regPayIntervalTime(log.getPayTime(), log.getRegTime()));
        return vo;
    }

    private GameOceanengineUserLog userLog(GameOceanengineOrderLog orderLog) {
        return gameOceanengineUserLogService.getOne(new LambdaQueryWrapper<GameOceanengineUserLog>()
                .eq(GameOceanengineUserLog::getGameId, orderLog.getGameId())
                .eq(GameOceanengineUserLog::getAppId, orderLog.getAppId())
                .eq(GameOceanengineUserLog::getOpenId, orderLog.getOpenId())
                .eq(GameOceanengineUserLog::getAccountId, orderLog.getAccountId())
                .orderByDesc(GameOceanengineUserLog::getCreateTime)
                .last("limit 1")
        );
    }

    public static class OceanengineOrderBackPolicyCheck implements BackPolicyUtil.IBackPolicyCheck {
        private final IGameOceanengineOrderLogService gameOceanengineOrderLogService;
        private final GameBackPolicy gameBackPolicy;
        private final GameOceanengineUserLog userLog;
        private final GameOceanengineOrderLog orderLog;

        public OceanengineOrderBackPolicyCheck(IGameOceanengineOrderLogService gameOceanengineOrderLogService, GameOceanengineUserLog userLog, GameOceanengineOrderLog orderLog, GameBackPolicy gameBackPolicy) {
            this.gameOceanengineOrderLogService = gameOceanengineOrderLogService;
            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 gameOceanengineOrderLogService.list(new LambdaQueryWrapper<GameOceanengineOrderLog>()
                        .eq(GameOceanengineOrderLog::getGameId, orderLog.getGameId())
                        .eq(GameOceanengineOrderLog::getAppId, orderLog.getAppId())
                        .eq(GameOceanengineOrderLog::getAccountId, orderLog.getAccountId())
                        .eq(GameOceanengineOrderLog::getBackPolicyId, gameBackPolicy.getId())
                        .eq(GameOceanengineOrderLog::getOrderStatus, OrderStatusEnum.SUCCESS_PAY.getValue())
                        .eq(GameOceanengineOrderLog::getIsFirstOrder, firstPolicy)
                        .ne(GameOceanengineOrderLog::getOrderNo, orderLog.getOrderNo())
                        .orderByDesc(GameOceanengineOrderLog::getCreateTime)
                        .last("limit " + numberOfRound)
                ).stream().filter(log -> log.getBackStatus().equals(BackStatusEnum.SUCCESS.getBackStatus())).count();
            } else if (backUnit == BackUnitEnum.UNIT_DAY) {
                return gameOceanengineOrderLogService.list(new LambdaQueryWrapper<GameOceanengineOrderLog>()
                        .eq(GameOceanengineOrderLog::getGameId, orderLog.getGameId())
                        .eq(GameOceanengineOrderLog::getAppId, orderLog.getAppId())
                        .eq(GameOceanengineOrderLog::getAccountId, orderLog.getAccountId())
                        .eq(GameOceanengineOrderLog::getBackPolicyId, gameBackPolicy.getId())
                        .eq(GameOceanengineOrderLog::getOrderStatus, OrderStatusEnum.SUCCESS_PAY.getValue())
                        .apply(firstPolicy, "date(reg_time) = date(pay_time)")
                        .apply(!firstPolicy, "date(reg_time) != date(pay_time)")
                        .ne(GameOceanengineOrderLog::getOrderNo, orderLog.getOrderNo())
                        .orderByDesc(GameOceanengineOrderLog::getCreateTime)
                        .last("limit " + numberOfRound)
                ).stream().filter(log -> log.getBackStatus().equals(BackStatusEnum.SUCCESS.getBackStatus())).count();
            } else if (backUnit == BackUnitEnum.UNIT_TIME_DAY) {
                return gameOceanengineOrderLogService.list(new LambdaQueryWrapper<GameOceanengineOrderLog>()
                        .eq(GameOceanengineOrderLog::getGameId, orderLog.getGameId())
                        .eq(GameOceanengineOrderLog::getAppId, orderLog.getAppId())
                        .eq(GameOceanengineOrderLog::getAccountId, orderLog.getAccountId())
                        .eq(GameOceanengineOrderLog::getBackPolicyId, gameBackPolicy.getId())
                        .eq(GameOceanengineOrderLog::getOrderStatus, OrderStatusEnum.SUCCESS_PAY.getValue())
                        .apply(firstPolicy, "TIMESTAMPDIFF(HOUR, reg_time, pay_time) < 24")
                        .apply(!firstPolicy, "TIMESTAMPDIFF(HOUR, reg_time, pay_time) >= 24")
                        .ne(GameOceanengineOrderLog::getOrderNo, orderLog.getOrderNo())
                        .orderByDesc(GameOceanengineOrderLog::getCreateTime)
                        .last("limit " + numberOfRound)
                ).stream().filter(log -> log.getBackStatus().equals(BackStatusEnum.SUCCESS.getBackStatus())).count();
            } else if (backUnit == BackUnitEnum.UNIT_TIME_2DAY) {
                return gameOceanengineOrderLogService.list(new LambdaQueryWrapper<GameOceanengineOrderLog>()
                        .eq(GameOceanengineOrderLog::getGameId, orderLog.getGameId())
                        .eq(GameOceanengineOrderLog::getAppId, orderLog.getAppId())
                        .eq(GameOceanengineOrderLog::getAccountId, orderLog.getAccountId())
                        .eq(GameOceanengineOrderLog::getBackPolicyId, gameBackPolicy.getId())
                        .eq(GameOceanengineOrderLog::getOrderStatus, OrderStatusEnum.SUCCESS_PAY.getValue())
                        .apply(firstPolicy, "TIMESTAMPDIFF(HOUR, reg_time, pay_time) < 48")
                        .apply(!firstPolicy, "TIMESTAMPDIFF(HOUR, reg_time, pay_time) >= 48")
                        .ne(GameOceanengineOrderLog::getOrderNo, orderLog.getOrderNo())
                        .orderByDesc(GameOceanengineOrderLog::getCreateTime)
                        .last("limit " + numberOfRound)
                ).stream().filter(log -> log.getBackStatus().equals(BackStatusEnum.SUCCESS.getBackStatus())).count();
            } else if (backUnit == BackUnitEnum.LARGE_AMOUNT) {
                return gameOceanengineOrderLogService.list(new LambdaQueryWrapper<GameOceanengineOrderLog>()
                        .eq(GameOceanengineOrderLog::getGameId, orderLog.getGameId())
                        .eq(GameOceanengineOrderLog::getAppId, orderLog.getAppId())
                        .eq(GameOceanengineOrderLog::getAccountId, orderLog.getAccountId())
                        .eq(GameOceanengineOrderLog::getBackPolicyId, gameBackPolicy.getId())
                        .eq(GameOceanengineOrderLog::getOrderStatus, OrderStatusEnum.SUCCESS_PAY.getValue())
                        .ne(GameOceanengineOrderLog::getOrderNo, orderLog.getOrderNo())
                        .orderByDesc(GameOceanengineOrderLog::getCreateTime)
                        .last("limit " + numberOfRound)
                ).stream().filter(log -> log.getBackStatus().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 gameOceanengineOrderLogService.count(new LambdaQueryWrapper<GameOceanengineOrderLog>()
                        .eq(GameOceanengineOrderLog::getGameId, orderLog.getGameId())
                        .eq(GameOceanengineOrderLog::getAppId, orderLog.getAppId())
                        .eq(GameOceanengineOrderLog::getAccountId, orderLog.getAccountId())
                        .eq(GameOceanengineOrderLog::getBackPolicyId, gameBackPolicy.getId())
                        .eq(GameOceanengineOrderLog::getOrderStatus, OrderStatusEnum.SUCCESS_PAY.getValue())
                        .eq(GameOceanengineOrderLog::getBackStatus, BackStatusEnum.SUCCESS.getBackStatus())
                        .eq(GameOceanengineOrderLog::getOpenId, userId)
                        .eq(GameOceanengineOrderLog::getIsFirstOrder, firstPolicy)
                        .ne(GameOceanengineOrderLog::getOrderNo, orderLog.getOrderNo())
                );
            } else if (backUnit == BackUnitEnum.UNIT_DAY) {
                return gameOceanengineOrderLogService.count(new LambdaQueryWrapper<GameOceanengineOrderLog>()
                        .eq(GameOceanengineOrderLog::getGameId, orderLog.getGameId())
                        .eq(GameOceanengineOrderLog::getAppId, orderLog.getAppId())
                        .eq(GameOceanengineOrderLog::getAccountId, orderLog.getAccountId())
                        .eq(GameOceanengineOrderLog::getBackPolicyId, gameBackPolicy.getId())
                        .eq(GameOceanengineOrderLog::getOrderStatus, OrderStatusEnum.SUCCESS_PAY.getValue())
                        .eq(GameOceanengineOrderLog::getBackStatus, BackStatusEnum.SUCCESS.getBackStatus())
                        .eq(GameOceanengineOrderLog::getOpenId, userId)
                        .apply(firstPolicy, "date(reg_time) = date(pay_time)")
                        .apply(!firstPolicy, "date(reg_time) != date(pay_time)")
                        .ne(GameOceanengineOrderLog::getOrderNo, orderLog.getOrderNo())
                );
            } else if (backUnit == BackUnitEnum.UNIT_TIME_DAY) {
                return gameOceanengineOrderLogService.count(new LambdaQueryWrapper<GameOceanengineOrderLog>()
                        .eq(GameOceanengineOrderLog::getGameId, orderLog.getGameId())
                        .eq(GameOceanengineOrderLog::getAppId, orderLog.getAppId())
                        .eq(GameOceanengineOrderLog::getAccountId, orderLog.getAccountId())
                        .eq(GameOceanengineOrderLog::getBackPolicyId, gameBackPolicy.getId())
                        .eq(GameOceanengineOrderLog::getOrderStatus, OrderStatusEnum.SUCCESS_PAY.getValue())
                        .eq(GameOceanengineOrderLog::getBackStatus, BackStatusEnum.SUCCESS.getBackStatus())
                        .eq(GameOceanengineOrderLog::getOpenId, userId)
                        .apply(firstPolicy, "TIMESTAMPDIFF(HOUR, reg_time, pay_time) < 24")
                        .apply(!firstPolicy, "TIMESTAMPDIFF(HOUR, reg_time, pay_time) >= 24")
                        .ne(GameOceanengineOrderLog::getOrderNo, orderLog.getOrderNo())
                );
            } else if (backUnit == BackUnitEnum.UNIT_TIME_2DAY) {
                return gameOceanengineOrderLogService.count(new LambdaQueryWrapper<GameOceanengineOrderLog>()
                        .eq(GameOceanengineOrderLog::getGameId, orderLog.getGameId())
                        .eq(GameOceanengineOrderLog::getAppId, orderLog.getAppId())
                        .eq(GameOceanengineOrderLog::getAccountId, orderLog.getAccountId())
                        .eq(GameOceanengineOrderLog::getBackPolicyId, gameBackPolicy.getId())
                        .eq(GameOceanengineOrderLog::getOrderStatus, OrderStatusEnum.SUCCESS_PAY.getValue())
                        .eq(GameOceanengineOrderLog::getBackStatus, BackStatusEnum.SUCCESS.getBackStatus())
                        .eq(GameOceanengineOrderLog::getOpenId, userId)
                        .apply(firstPolicy, "TIMESTAMPDIFF(HOUR, reg_time, pay_time) < 48")
                        .apply(!firstPolicy, "TIMESTAMPDIFF(HOUR, reg_time, pay_time) >= 48")
                        .ne(GameOceanengineOrderLog::getOrderNo, orderLog.getOrderNo())
                );
            } else if (backUnit == BackUnitEnum.LARGE_AMOUNT) {
                return gameOceanengineOrderLogService.count(new LambdaQueryWrapper<GameOceanengineOrderLog>()
                        .eq(GameOceanengineOrderLog::getGameId, orderLog.getGameId())
                        .eq(GameOceanengineOrderLog::getAppId, orderLog.getAppId())
                        .eq(GameOceanengineOrderLog::getAccountId, orderLog.getAccountId())
                        .eq(GameOceanengineOrderLog::getBackPolicyId, gameBackPolicy.getId())
                        .eq(GameOceanengineOrderLog::getOrderStatus, OrderStatusEnum.SUCCESS_PAY.getValue())
                        .eq(GameOceanengineOrderLog::getBackStatus, BackStatusEnum.SUCCESS.getBackStatus())
                        .eq(GameOceanengineOrderLog::getOpenId, userId)
                        .ne(GameOceanengineOrderLog::getOrderNo, orderLog.getOrderNo())
                );
            } else {
                throw new RuntimeException("不支持的回传单位[" + backUnit.getValue() + "]");
            }
        }

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

        @Override
        public long markUpForUser(String userId, Long markUpTime) {
            return gameOceanengineOrderLogService.count(new LambdaQueryWrapper<GameOceanengineOrderLog>()
                    .eq(GameOceanengineOrderLog::getGameId, orderLog.getGameId())
                    .eq(GameOceanengineOrderLog::getAppId, orderLog.getAppId())
                    .eq(GameOceanengineOrderLog::getAccountId, orderLog.getAccountId())
                    .eq(GameOceanengineOrderLog::getBackPolicyId, gameBackPolicy.getId())
                    .eq(GameOceanengineOrderLog::getOrderStatus, OrderStatusEnum.SUCCESS_PAY.getValue())
                    .eq(GameOceanengineOrderLog::getBackStatus, BackStatusEnum.SUCCESS.getBackStatus())
                    .eq(GameOceanengineOrderLog::getOpenId, userId)
                    .apply("TIMESTAMPDIFF(MINUTE, reg_time, pay_time) > {0}", markUpTime)
                    .ne(GameOceanengineOrderLog::getOrderNo, orderLog.getOrderNo())
            );
        }

        @Override
        public Long totalRechargeAmount() {
            Map<String, Object> data = gameOceanengineOrderLogService.getMap(new QueryWrapper<GameOceanengineOrderLog>()
                    .select("ifnull(sum(amount), 0) as amount").lambda()
                    .eq(GameOceanengineOrderLog::getGameId, orderLog.getGameId())
                    .eq(GameOceanengineOrderLog::getAppId, orderLog.getAppId())
                    .eq(GameOceanengineOrderLog::getAccountId, orderLog.getAccountId())
                    .eq(GameOceanengineOrderLog::getBackPolicyId, gameBackPolicy.getId())
                    .eq(GameOceanengineOrderLog::getOrderStatus, OrderStatusEnum.SUCCESS_PAY.getValue())
                    .eq(GameOceanengineOrderLog::getOpenId, orderLog.getOpenId())
                    .ne(GameOceanengineOrderLog::getOrderNo, orderLog.getOrderNo())
            );
            return ObjectUtil.objToLong(data.get("amount"), 0L);
        }
    }
}
