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.dao.mapper.GameTencentAppOrderMapper;
import com.zanxiang.game.back.serve.oceanengine.MiniGameCallback;
import com.zanxiang.game.back.serve.pojo.dto.GameTencentAppOrderDTO;
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.GameTencentAppOrderSplitLogVO;
import com.zanxiang.game.back.serve.pojo.vo.GameTencentAppOrderVO;
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.ObjectUtil;
import com.zanxiang.module.util.bean.BeanUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
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.function.Function;
import java.util.stream.Collectors;

@Slf4j
@Service
public class GameTencentAppOrderServiceImpl extends ServiceImpl<GameTencentAppOrderMapper, GameTencentAppOrder>
        implements IGameTencentAppOrderService {

    @DubboReference(providedBy = ServerInfo.SERVER_DUBBO_NAME)
    private IAgentRpc agentRpc;

    @Autowired
    private IGameBackPolicyService gameBackPolicyService;

    @Autowired
    private IGameTencentAppUserService gameTencentAppUserService;


    @Autowired
    private IGameTencentAppBackLogService gameTencentAppBackLogService;

    @Autowired
    private IGameTencentAppOrderSplitLogService gameTencentAppOrderSplitLogService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean callback(GameTencentAppOrder orderLog) {
        if (!Objects.equals(orderLog.getOrderStatus(), OrderStatusEnum.SUCCESS_PAY.getValue())) {
            // 腾讯只要回传支付订单
            return true;
        }
        GameTencentAppUser userLog = userLog(orderLog);
        if (userLog == null) {
            // 找不到用户
            return update(new LambdaUpdateWrapper<GameTencentAppOrder>()
                    .set(GameTencentAppOrder::getBackStatus, BackStatusEnum.NO.getBackStatus())
                    .set(GameTencentAppOrder::getBackMoney, orderLog.getAmount())
                    .set(GameTencentAppOrder::getBackMsg, "回传失败！找不到回传用户")
                    .eq(GameTencentAppOrder::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.getUserId(),
                new GameTencentAppOrderServiceImpl.TencentAppOrderBackPolicyCheck(this, gameTencentAppOrderSplitLogService, userLog, orderLog, gameBackPolicy)
        );
        boolean doBack = backInfo.first;
        Long backMoney = backInfo.second;
        String backMsg = backInfo.third;

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

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


    private Tuple2<BackStatusEnum, String> doCallback(GameTencentAppOrder orderLog,  Long backMoney) {
        GameTencentAppUser userLog = userLog(orderLog);
        if (userLog == null) {
            gameTencentAppBackLogService.save(GameTencentAppBackLog.builder()
                    .userId(orderLog.getUserId())
                    .mac(orderLog.getMac())
                    .imei(orderLog.getImei())
                    .oaid(orderLog.getOaid())
                    .androidId(orderLog.getAndroidId())
                    .idfa(orderLog.getIdfa())
                    .caid(orderLog.getCaid())
                    .gameId(orderLog.getGameId())
                    .accountId(orderLog.getAccountId())
                    .eventType(String.valueOf(MiniGameCallback.EventType.ACTIVE_PAY.getEventType()))
                    .eventLogId(orderLog.getId())
                    .createTime(LocalDateTime.now())
                    .payAmount(backMoney)
                    .backStatus(BackStatusEnum.FAILED.getBackStatus())
                    .errMsg("找不到用户注册信息")
                    .build());
            return Tuple2.with(BackStatusEnum.FAILED, "找不到用户注册信息");
        }
        Integer eventType = MiniGameCallback.EventType.ACTIVE_PAY.getEventType();
        BackStatusEnum backStatus = BackStatusEnum.SUCCESS;
        String errMsg = null;
        gameTencentAppBackLogService.save(GameTencentAppBackLog.builder()
                .userId(orderLog.getUserId())
                .mac(orderLog.getMac())
                .imei(orderLog.getImei())
                .oaid(orderLog.getOaid())
                .androidId(orderLog.getAndroidId())
                .idfa(orderLog.getIdfa())
                .caid(orderLog.getCaid())
                .gameId(orderLog.getGameId())
                .accountId(orderLog.getAccountId())
                .eventType(String.valueOf(eventType))
                .eventLogId(orderLog.getId())
                .createTime(LocalDateTime.now())
                .payAmount(backMoney)
                .backStatus(backStatus.getBackStatus())
                .errMsg(errMsg)
                .build());
        return Tuple2.with(backStatus, errMsg);
    }

    @Override
    public IPage<GameTencentAppOrderVO> gameTencentAppOrderLogList(GameTencentAppOrderDTO dto) {
        IPage<GameTencentAppOrder> page = page(dto.toPage(), new LambdaQueryWrapper<GameTencentAppOrder>()
                .eq(StringUtils.isNotBlank(dto.getUserId()), GameTencentAppOrder::getUserId, dto.getUserId())
                .eq(StringUtils.isNotBlank(dto.getMac()), GameTencentAppOrder::getMac, dto.getMac())
                .eq(StringUtils.isNotBlank(dto.getImei()), GameTencentAppOrder::getImei, dto.getImei())
                .eq(StringUtils.isNotBlank(dto.getOaid()), GameTencentAppOrder::getOaid, dto.getOaid())
                .eq(StringUtils.isNotBlank(dto.getAndroidId()), GameTencentAppOrder::getAndroidId, dto.getAndroidId())
                .eq(StringUtils.isNotBlank(dto.getIdfa()), GameTencentAppOrder::getIdfa, dto.getIdfa())
                .eq(StringUtils.isNotBlank(dto.getCaid()), GameTencentAppOrder::getCaid, dto.getCaid())
                .eq(StringUtils.isNotBlank(dto.getAgentKey()), GameTencentAppOrder::getAgentKey, dto.getAgentKey())
                .ge(dto.getRegTimeBegin() != null, GameTencentAppOrder::getRegTime, dto.getRegTimeBegin() == null ? null : LocalDateTime.of(dto.getRegTimeBegin(), LocalTime.MIDNIGHT))
                .le(dto.getRegTimeEnd() != null, GameTencentAppOrder::getRegTime, dto.getRegTimeEnd() == null ? null : LocalDateTime.of(dto.getRegTimeEnd(), LocalTime.MAX))
                .eq(null != dto.getGameId(), GameTencentAppOrder::getGameId, dto.getGameId())
                .eq(null != dto.getAccountId(), GameTencentAppOrder::getAccountId, dto.getAccountId())
                .eq(StringUtils.isNotBlank(dto.getOrderNo()), GameTencentAppOrder::getOrderNo, dto.getOrderNo())
                .eq(null != dto.getBackStatus(), GameTencentAppOrder::getBackStatus, dto.getBackStatus())
                .eq(dto.getIsFirstOrder() != null, GameTencentAppOrder::getIsFirstOrder, dto.getIsFirstOrder())
                .eq(null != dto.getOrderStatus(), GameTencentAppOrder::getOrderStatus, dto.getOrderStatus())
                .like(StringUtils.isNotBlank(dto.getRoleName()), GameTencentAppOrder::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(GameTencentAppOrder::getCreateTime)
        );
        IPage<GameTencentAppOrderVO> 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<GameTencentAppOrderVO> toVOBatch(List<GameTencentAppOrder> logList) {
        if (CollectionUtils.isEmpty(logList)) {
            return Collections.emptyList();
        }
        List<GameTencentAppOrderSplitLogVO> orderSplitList = gameTencentAppOrderSplitLogService.listByOrderNo(
                logList.stream().map(GameTencentAppOrder::getOrderNo).collect(Collectors.toSet()));
        Set<String> agentKeys = logList.stream().map(GameTencentAppOrder::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 -> {
            GameTencentAppOrderVO vo = toVOSimple(log);
            if (StringUtils.isNotBlank(log.getAgentKey())) {
                AgentRpcVO agent = agentMap.get(log.getAgentKey());
                if (agent != null) {
                    vo.setAgentName(agent.getAgentName());
                }
            }
            List<GameTencentAppOrderSplitLogVO> splitList = orderSplitList.stream()
                    .filter(obj -> obj.getOrderNo().equals(log.getOrderNo()))
                    .collect(Collectors.toList());
            vo.setSplitOrderList(splitList);
            return vo;
        }).collect(Collectors.toList());
    }

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

    private GameTencentAppUser userLog(GameTencentAppOrder orderLog) {
        return gameTencentAppUserService.getOne(new LambdaQueryWrapper<GameTencentAppUser>()
                .eq(GameTencentAppUser::getGameId, orderLog.getGameId())
                .eq(GameTencentAppUser::getUserId, orderLog.getUserId())
                .eq(GameTencentAppUser::getAccountId, orderLog.getAccountId())
                .orderByDesc(GameTencentAppUser::getCreateTime)
                .last("limit 1")
        );
    }

    public static class TencentAppOrderBackPolicyCheck implements BackPolicyUtil.IBackPolicyCheck {
        private final IGameTencentAppOrderService gameTencentAppOrderService;
        private final IGameTencentAppOrderSplitLogService gameTencentAppOrderSplitLogService;
        private final GameBackPolicy gameBackPolicy;
        private final GameTencentAppUser userLog;
        private final GameTencentAppOrder orderLog;

        public TencentAppOrderBackPolicyCheck(IGameTencentAppOrderService gameTencentAppOrderService,
                                              IGameTencentAppOrderSplitLogService gameTencentAppOrderSplitLogService,
                                              GameTencentAppUser userLog, GameTencentAppOrder orderLog, GameBackPolicy gameBackPolicy) {
            this.gameTencentAppOrderService = gameTencentAppOrderService;
            this.gameTencentAppOrderSplitLogService = gameTencentAppOrderSplitLogService;
            this.gameBackPolicy = gameBackPolicy;
            this.userLog = userLog;
            this.orderLog = orderLog;
        }

        public Tuple2<Long, Long> backCountForUserWithSplitOrder(String userId) {
            Map<String, Long> orderMap = gameTencentAppOrderService.list(new LambdaQueryWrapper<GameTencentAppOrder>()
                    .select(GameTencentAppOrder::getOrderNo, GameTencentAppOrder::getBackMoney)
                    .eq(GameTencentAppOrder::getGameId, orderLog.getGameId())
                    .eq(GameTencentAppOrder::getAccountId, orderLog.getAccountId())
                    .eq(GameTencentAppOrder::getBackPolicyId, gameBackPolicy.getId())
                    .eq(GameTencentAppOrder::getOrderStatus, OrderStatusEnum.SUCCESS_PAY.getValue())
                    .eq(GameTencentAppOrder::getBackStatus, BackStatusEnum.SUCCESS.getBackStatus())
                    .eq(GameTencentAppOrder::getUserId, userId)
                    .ne(GameTencentAppOrder::getOrderNo, orderLog.getOrderNo())
            ).stream().collect(Collectors.toMap(GameTencentAppOrder::getOrderNo, GameTencentAppOrder::getBackMoney));
            if (MapUtils.isEmpty(orderMap)) {
                return Tuple2.with(0L, 0L);
            }
            Map<String, Integer> splitBackCountMap = gameTencentAppOrderSplitLogService.list(new LambdaQueryWrapper<GameTencentAppOrderSplitLog>()
                    .select(GameTencentAppOrderSplitLog::getOrderNo, GameTencentAppOrderSplitLog::getBackIndex, GameTencentAppOrderSplitLog::getBackCount)
                    .in(GameTencentAppOrderSplitLog::getOrderNo, orderMap.keySet())
            ).stream().collect(Collectors.toMap(GameTencentAppOrderSplitLog::getOrderNo, GameTencentAppOrderSplitLog::getBackCount, (obj1, obj2) -> obj1));
            long count = 0;
            long backMoney = 0;
            for (Map.Entry<String, Long> entry : orderMap.entrySet()) {
                Integer splitBackCount = splitBackCountMap.get(entry.getKey());
                backMoney += entry.getValue();
                if (splitBackCount != null) {
                    count += splitBackCount;
                } else {
                    count += 1;
                }
            }
            return Tuple2.with(count, backMoney);
        }

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

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

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

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