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.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.GameTencentMiniGameOrderMapper;
import com.zanxiang.game.back.serve.pojo.dto.GameTencentMiniGameOrderDTO;
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.BackTypeEnum;
import com.zanxiang.game.back.serve.pojo.enums.BackUnitEnum;
import com.zanxiang.game.back.serve.pojo.vo.GameTencentMiniGameOrderVO;
import com.zanxiang.game.back.serve.pojo.vo.GameTencentMiniOrderSplitLogVO;
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 GameTencentMiniGameOrderServiceImpl extends ServiceImpl<GameTencentMiniGameOrderMapper, GameTencentMiniGameOrder>
        implements IGameTencentMiniGameOrderService {

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

    @DubboReference(providedBy = ErpServer.SERVER_DUBBO_NAME)
    private ISysUserRpc sysUserRpc;

    @DubboReference(providedBy = AdvertisingTencentServer.SERVER_DUBBO_NAME)
    private IUserActionSetRpc userActionSetRpc;

    @Autowired
    private IGameTencentMiniGameBackLogService gameTencentMiniGameBackLogService;

    @Autowired
    private IGameTencentMiniGameUserService gameTencentMiniGameUserService;

    @Autowired
    private IGameBackPolicyService gameBackPolicyService;

    @Autowired
    private IGameTencentMiniGameOrderSplitLogService gameTencentMiniGameOrderSplitLogService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean orderBack(GameTencentMiniGameOrder orderLog) {
        if (StringUtils.isBlank(orderLog.getClickId())) {
            // 没有点击 id（之后做监测链接，从监测链接里面找）
            return false;
        }
        if (!Objects.equals(orderLog.getOrderStatus(), OrderStatusEnum.SUCCESS_PAY.getValue())) {
            // 只要回传 支付行为
            return true;
        }
        GameTencentMiniGameUser userLog = gameTencentMiniGameUserService.getOne(new LambdaQueryWrapper<GameTencentMiniGameUser>()
                .eq(GameTencentMiniGameUser::getGameId, orderLog.getGameId())
                .eq(GameTencentMiniGameUser::getWechatAppId, orderLog.getWechatAppId())
                .eq(GameTencentMiniGameUser::getWechatOpenid, orderLog.getWechatOpenid())
                .eq(GameTencentMiniGameUser::getAdAccountId, orderLog.getAdAccountId())
                .eq(GameTencentMiniGameUser::getBackType, BackTypeEnum.BACK_API.getBackType())
                .orderByDesc(GameTencentMiniGameUser::getCreateTime)
                .last("limit 1")
        );
        if (userLog == null) {
            return update(new LambdaUpdateWrapper<GameTencentMiniGameOrder>()
                    .set(GameTencentMiniGameOrder::getBackStatus, BackStatusEnum.FAILED.getBackStatus())
                    .set(GameTencentMiniGameOrder::getBackMoney, orderLog.getRechargeMoney())
                    .set(GameTencentMiniGameOrder::getBackMsg, "回传失败！找不到回传用户")
                    .eq(GameTencentMiniGameOrder::getId, orderLog.getId())
            );
        }

        GameBackPolicy gameBackPolicy = gameBackPolicyService.getById(orderLog.getBackPolicyId());
        // 此处是否是首单用 limit 2。因为在执行判断之前订单已入库，所以库里只有一笔才是首单
        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 TencentMiniGameOrderBackPolicyCheck(this, gameBackPolicy, userLog, orderLog, BackTypeEnum.BACK_API));
        boolean doBack = backInfo.first;
        Long backMoney = backInfo.second;
        String backMsg = backInfo.third;

        if (!doBack) {
            return update(new LambdaUpdateWrapper<GameTencentMiniGameOrder>()
                    .set(GameTencentMiniGameOrder::getBackStatus, BackStatusEnum.NO.getBackStatus())
                    .set(GameTencentMiniGameOrder::getBackMoney, backMoney)
                    .set(GameTencentMiniGameOrder::getBackMsg, backMsg)
                    .eq(GameTencentMiniGameOrder::getId, orderLog.getId())
            );
        }
        // 拆单
        if (CollectionUtils.isNotEmpty(backInfo.fourth)) {
            // 需要拆单
            List<GameTencentMiniGameOrderSplitLog> 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(GameTencentMiniGameOrderSplitLog.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())
                        .backType(BackTypeEnum.BACK_API.getBackType())
                        .build());
            }
            gameTencentMiniGameOrderSplitLogService.saveBatch(splitOrderLogList);
            return update(new LambdaUpdateWrapper<GameTencentMiniGameOrder>()
                    .set(GameTencentMiniGameOrder::getBackStatus, BackStatusEnum.NO.getBackStatus())
                    .set(GameTencentMiniGameOrder::getBackMoney, backInfo.second)
                    .set(GameTencentMiniGameOrder::getBackMsg, backMsg)
                    .eq(GameTencentMiniGameOrder::getId, orderLog.getId())
            );
        }

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

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean callback(GameTencentMiniGameOrder orderLog) {
        if (!Objects.equals(orderLog.getOrderStatus(), OrderStatusEnum.SUCCESS_PAY.getValue())) {
            // 只要回传 支付行为
            return true;
        }
        GameTencentMiniGameUser userLog = this.userLog(orderLog);
        if (userLog == null) {
            return update(new LambdaUpdateWrapper<GameTencentMiniGameOrder>()
                    .set(GameTencentMiniGameOrder::getBackStatus, BackStatusEnum.FAILED.getBackStatus())
                    .set(GameTencentMiniGameOrder::getBackMoney, orderLog.getRechargeMoney())
                    .set(GameTencentMiniGameOrder::getBackMsg, "回传失败！找不到回传用户")
                    .eq(GameTencentMiniGameOrder::getId, orderLog.getId())
            );
        }

        GameBackPolicy gameBackPolicy = gameBackPolicyService.getById(orderLog.getBackPolicyId());
        // 此处是否是首单用 limit 2。因为在执行判断之前订单已入库，所以库里只有一笔才是首单
        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 TencentMiniGameOrderBackPolicyCheck(this, gameBackPolicy, userLog, orderLog, BackTypeEnum.BACK_MEDIA_SDK));
        boolean doBack = backInfo.first;
        Long backMoney = backInfo.second;
        String backMsg = backInfo.third;

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

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

    private Tuple2<BackStatusEnum, String> doCallbackMediaSdk(GameTencentMiniGameOrder orderLog, LocalDateTime backTime, Long backMoney) {
        GameTencentMiniGameUser userLog = this.userLog(orderLog);
        String actionType = orderLog.getOrderStatus().equals(OrderStatusEnum.SUCCESS_PAY.getValue()) ?
                ActionTypeEnum.PURCHASE.getActionType() : ActionTypeEnum.COMPLETE_ORDER.getActionType();
        if (userLog == null) {
            gameTencentMiniGameBackLogService.save(GameTencentMiniGameBackLog.builder()
                    .gameId(orderLog.getGameId())
                    .adAccountId(orderLog.getAdAccountId())
                    .clickId(orderLog.getClickId())
                    .actionTime(backTime)
                    .wechatOpenid(orderLog.getWechatOpenid())
                    .wechatAppId(orderLog.getWechatAppId())
                    .actionType(actionType)
                    .amount(backMoney)
                    .orderId(orderLog.getOrderId())
                    .createTime(LocalDateTime.now())
                    .backStatus(BackStatusEnum.FAILED.getBackStatus())
                    .errMsg("找不到用户注册信息")
                    .backType(BackTypeEnum.BACK_MEDIA_SDK.getBackType())
                    .build());
            return Tuple2.with(BackStatusEnum.FAILED, "找不到用户注册信息");
        }
        BackStatusEnum backStatus = BackStatusEnum.SUCCESS;
        gameTencentMiniGameBackLogService.save(GameTencentMiniGameBackLog.builder()
                .gameId(orderLog.getGameId())
                .adAccountId(orderLog.getAdAccountId())
                .clickId(orderLog.getClickId())
                .actionTime(backTime)
                .wechatOpenid(orderLog.getWechatOpenid())
                .wechatAppId(orderLog.getWechatAppId())
                .actionType(actionType)
                .amount(backMoney)
                .orderId(orderLog.getOrderId())
                .createTime(LocalDateTime.now())
                .backStatus(backStatus.getBackStatus())
                .errMsg(null)
                .backType(BackTypeEnum.BACK_MEDIA_SDK.getBackType())
                .build());
        return Tuple2.with(backStatus, null);
    }

    private GameTencentMiniGameUser userLog(GameTencentMiniGameOrder orderLog) {
        return gameTencentMiniGameUserService.getOne(new LambdaQueryWrapper<GameTencentMiniGameUser>()
                .eq(GameTencentMiniGameUser::getGameId, orderLog.getGameId())
                .eq(GameTencentMiniGameUser::getWechatAppId, orderLog.getWechatAppId())
                .eq(GameTencentMiniGameUser::getWechatOpenid, orderLog.getWechatOpenid())
                .eq(GameTencentMiniGameUser::getAdAccountId, orderLog.getAdAccountId())
                .eq(GameTencentMiniGameUser::getBackType, BackTypeEnum.BACK_MEDIA_SDK.getBackType())
                .orderByDesc(GameTencentMiniGameUser::getCreateTime)
                .last("limit 1"));
    }

    @Override
    public IPage<GameTencentMiniGameOrderVO> listOfPage(GameTencentMiniGameOrderDTO dto) {
        IPage<GameTencentMiniGameOrder> page = page(dto.toPage(), new LambdaQueryWrapper<GameTencentMiniGameOrder>()
                .eq(StringUtils.isNotBlank(dto.getAgentKey()), GameTencentMiniGameOrder::getAgentKey, dto.getAgentKey())
                .ge(dto.getRegTimeBegin() != null, GameTencentMiniGameOrder::getRegisterTime, dto.getRegTimeBegin() == null ? null : LocalDateTime.of(dto.getRegTimeBegin(), LocalTime.MIDNIGHT))
                .le(dto.getRegTimeEnd() != null, GameTencentMiniGameOrder::getRegisterTime, dto.getRegTimeEnd() == null ? null : LocalDateTime.of(dto.getRegTimeEnd(), LocalTime.MAX))
                .eq(null != dto.getGameId(), GameTencentMiniGameOrder::getGameId, dto.getGameId())
                .eq(null != dto.getAdAccountId(), GameTencentMiniGameOrder::getAdAccountId, dto.getAdAccountId())
                .eq(StringUtils.isNotBlank(dto.getWechatAppId()), GameTencentMiniGameOrder::getWechatAppId, dto.getWechatAppId())
                .eq(StringUtils.isNotBlank(dto.getWechatOpenid()), GameTencentMiniGameOrder::getWechatOpenid, dto.getWechatOpenid())
                .eq(StringUtils.isNotBlank(dto.getOrderId()), GameTencentMiniGameOrder::getOrderId, dto.getOrderId())
                .eq(null != dto.getBackStatus(), GameTencentMiniGameOrder::getBackStatus, dto.getBackStatus())
                .eq(null != dto.getOrderStatus(), GameTencentMiniGameOrder::getOrderStatus, dto.getOrderStatus())
                .eq(dto.getIsFirstOrder() != null, GameTencentMiniGameOrder::getIsFirstOrder, dto.getIsFirstOrder())
                .like(StringUtils.isNotBlank(dto.getRoleName()), GameTencentMiniGameOrder::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(GameTencentMiniGameOrder::getCreateTime)
        );
        IPage<GameTencentMiniGameOrderVO> 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 doReport(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.getRechargeMoney().equals(total.get())) {
                            throw new BaseException("订单充值金额和回传金额对不上");
                        }
                        log.error("手动拆单回传：{}-{}", orderLog.getId(), StringUtils.join(dto.getSplitMoney(), ","));
                        List<GameTencentMiniGameOrderSplitLog> 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(GameTencentMiniGameOrderSplitLog.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()));
                        }
                        gameTencentMiniGameOrderSplitLogService.saveBatch(splitOrderLogList);
                        update(new LambdaUpdateWrapper<GameTencentMiniGameOrder>()
                                .set(GameTencentMiniGameOrder::getBackStatus, BackStatusEnum.NO.getBackStatus())
                                .set(GameTencentMiniGameOrder::getBackMoney, backMoneyTotal)
                                .set(GameTencentMiniGameOrder::getBackMsg, "手动触发回传（拆单回传）")
                                .eq(GameTencentMiniGameOrder::getId, orderLog.getId())
                        );
                    } else {
                        log.error("手动直接回传：{}-{}", orderLog.getId(), dto.getBackMoney());
                        long backMoney = NumberUtil.multiply100(dto.getBackMoney()).longValue();
                        Tuple2<BackStatusEnum, String> backResult = gameTencentMiniGameBackLogService.orderBack(orderLog, orderLog.getPayTime(), backMoney);
                        String backMsg = "手动触发回传！";
                        if (StringUtils.isNotBlank(backResult.second)) {
                            backMsg += ("回传失败：" + backResult.second);
                        }
                        update(new LambdaUpdateWrapper<GameTencentMiniGameOrder>()
                                .set(GameTencentMiniGameOrder::getBackStatus, backResult.first.getBackStatus())
                                .set(GameTencentMiniGameOrder::getBackMoney, backMoney)
                                .set(GameTencentMiniGameOrder::getBackMsg, backMsg)
                                .eq(GameTencentMiniGameOrder::getId, orderLog.getId())
                        );
                    }
                });
        return true;
    }

    private List<GameTencentMiniGameOrderVO> toVOBatch(List<GameTencentMiniGameOrder> logList) {
        if (CollectionUtils.isEmpty(logList)) {
            return Collections.emptyList();
        }
        List<GameTencentMiniOrderSplitLogVO> orderSplitList = gameTencentMiniGameOrderSplitLogService.listByOrderNo(logList.stream().map(GameTencentMiniGameOrder::getOrderId).collect(Collectors.toList()));
        Set<String> agentKeys = logList.stream().map(GameTencentMiniGameOrder::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 -> {
            GameTencentMiniGameOrderVO vo = toVOSimple(log);
            if (StringUtils.isNotBlank(log.getAgentKey())) {
                AgentRpcVO agent = agentMap.get(log.getAgentKey());
                if (agent != null) {
                    vo.setAgentName(agent.getAgentName());
                }
            }
            List<GameTencentMiniOrderSplitLogVO> splitList = orderSplitList.stream().filter(obj -> obj.getOrderNo().equals(log.getOrderId())).collect(Collectors.toList());
            vo.setSplitOrderList(splitList);
            return vo;
        }).collect(Collectors.toList());
    }

    private GameTencentMiniGameOrderVO toVOSimple(GameTencentMiniGameOrder orderLog) {
        GameTencentMiniGameOrderVO vo = BeanUtil.copy(orderLog, GameTencentMiniGameOrderVO.class);
        vo.setRegPayIntervalTime(OrderUtil.regPayIntervalTime(orderLog.getPayTime(), orderLog.getRegisterTime()));
        return vo;
    }

    public static class TencentMiniGameOrderBackPolicyCheck implements BackPolicyUtil.IBackPolicyCheck {
        private final IGameTencentMiniGameOrderService gameTencentMiniGameOrderService;
        private final GameBackPolicy gameBackPolicy;
        private final GameTencentMiniGameUser userLog;
        private final GameTencentMiniGameOrder orderLog;
        private final BackTypeEnum backTypeEnum;

        public TencentMiniGameOrderBackPolicyCheck(IGameTencentMiniGameOrderService gameTencentMiniGameOrderService,
                                                   GameBackPolicy gameBackPolicy, GameTencentMiniGameUser userLog,
                                                   GameTencentMiniGameOrder orderLog, BackTypeEnum backTypeEnum) {
            this.gameTencentMiniGameOrderService = gameTencentMiniGameOrderService;
            this.gameBackPolicy = gameBackPolicy;
            this.orderLog = orderLog;
            this.userLog = userLog;
            this.backTypeEnum = backTypeEnum;
        }

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

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

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

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