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

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
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.Tuple3;
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.entity.GameBackPolicy;
import com.zanxiang.game.back.serve.pojo.entity.GameTencentMiniGameOrder;
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.GameTencentMiniGameOrderVO;
import com.zanxiang.game.back.serve.service.IGameBackPolicyService;
import com.zanxiang.game.back.serve.service.IGameTencentMiniGameBackLogService;
import com.zanxiang.game.back.serve.service.IGameTencentMiniGameOrderService;
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.bean.BeanUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
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.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;

@Slf4j
@Service
public class GameTencentMiniGameOrderServiceImpl extends ServiceImpl<GameTencentMiniGameOrderMapper, GameTencentMiniGameOrder>
        implements IGameTencentMiniGameOrderService {

    @DubboReference(providedBy = AdvertisingTencentServer.SERVER_DUBBO_NAME)
    private IUserActionSetRpc userActionSetRpc;
    @DubboReference(providedBy = ErpServer.SERVER_DUBBO_NAME)
    private ISysUserRpc sysUserRpc;
    @Autowired
    private IGameTencentMiniGameBackLogService gameTencentMiniGameBackLogService;
    @Autowired
    private IGameBackPolicyService gameBackPolicyService;
    @DubboReference(providedBy = ServerInfo.SERVER_DUBBO_NAME)
    private IAgentRpc agentRpc;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean orderBack(GameTencentMiniGameOrder orderLog, boolean mustBack, Long backMoneyOfInput) {
        if (StringUtils.isBlank(orderLog.getClickId())) {
            // 没有点击 id（之后做监测链接，从监测链接里面找）
            return false;
        }
        boolean doBack = false;
        Long backMoney;
        String backMsg;
        if (mustBack) {
            doBack = true;
            backMoney = backMoneyOfInput;
            backMsg = "手动触发的回传";
        } else {
            if (!Objects.equals(orderLog.getOrderStatus(), OrderStatusEnum.SUCCESS_PAY.getValue())) {
                // 只要回传 支付行为
                return true;
            }
            GameBackPolicy gameBackPolicy = gameBackPolicyService.getById(orderLog.getBackPolicyId());
            // 此处是否是首单用 limit 2。因为在执行判断之前订单已入库，所以库里只有一笔才是首单
            Tuple3<Boolean, Long, String> backInfo = BackPolicyUtil.backOrder(orderLog.getOrderId(), gameBackPolicy, orderLog.getRechargeMoney(),
                    orderLog.getIsFirstOrder(), orderLog.getPayTime(), orderLog.getRegisterTime(), orderLog.getWechatOpenid(),
                    new BackPolicyUtil.IBackPolicyCheck() {
                        @Override
                        public long backCountForFixedRate(int numberOfRound, BackUnitEnum backUnit, Boolean firstPolicy) {
                            numberOfRound = numberOfRound - 1;
                            if (backUnit == BackUnitEnum.UNIT_ONCE) {
                                return 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())
                                        .orderByDesc(GameTencentMiniGameOrder::getCreateTime)
                                        .last("limit " + numberOfRound)
                                ).stream().filter(log -> log.getBackStatus().equals(BackStatusEnum.SUCCESS.getBackStatus())).count();
                            } else if (backUnit == BackUnitEnum.UNIT_DAY) {
                                return 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())
                                        .orderByDesc(GameTencentMiniGameOrder::getCreateTime)
                                        .last("limit " + numberOfRound)
                                ).stream().filter(log -> log.getBackStatus().equals(BackStatusEnum.SUCCESS.getBackStatus())).count();
                            } else if (backUnit == BackUnitEnum.UNIT_TIME_DAY) {
                                return 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())
                                        .orderByDesc(GameTencentMiniGameOrder::getCreateTime)
                                        .last("limit " + numberOfRound)
                                ).stream().filter(log -> log.getBackStatus().equals(BackStatusEnum.SUCCESS.getBackStatus())).count();
                            } else if (backUnit == BackUnitEnum.UNIT_TIME_2DAY) {
                                return 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())
                                        .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 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())
                                );
                            } else if (backUnit == BackUnitEnum.UNIT_DAY) {
                                return 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(recharge_time) = date(pay_time)")
                                        .apply(!firstPolicy, "date(recharge_time) != date(pay_time)")
                                        .ne(GameTencentMiniGameOrder::getOrderId, orderLog.getOrderId())
                                );
                            } else if (backUnit == BackUnitEnum.UNIT_TIME_DAY) {
                                return 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())
                                );
                            } else if (backUnit == BackUnitEnum.UNIT_TIME_2DAY) {
                                return 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())
                                );
                            } else {
                                throw new RuntimeException("不支持的回传单位[" + backUnit.getValue() + "]");
                            }
                        }

                        @Override
                        public long markUpOfFixedRate(int numberOfRound, Long markUpTime) {
                            numberOfRound = numberOfRound - 1;
                            return 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())
                                    .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 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())
                            );
                        }
                    });
            doBack = backInfo.first;
            backMoney = backInfo.second;
            backMsg = backInfo.third;
        }
        BackStatusEnum backStatus = BackStatusEnum.NO;
        orderLog.setBackMoney(backMoney);
        if (doBack) {
            backStatus = gameTencentMiniGameBackLogService.orderBack(orderLog);
        }
        return update(new LambdaUpdateWrapper<GameTencentMiniGameOrder>()
                .set(GameTencentMiniGameOrder::getBackStatus, backStatus.getBackStatus())
                .set(GameTencentMiniGameOrder::getBackMoney, backMoney)
                .set(GameTencentMiniGameOrder::getBackMsg, backMsg)
                .eq(GameTencentMiniGameOrder::getId, orderLog.getId())
        );
    }

    @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(List<Long> orderLogIds, Long backMoney) {
        listByIds(orderLogIds).stream()
                .filter(order -> !Objects.equals(order.getBackStatus(), BackStatusEnum.SUCCESS.getBackStatus()))
                .forEach(orderLog -> {
                    log.error("手动回传：{}-{}", orderLog.getId(), backMoney);
                    orderBack(orderLog, true, backMoney);
                });
        return true;
    }

    private List<GameTencentMiniGameOrderVO> toVOBatch(List<GameTencentMiniGameOrder> logList) {
        if (CollectionUtils.isEmpty(logList)) {
            return Collections.emptyList();
        }
        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());
                }
            }
            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;
    }
}
