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

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.zanxiang.game.back.base.pojo.dto.TencentOrderDTO;
import com.zanxiang.game.back.base.pojo.dto.TencentRoleRegisterRpcDTO;
import com.zanxiang.game.back.base.pojo.dto.TencentUserDTO;
import com.zanxiang.game.back.base.pojo.enums.OrderStatusEnum;
import com.zanxiang.game.back.base.rpc.ITencentMiniGameBackRpc;
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.entity.GameTencentMiniGameRoleRegister;
import com.zanxiang.game.back.serve.pojo.entity.GameTencentMiniGameUser;
import com.zanxiang.game.back.serve.pojo.enums.BackStatusEnum;
import com.zanxiang.game.back.serve.service.IGameBackPolicyService;
import com.zanxiang.game.back.serve.service.IGameTencentMiniGameOrderService;
import com.zanxiang.game.back.serve.service.IGameTencentMiniGameRoleRegisterService;
import com.zanxiang.game.back.serve.service.IGameTencentMiniGameUserService;
import com.zanxiang.module.util.JsonUtil;
import com.zanxiang.module.util.pojo.ResultVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;

import java.time.LocalDateTime;
import java.util.Objects;

@Slf4j
@DubboService
public class TencentMiniGameBackRpcImpl implements ITencentMiniGameBackRpc {

    @Autowired
    private IGameBackPolicyService gameBackPolicyService;

    @Autowired
    private IGameTencentMiniGameOrderService gameTencentMiniGameOrderService;

    @Autowired
    private IGameTencentMiniGameUserService gameTencentMiniGameUserService;

    @Autowired
    private IGameTencentMiniGameRoleRegisterService gameTencentMiniGameRoleRegisterService;

    @Override
    public ResultVO<Boolean> backOrder(TencentOrderDTO dto) {
        if (Objects.equals(OrderStatusEnum.SUCCESS_PAY.getValue(), dto.getOrderStatus())) {
            log.error("腾讯小游戏订单回传收到：{}。", JsonUtil.toString(dto));
        } else {
            log.error("腾讯小游戏订单回传收到：{}。订单未支付，直接过滤", JsonUtil.toString(dto));
            return ResultVO.ok(true);
        }
        boolean isFirstOrder = gameTencentMiniGameOrderService.getOne(new LambdaQueryWrapper<GameTencentMiniGameOrder>()
                .select(GameTencentMiniGameOrder::getOrderId)
                .eq(GameTencentMiniGameOrder::getGameId, dto.getGameId())
                .eq(GameTencentMiniGameOrder::getWechatAppId, dto.getWechatAppId())
                .eq(GameTencentMiniGameOrder::getAdAccountId, dto.getAdAccountId())
                .eq(GameTencentMiniGameOrder::getOrderStatus, OrderStatusEnum.SUCCESS_PAY.getValue())
                .eq(GameTencentMiniGameOrder::getWechatOpenid, dto.getWechatOpenid())
                .last("limit 1")
        ) == null;
        GameTencentMiniGameUser userLog = gameTencentMiniGameUserService.getOne(new LambdaQueryWrapper<GameTencentMiniGameUser>()
                .select(GameTencentMiniGameUser::getBackStatus, GameTencentMiniGameUser::getClickId)
                .eq(GameTencentMiniGameUser::getGameId, dto.getGameId())
                .eq(GameTencentMiniGameUser::getWechatAppId, dto.getWechatAppId())
                .eq(GameTencentMiniGameUser::getWechatOpenid, dto.getWechatOpenid())
                .eq(GameTencentMiniGameUser::getAdAccountId, dto.getAdAccountId())
                .orderByDesc(GameTencentMiniGameUser::getCreateTime)
                .last("limit 1")
        );
        GameTencentMiniGameOrder orderLog = GameTencentMiniGameOrder.builder()
                .adAccountId(dto.getAdAccountId())
                .gameId(dto.getGameId())
                .orderId(dto.getOrderId())
                .agentKey(dto.getChannel())
                .rechargeMoney(dto.getRechargeMoney())
                .rechargeTime(dto.getRechargeTime())
                .subscribeTime(dto.getSubscribeTime())
                .registerTime(dto.getRegisterTime())
                .wechatAppId(dto.getWechatAppId())
                .wechatOpenid(dto.getWechatOpenid())
                .orderStatus(dto.getOrderStatus())
                .payTime(dto.getPayTime())
                .createTime(LocalDateTime.now())
                .backStatus(BackStatusEnum.NO.getBackStatus())
                .backPolicyId(dto.getBackPolicyId())
                .clickId(userLog == null ? null : userLog.getClickId())
                .roleId(dto.getRoleId())
                .roleName(dto.getRoleName())
                .isFirstOrder(isFirstOrder)
                .build();
        gameTencentMiniGameOrderService.save(orderLog);
        if (userLog == null) {
            log.error("腾讯小游戏订单回传失败，找不到回传的用户 orderId: {}", orderLog.getOrderId());
            return ResultVO.fail("找不到回传用户");
        } else {
            return ResultVO.ok(gameTencentMiniGameOrderService.orderBack(orderLog));
        }
    }

