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.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.zanxiang.game.back.base.pojo.dto.TtOrderRpcDTO;
import com.zanxiang.game.back.base.pojo.dto.TtRoleRegisterRpcDTO;
import com.zanxiang.game.back.base.pojo.dto.TtUserActiveRpcDTO;
import com.zanxiang.game.back.base.pojo.enums.OrderStatusEnum;
import com.zanxiang.game.back.base.rpc.ITtMiniGameBackRpc;
import com.zanxiang.game.back.serve.pojo.entity.GameBackPolicy;
import com.zanxiang.game.back.serve.pojo.entity.GameOceanengineOrderLog;
import com.zanxiang.game.back.serve.pojo.entity.GameOceanengineRoleRegisterLog;
import com.zanxiang.game.back.serve.pojo.entity.GameOceanengineUserLog;
import com.zanxiang.game.back.serve.pojo.enums.BackStatusEnum;
import com.zanxiang.game.back.serve.service.IGameBackPolicyService;
import com.zanxiang.game.back.serve.service.IGameOceanengineOrderLogService;
import com.zanxiang.game.back.serve.service.IGameOceanengineRoleRegisterLogService;
import com.zanxiang.game.back.serve.service.IGameOceanengineUserLogService;
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.JsonUtil;
import com.zanxiang.module.util.pojo.ResultVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;

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

@Slf4j
@DubboService
public class TtMiniGameBackRpcImpl implements ITtMiniGameBackRpc {

    @Autowired
    private IGameBackPolicyService gameBackPolicyService;

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

    @Autowired
    private IGameOceanengineUserLogService gameOceanengineUserLogService;

    @Autowired
    private IGameOceanengineOrderLogService gameOceanengineOrderLogService;

    @Autowired
    private IGameOceanengineRoleRegisterLogService gameOceanengineRoleRegisterLogService;

    @Override
    public ResultVO<Boolean> userActiveReport(TtUserActiveRpcDTO dto) {
        log.error("头条小游戏用户回传收到：{}", JsonUtil.toString(dto));
        GameOceanengineUserLog userLog = GameOceanengineUserLog.builder()
                .backPolicyId(dto.getBackPolicyId())
                .appId(dto.getWechatAppId())
                .openId(dto.getWechatOpenId())
                .unionId(dto.getWechatUnionId())
                .gameId(dto.getGameId())
                .accountId(dto.getAccountReport().getAccountId())
                .accountReportToken(dto.getAccountReport().getReportToken())
                .accountReportUrl(dto.getAccountReport().getReportUrl())
                .agentKey(dto.getAgentKey())
                .clueToken(dto.getClueToken())
                .projectId(dto.getProjectId())
                .promotionId(dto.getPromotionId())
                .reqId(dto.getReqId())
                .activeTime(dto.getActiveTime())
                .backStatus(BackStatusEnum.NO.getBackStatus())
                .createTime(LocalDateTime.now())
                .build();
        gameOceanengineUserLogService.save(userLog);
        //查询策略信息
        GameBackPolicy gameBackPolicy = null;
        if (dto.getBackPolicyId() != null) {
            gameBackPolicy = gameBackPolicyService.getById(dto.getBackPolicyId());
        } else {
            List<AgentRpcVO> agentRpcVOList = agentRpc.getByAgentKeys(Collections.singletonList(dto.getAgentKey())).getData();
            if (CollectionUtils.isNotEmpty(agentRpcVOList)) {
                gameBackPolicy = gameBackPolicyService.getById(agentRpcVOList.get(0).getId());
            }
        }
        //判断是否开启激活回传开关
        if (gameBackPolicy != null && Objects.equals(gameBackPolicy.getActiveBackSwitch(), Boolean.TRUE)) {
            //激活回传
            gameOceanengineUserLogService.callback(userLog, Boolean.FALSE);
        }
        return ResultVO.ok(Boolean.TRUE);
    }

