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.extension.service.impl.ServiceImpl;
import com.github.sd4324530.jtuple.Tuple2;
import com.zanxiang.advertising.tencent.base.AdvertisingTencentServer;
import com.zanxiang.advertising.tencent.base.pojo.dto.DataReportOfAccountIdV3RpcDTO;
import com.zanxiang.advertising.tencent.base.pojo.dto.UserActionV3RpcDTO;
import com.zanxiang.advertising.tencent.base.rpc.IUserActionSetV3Rpc;
import com.zanxiang.game.back.serve.dao.mapper.GameTencentAppApiRoleRegisterMapper;
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.service.*;
import com.zanxiang.module.util.pojo.ResultVO;
import lombok.extern.slf4j.Slf4j;
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.util.List;

@Slf4j
@Service
public class GameTencentAppApiRoleRegisterServiceImpl extends ServiceImpl<GameTencentAppApiRoleRegisterMapper, GameTencentAppApiRoleRegister>
        implements IGameTencentAppApiRoleRegisterService {

    @Autowired
    private IGameTencentAppApiBackLogService gameTencentAppApiBackLogService;
    @Autowired
    private IGameTencentAppApiUserService gameTencentAppApiUserService;
    @Autowired
    private IGameBackPolicyService gameBackPolicyService;
    @Autowired
    private IGameTencentAppCallbackService gameTencentAppCallbackService;
    @DubboReference(providedBy = AdvertisingTencentServer.SERVER_DUBBO_NAME)
    private IUserActionSetV3Rpc userActionSetRpc;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean roleRegisterBack(GameTencentAppApiRoleRegister roleRegisterLog) {
        Tuple2<BackStatusEnum, String> backStatus = doCallback(roleRegisterLog);
        return update(new LambdaUpdateWrapper<GameTencentAppApiRoleRegister>()
                .set(GameTencentAppApiRoleRegister::getIsBack, backStatus.first.getBackStatus())
                .set(GameTencentAppApiRoleRegister::getBackLog, backStatus.second)
                .eq(GameTencentAppApiRoleRegister::getId, roleRegisterLog.getId())
        );
    }

    @Override
    public boolean tencentUserReport(List<Long> ids) {
        listByIds(ids).forEach(roleRegisterLog -> {
            Tuple2<BackStatusEnum, String> backStatus = doCallback(roleRegisterLog);
            update(new LambdaUpdateWrapper<GameTencentAppApiRoleRegister>()
                    .set(GameTencentAppApiRoleRegister::getIsBack, backStatus.first.getBackStatus())
                    .set(GameTencentAppApiRoleRegister::getBackLog, backStatus.second)
                    .eq(GameTencentAppApiRoleRegister::getId, roleRegisterLog.getId())
            );
        });
        return true;
    }

    private Tuple2<BackStatusEnum, String> doCallback(GameTencentAppApiRoleRegister roleRegisterLog) {
        if (roleRegisterLog.getBackPolicyId() != null) {
            GameBackPolicy gameBackPolicy = gameBackPolicyService.getById(roleRegisterLog.getBackPolicyId());
            if (gameBackPolicy.getRoleLevelMin() != null && roleRegisterLog.getRoleLevel() != null
                    && roleRegisterLog.getRoleLevel() < gameBackPolicy.getRoleLevelMin()) {
                return Tuple2.with(BackStatusEnum.NO, "等级小于回传策略等级 " + gameBackPolicy.getRoleLevelMin() + "。不回传");
            }
        }

        GameTencentAppApiUser user = gameTencentAppApiUserService.getOne(new LambdaQueryWrapper<GameTencentAppApiUser>()
                .eq(GameTencentAppApiUser::getGameId, roleRegisterLog.getGameId())
                .eq(GameTencentAppApiUser::getUserId, roleRegisterLog.getUserId())
                .eq(GameTencentAppApiUser::getAdAccountId, roleRegisterLog.getAdAccountId())
                .orderByDesc(GameTencentAppApiUser::getCreateTime)
                .last("limit 1")
        );

        if (user != null) {
            if (user.getCallbackId() == null || user.getCallbackId() < 1) {
                return Tuple2.with(BackStatusEnum.FAILED, "用户匹配不到广告");
            }
            if (BackStatusEnum.NO.getBackStatus().equals(user.getIsBack())) {
                gameTencentAppApiUserService.userBack(user, true);
            } else {
                // 注册已回传，则默认认为创角也回传了
                return Tuple2.with(BackStatusEnum.NO, "用户第二+次创角不回传");
            }
        } else {
            return Tuple2.with(BackStatusEnum.FAILED, "找不到用户");
        }

        GameTencentAppCallback callback = gameTencentAppCallbackService.getById(user.getCallbackId());

        UserActionV3RpcDTO.UserIdRpcDTO userId = UserActionV3RpcDTO.UserIdRpcDTO.builder().build();
        if ("android".equalsIgnoreCase(callback.getDeviceOsType())) {
            if (StringUtils.isNotBlank(callback.getMuid())) {
                userId.setHashImei(callback.getMuid());
            }
            if (StringUtils.isNotBlank(callback.getHashOaid())) {
                userId.setHashOaid(callback.getHashOaid());
            }
            if (StringUtils.isNotBlank(callback.getHashAndroidId())) {
                userId.setHashAndroidId(callback.getHashAndroidId());
            }
        } else {
            if (StringUtils.isNotBlank(callback.getMuid())) {
                userId.setHashIdfa(callback.getMuid());
            }
        }
        DataReportOfAccountIdV3RpcDTO dataReportOfAccountIdRpcDTO = DataReportOfAccountIdV3RpcDTO.builder()
                .accountId(user.getAdAccountId())
                .userActionSetId(user.getUserActionSetId())
                .action(UserActionV3RpcDTO.builder()
                        .actionTime(roleRegisterLog.getRegisterTime())
                        .actionType(ActionTypeEnum.CREATE_ROLE.getActionType())
                        .userId(userId)
                        .trace(UserActionV3RpcDTO.TraceRpcDTO.builder()
                                .clickId(callback.getClickId())
                                .build())
                        .build())
                .build();

        GameTencentAppApiBackLog gameTencentBackLog = GameTencentAppApiBackLog.builder()
                .gameId(roleRegisterLog.getGameId())
                .userId(roleRegisterLog.getUserId())
                .adAccountId(roleRegisterLog.getAdAccountId())
                .actionTime(roleRegisterLog.getRegisterTime())
                .createTime(LocalDateTime.now())
                .actionType(ActionTypeEnum.CREATE_ROLE.getActionType())
                .imei(roleRegisterLog.getImei())
                .oaid(roleRegisterLog.getOaid())
                .androidId(roleRegisterLog.getAndroidId())
                .idfa(roleRegisterLog.getIdfa())
                .caid(roleRegisterLog.getCaid())
                .build();
        ResultVO<Boolean> result = userActionSetRpc.reportByAccountId(dataReportOfAccountIdRpcDTO);
        BackStatusEnum backStatus = BackStatusEnum.FAILED;
        if (result.isSuccess()) {
            backStatus = BackStatusEnum.SUCCESS;
            gameTencentBackLog.setBackLog("回传成功");
        } else {
            gameTencentBackLog.setBackLog(result.getMsg());
        }
        gameTencentAppApiBackLogService.save(gameTencentBackLog);
        return Tuple2.with(backStatus, gameTencentBackLog.getBackLog());
    }
}