    @Override
    public ResultVO<Boolean> backUser(TencentUserDTO dto) {
        log.error("腾讯小游戏用户回传收到：{}", JsonUtil.toString(dto));
        GameTencentMiniGameUser userLog = GameTencentMiniGameUser.builder()
                .adAccountId(dto.getAdAccountId())
                .gameId(dto.getGameId())
                .agentKey(dto.getChannel())
                .subscribeTime(dto.getSubscribeTime())
                .registerTime(dto.getRegisterTime())
                .wechatAppId(dto.getWechatAppId())
                .wechatOpenid(dto.getWechatOpenid())
                .backStatus(BackStatusEnum.NO.getBackStatus())
                .clickId(dto.getClickId())
                .createTime(LocalDateTime.now())
                .build();
        gameTencentMiniGameUserService.save(userLog);
        //查询回传策略
        GameBackPolicy gameBackPolicy = gameBackPolicyService.getById(dto.getBackPolicyId());
        //判断是否开启激活回传开关
        if (gameBackPolicy != null && Objects.equals(gameBackPolicy.getActiveBackSwitch(), Boolean.TRUE)) {
            //激活回传
            gameTencentMiniGameUserService.userBack(userLog);
        }
        return ResultVO.ok(Boolean.TRUE);
    }

    @Override
    public ResultVO<Boolean> backRoleRegister(TencentRoleRegisterRpcDTO dto) {
        log.error("腾讯小游戏创角回传收到：{}", JsonUtil.toString(dto));
        GameTencentMiniGameRoleRegister roleRegisterLog;
        GameTencentMiniGameRoleRegister oldRole = gameTencentMiniGameRoleRegisterService.getOne(new LambdaQueryWrapper<GameTencentMiniGameRoleRegister>()
                .eq(GameTencentMiniGameRoleRegister::getGameId, dto.getGameId())
                .eq(GameTencentMiniGameRoleRegister::getWechatAppId, dto.getWechatAppId())
                .eq(GameTencentMiniGameRoleRegister::getWechatOpenid, dto.getWechatOpenid())
                .eq(GameTencentMiniGameRoleRegister::getRoleId, dto.getRoleId())
                .last("limit 1")
        );
        if (oldRole != null) {
            roleRegisterLog = oldRole;
            if (dto.getRoleLevel() != null && (oldRole.getRoleLevel() == null || oldRole.getRoleLevel() < dto.getRoleLevel())) {
                gameTencentMiniGameRoleRegisterService.update(new LambdaUpdateWrapper<GameTencentMiniGameRoleRegister>()
                        .set(GameTencentMiniGameRoleRegister::getRoleLevel, dto.getRoleLevel())
                        .set(GameTencentMiniGameRoleRegister::getRoleName, dto.getRoleName())
                        .eq(GameTencentMiniGameRoleRegister::getId, oldRole.getId())
                );
            }
            // 创角已回传
            if (Objects.equals(oldRole.getBackStatus(), BackStatusEnum.SUCCESS.getBackStatus())) {
                //判断是否完成新手引导回传, 若没有, 则执行新手引导回传
                if (!Objects.equals(oldRole.getTutorialFinishBackStatus(), BackStatusEnum.SUCCESS.getBackStatus())) {
                    //回传策略
                    GameBackPolicy gameBackPolicy = oldRole.getBackPolicyId() == null ? null : gameBackPolicyService.getById(roleRegisterLog.getBackPolicyId());
                    //新手引导回传, 设置最新等级
                    oldRole.setRoleLevel(dto.getRoleLevel());
                    gameTencentMiniGameRoleRegisterService.tutorialFinishBack(oldRole, gameBackPolicy);
                }
                // 创角已回传, 不重复执行回传
                return ResultVO.ok(true);
            }
        } else {
            GameTencentMiniGameUser userLog = gameTencentMiniGameUserService.getOne(new LambdaQueryWrapper<GameTencentMiniGameUser>()
                    .select(GameTencentMiniGameUser::getBackStatus, GameTencentMiniGameUser::getClickId)
                    .eq(GameTencentMiniGameUser::getGameId, dto.getGameId())
                    .eq(GameTencentMiniGameUser::getWechatAppId, dto.getWechatAppId())
                    .eq(GameTencentMiniGameUser::getWechatOpenid, dto.getWechatOpenid())
                    .eq(GameTencentMiniGameUser::getAdAccountId, dto.getAdAccountId())
                    .orderByDesc(GameTencentMiniGameUser::getCreateTime)
                    .last("limit 1")
            );
            roleRegisterLog = GameTencentMiniGameRoleRegister.builder()
                    .backPolicyId(dto.getBackPolicyId())
                    .agentKey(dto.getChannel())
                    .gameId(dto.getGameId())
                    .adAccountId(dto.getAdAccountId())
                    .wechatAppId(dto.getWechatAppId())
                    .wechatOpenid(dto.getWechatOpenid())
                    .clickId(userLog == null ? null : userLog.getClickId())
                    .registerTime(dto.getRegisterTime())
                    .backStatus(BackStatusEnum.NO.getBackStatus())
                    .createTime(LocalDateTime.now())
                    .roleId(dto.getRoleId())
                    .roleName(dto.getRoleName())
                    .roleLevel(dto.getRoleLevel())
                    .build();
            gameTencentMiniGameRoleRegisterService.save(roleRegisterLog);
        }
        return ResultVO.ok(gameTencentMiniGameRoleRegisterService.roleRegisterBack(roleRegisterLog));
    }
}