    @Override
    public ResultVO<Boolean> orderReport(TtOrderRpcDTO 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);
        }
        GameOceanengineOrderLog orderLog = GameOceanengineOrderLog.builder()
                .appId(dto.getWechatAppId())
                .openId(dto.getWechatOpenId())
                .unionId(dto.getWechatUnionId())
                .gameId(dto.getGameId())
                .backPolicyId(dto.getBackPolicyId())
                .accountId(dto.getAccountReport().getAccountId())
                .accountReportToken(dto.getAccountReport().getReportToken())
                .accountReportUrl(dto.getAccountReport().getReportUrl())
                .agentKey(dto.getAgentKey())
                .regTime(dto.getRegTime())
                .orderNo(dto.getOrderId())
                .amount(dto.getRechargeMoney())
                .orderStatus(dto.getOrderStatus())
                .createTime(dto.getCreateTime())
                .payTime(dto.getPayTime())
                .backStatus(BackStatusEnum.NO.getBackStatus())
                .roleId(dto.getRoleId())
                .roleName(dto.getRoleName())
                .build();
        boolean isFirstOrder = gameOceanengineOrderLogService.getOne(new LambdaQueryWrapper<GameOceanengineOrderLog>()
                .eq(GameOceanengineOrderLog::getGameId, orderLog.getGameId())
                .eq(GameOceanengineOrderLog::getAppId, orderLog.getAppId())
                .eq(GameOceanengineOrderLog::getAccountId, orderLog.getAccountId())
                .eq(GameOceanengineOrderLog::getOrderStatus, OrderStatusEnum.SUCCESS_PAY.getValue())
                .eq(GameOceanengineOrderLog::getOpenId, orderLog.getOpenId())
                .last("limit 1")
        ) == null;
        orderLog.setIsFirstOrder(isFirstOrder);
        gameOceanengineOrderLogService.save(orderLog);
        return ResultVO.ok(gameOceanengineOrderLogService.callback(orderLog));
    }

    @Override
    public ResultVO<Boolean> roleRegisterReport(TtRoleRegisterRpcDTO dto) {
        log.error("头条小游戏创角回传收到：{}", JsonUtil.toString(dto));
        GameOceanengineRoleRegisterLog roleRegisterLog;
        GameOceanengineRoleRegisterLog oldRole = gameOceanengineRoleRegisterLogService.getOne(new LambdaQueryWrapper<GameOceanengineRoleRegisterLog>()
                .eq(GameOceanengineRoleRegisterLog::getGameId, dto.getGameId())
                .eq(GameOceanengineRoleRegisterLog::getAppId, dto.getWechatAppId())
                .eq(GameOceanengineRoleRegisterLog::getOpenId, dto.getWechatOpenId())
                .eq(GameOceanengineRoleRegisterLog::getRoleId, dto.getRoleId())
                .last("limit 1")
        );
        if (oldRole != null) {
            roleRegisterLog = oldRole;
            if (dto.getRoleLevel() != null && (oldRole.getRoleLevel() == null || oldRole.getRoleLevel() < dto.getRoleLevel())) {
                gameOceanengineRoleRegisterLogService.update(new LambdaUpdateWrapper<GameOceanengineRoleRegisterLog>()
                        .set(GameOceanengineRoleRegisterLog::getRoleLevel, dto.getRoleLevel())
                        .set(GameOceanengineRoleRegisterLog::getRoleName, dto.getRoleName())
                        .eq(GameOceanengineRoleRegisterLog::getId, oldRole.getId())
                );
            }
            if (Objects.equals(oldRole.getBackStatus(), BackStatusEnum.SUCCESS.getBackStatus())) {
                // 创角已回传。不重复传了
                return ResultVO.ok(true);
            }
        } else  {
            roleRegisterLog = GameOceanengineRoleRegisterLog.builder()
                    .backPolicyId(dto.getBackPolicyId())
                    .appId(dto.getWechatAppId())
                    .openId(dto.getWechatOpenId())
                    .unionId(dto.getWechatUnionId())
                    .gameId(dto.getGameId())
                    .accountId(dto.getAccountReport().getAccountId())
                    .accountReportToken(dto.getAccountReport().getReportToken())
                    .accountReportUrl(dto.getAccountReport().getReportUrl())
                    .agentKey(dto.getAgentKey())
                    .roleId(dto.getRoleId())
                    .roleName(dto.getRoleName())
                    .roleLevel(dto.getRoleLevel())
                    .registerTime(dto.getRegisterTime())
                    .backStatus(BackStatusEnum.NO.getBackStatus())
                    .createTime(LocalDateTime.now())
                    .build();
            gameOceanengineRoleRegisterLogService.save(roleRegisterLog);
        }
        return ResultVO.ok(gameOceanengineRoleRegisterLogService.callback(roleRegisterLog));
    }
}
