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.github.sd4324530.jtuple.Tuple2;
import com.zanxiang.game.back.base.pojo.dto.TencentAppApiUserAgentQueryRpcDTO;
import com.zanxiang.game.back.base.pojo.dto.TencentOrderAppApiRpcDTO;
import com.zanxiang.game.back.base.pojo.dto.TencentRoleRegisterAppApiRpcDTO;
import com.zanxiang.game.back.base.pojo.dto.TencentUserAppApiRpcDTO;
import com.zanxiang.game.back.base.pojo.enums.OrderStatusEnum;
import com.zanxiang.game.back.base.rpc.ITencentAppApiBackRpc;
import com.zanxiang.game.back.serve.pojo.entity.GameTencentAppApiOrder;
import com.zanxiang.game.back.serve.pojo.entity.GameTencentAppApiRoleRegister;
import com.zanxiang.game.back.serve.pojo.entity.GameTencentAppApiUser;
import com.zanxiang.game.back.serve.pojo.entity.GameTencentAppCallback;
import com.zanxiang.game.back.serve.pojo.enums.BackStatusEnum;
import com.zanxiang.game.back.serve.service.IGameTencentAppApiOrderService;
import com.zanxiang.game.back.serve.service.IGameTencentAppApiRoleRegisterService;
import com.zanxiang.game.back.serve.service.IGameTencentAppApiUserService;
import com.zanxiang.game.back.serve.service.IGameTencentAppCallbackService;
import com.zanxiang.module.util.JsonUtil;
import com.zanxiang.module.util.pojo.ResultVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
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 TencentAppApiBackRpcImpl implements ITencentAppApiBackRpc {
    @Autowired
    private IGameTencentAppApiUserService gameTencentAppApiUserService;
    @Autowired
    private IGameTencentAppApiRoleRegisterService gameTencentAppApiRoleRegisterService;
    @Autowired
    private IGameTencentAppApiOrderService gameTencentAppApiOrderService;
    @Autowired
    private IGameTencentAppCallbackService gameTencentAppCallbackService;

    @Override
    public ResultVO<Boolean> backUser(TencentUserAppApiRpcDTO dto) {
        log.error("腾讯 APP-API 用户回传收到：{}", JsonUtil.toString(dto));
        if (StringUtils.isBlank(dto.getMac())) {
            dto.setMac("");
        }
        if (StringUtils.isBlank(dto.getImei())) {
            dto.setImei("");
        }
        if (StringUtils.isBlank(dto.getOaid())) {
            dto.setOaid("");
        }
        if (StringUtils.isBlank(dto.getAndroidId())) {
            dto.setAndroidId("");
        }
        if (StringUtils.isBlank(dto.getIdfa())) {
            dto.setIdfa("");
        }
        if (StringUtils.isBlank(dto.getCaid())) {
            dto.setCaid("");
        }
        if (StringUtils.isBlank(dto.getImei())
                && StringUtils.isBlank(dto.getOaid())
                && StringUtils.isBlank(dto.getAndroidId())
                && StringUtils.isBlank(dto.getIdfa())
                && StringUtils.isBlank(dto.getCaid())) {
            return ResultVO.fail("找不到用户唯一标识");
        }
        GameTencentAppApiUser userLog = GameTencentAppApiUser.builder()
                .userId(dto.getUserId())
                .adAccountId(dto.getAdAccountId())
                .gameId(dto.getGameId())
                .channel(dto.getChannel())
                .registerTime(dto.getRegisterTime())
                .ip(dto.getRegIp())
                .userActionSetId(dto.getUserActionSetId())
                .mac(dto.getMac())
                .imei(dto.getImei())
                .oaid(dto.getOaid())
                .androidId(dto.getAndroidId())
                .idfa(dto.getIdfa())
                .caid(dto.getCaid())
                .isBack(BackStatusEnum.NO.getBackStatus())
                .createTime(LocalDateTime.now())
                .build();

        if (dto.getCallbackId() != null) {
            userLog.setCallbackId(dto.getCallbackId());
        } else {
            GameTencentAppCallback callback = gameTencentAppCallbackService.getUserCallback(userLog.getGameId(), userLog.getImei(), userLog.getOaid(), userLog.getAndroidId(), userLog.getIdfa(), userLog.getCaid(), userLog.getIp(), userLog.getRegisterTime());
            userLog.setCallbackId(callback == null ? -1L : callback.getId());
        }
        gameTencentAppApiUserService.save(userLog);
        return ResultVO.ok(true);
        // 激活现在默认不回传了，等创角的时候一起回传
        // return ResultVO.ok(gameTencentAppApiUserService.userBack(gameTencentUser, false));
    }

    @Override
    public ResultVO<Boolean> backRoleRegister(TencentRoleRegisterAppApiRpcDTO dto) {
        log.error("腾讯 APP-API 创角回传收到：{}", JsonUtil.toString(dto));
        if (StringUtils.isBlank(dto.getMac())) {
            dto.setMac("");
        }
        if (StringUtils.isBlank(dto.getImei())) {
            dto.setImei("");
        }
        if (StringUtils.isBlank(dto.getOaid())) {
            dto.setOaid("");
        }
        if (StringUtils.isBlank(dto.getAndroidId())) {
            dto.setAndroidId("");
        }
        if (StringUtils.isBlank(dto.getIdfa())) {
            dto.setIdfa("");
        }
        if (StringUtils.isBlank(dto.getCaid())) {
            dto.setCaid("");
        }
        if (StringUtils.isBlank(dto.getImei())
                && StringUtils.isBlank(dto.getOaid())
                && StringUtils.isBlank(dto.getAndroidId())
                && StringUtils.isBlank(dto.getIdfa())
                && StringUtils.isBlank(dto.getCaid())) {
            return ResultVO.fail("找不到用户唯一标识");
        }
        GameTencentAppApiRoleRegister roleRegister;
        GameTencentAppApiRoleRegister oldRole = gameTencentAppApiRoleRegisterService.getOne(new LambdaQueryWrapper<GameTencentAppApiRoleRegister>()
                .eq(GameTencentAppApiRoleRegister::getGameId, dto.getGameId())
                .eq(GameTencentAppApiRoleRegister::getUserId, dto.getUserId())
                .eq(GameTencentAppApiRoleRegister::getRoleId, dto.getRoleId())
                .last("limit 1")
        );
        if (oldRole != null) {
            roleRegister = oldRole;
            if (dto.getRoleLevel() != null && (oldRole.getRoleLevel() == null || oldRole.getRoleLevel() < dto.getRoleLevel())) {
                gameTencentAppApiRoleRegisterService.update(new LambdaUpdateWrapper<GameTencentAppApiRoleRegister>()
                        .set(GameTencentAppApiRoleRegister::getRoleLevel, dto.getRoleLevel())
                        .set(GameTencentAppApiRoleRegister::getRoleName, dto.getRoleName())
                        .eq(GameTencentAppApiRoleRegister::getId, oldRole.getId())
                );
            }
            if (Objects.equals(oldRole.getIsBack(), BackStatusEnum.SUCCESS.getBackStatus())) {
                // 创角已回传。不重复传了
                return ResultVO.ok(true);
            }
        } else {
            roleRegister = GameTencentAppApiRoleRegister.builder()
                    .userId(dto.getUserId())
                    .backPolicyId(dto.getBackPolicyId())
                    .channel(dto.getChannel())
                    .gameId(dto.getGameId())
                    .adAccountId(dto.getAdAccountId())
                    .registerTime(dto.getRegisterTime())
                    .mac(dto.getMac())
                    .imei(dto.getImei())
                    .oaid(dto.getOaid())
                    .androidId(dto.getAndroidId())
                    .idfa(dto.getIdfa())
                    .caid(dto.getCaid())
                    .isBack(BackStatusEnum.NO.getBackStatus())
                    .createTime(LocalDateTime.now())
                    .roleId(dto.getRoleId())
                    .roleName(dto.getRoleName())
                    .roleLevel(dto.getRoleLevel())
                    .build();
            gameTencentAppApiRoleRegisterService.save(roleRegister);
        }
        return ResultVO.ok(gameTencentAppApiRoleRegisterService.roleRegisterBack(roleRegister));
    }

    @Override
    public ResultVO<Boolean> backOrder(TencentOrderAppApiRpcDTO dto) {
        if (Objects.equals(OrderStatusEnum.SUCCESS_PAY.getValue(), dto.getOrderStatus())) {
            log.error("腾讯 APP-API 订单回传收到：{}。", JsonUtil.toString(dto));
        } else {
            log.error("腾讯 APP-API 订单回传收到：{}。订单未支付，直接过滤", JsonUtil.toString(dto));
            return ResultVO.ok(true);
        }
        if (StringUtils.isBlank(dto.getMac())) {
            dto.setMac("");
        }
        if (StringUtils.isBlank(dto.getImei())) {
            dto.setImei("");
        }
        if (StringUtils.isBlank(dto.getOaid())) {
            dto.setOaid("");
        }
        if (StringUtils.isBlank(dto.getAndroidId())) {
            dto.setAndroidId("");
        }
        if (StringUtils.isBlank(dto.getIdfa())) {
            dto.setIdfa("");
        }
        if (StringUtils.isBlank(dto.getCaid())) {
            dto.setCaid("");
        }
        if (StringUtils.isBlank(dto.getImei())
                && StringUtils.isBlank(dto.getOaid())
                && StringUtils.isBlank(dto.getAndroidId())
                && StringUtils.isBlank(dto.getIdfa())
                && StringUtils.isBlank(dto.getCaid())) {
            return ResultVO.fail("找不到用户唯一标识");
        }
        boolean isFirstOrder = gameTencentAppApiOrderService.getOne(new LambdaQueryWrapper<GameTencentAppApiOrder>()
                .select(GameTencentAppApiOrder::getOrderId)
                .eq(GameTencentAppApiOrder::getGameId, dto.getGameId())
                .eq(GameTencentAppApiOrder::getAdAccountId, dto.getAdAccountId())
                .eq(GameTencentAppApiOrder::getUserId, dto.getUserId())
                .eq(GameTencentAppApiOrder::getOrderStatus, OrderStatusEnum.SUCCESS_PAY.getValue())
                .last("limit 1")
        ) == null;
        //订单保存
        GameTencentAppApiOrder gameTencentOrder = GameTencentAppApiOrder.builder()
                .userId(dto.getUserId())
                .adAccountId(dto.getAdAccountId())
                .gameId(dto.getGameId())
                .orderId(dto.getOrderId())
                .channel(dto.getChannel())
                .rechargeMoney(dto.getRechargeMoney())
                .rechargeTime(dto.getRechargeTime())
                .subscribeTime(dto.getSubscribeTime())
                .registerTime(dto.getRegisterTime())
                .mac(dto.getMac())
                .imei(dto.getImei())
                .oaid(dto.getOaid())
                .androidId(dto.getAndroidId())
                .idfa(dto.getIdfa())
                .caid(dto.getCaid())
                .orderStatus(dto.getOrderStatus())
                .payTime(dto.getPayTime())
                .createTime(LocalDateTime.now())
                .isBack(BackStatusEnum.NO.getBackStatus())
                .backPolicyId(dto.getBackPolicyId())
                .roleId(dto.getRoleId())
                .roleName(dto.getRoleName())
                .isFirstOrder(isFirstOrder)
                .build();
        gameTencentAppApiOrderService.save(gameTencentOrder);
        return ResultVO.ok(gameTencentAppApiOrderService.orderBack(gameTencentOrder));
    }

    @Override
    public ResultVO<Tuple2<String, Long>> queryUserAgentFromCallback(TencentAppApiUserAgentQueryRpcDTO dto) {
        GameTencentAppCallback callback = gameTencentAppCallbackService.getUserCallback(dto.getGameId(), dto.getImei(), dto.getOaid(), dto.getAndroidId(), dto.getIdfa(), dto.getCaid(), dto.getRegIp(), dto.getRegisterTime());
        if (callback == null) {
            return ResultVO.ok(null);
        }
        return ResultVO.ok(Tuple2.with(callback.getAgentKey(), callback.getId()));
    }
}
