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.GameTencentAppApiUserMapper;
import com.zanxiang.game.back.serve.pojo.entity.GameTencentAppApiBackLog;
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.ActionTypeEnum;
import com.zanxiang.game.back.serve.pojo.enums.BackStatusEnum;
import com.zanxiang.game.back.serve.service.IGameTencentAppApiBackLogService;
import com.zanxiang.game.back.serve.service.IGameTencentAppApiUserService;
import com.zanxiang.game.back.serve.service.IGameTencentAppCallbackService;
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 org.springframework.web.client.RestTemplate;

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

@Slf4j
@Service
public class GameTencentAppApiUserServiceImpl extends ServiceImpl<GameTencentAppApiUserMapper, GameTencentAppApiUser>
implements IGameTencentAppApiUserService {
    @Autowired
    private IGameTencentAppApiBackLogService gameTencentAppApiBackLogService;
    @Autowired
    private IGameTencentAppCallbackService gameTencentAppCallbackService;
    @Autowired
    private RestTemplate restTemplate;
    @DubboReference(providedBy = AdvertisingTencentServer.SERVER_DUBBO_NAME)
    private IUserActionSetV3Rpc userActionSetRpc;

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

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


    private Tuple2<BackStatusEnum, String> doCallback(GameTencentAppApiUser userLog, boolean mustBack) {
        boolean isBack = mustBack ? false : gameTencentAppApiBackLogService.count(new LambdaQueryWrapper<GameTencentAppApiBackLog>()
                .eq(GameTencentAppApiBackLog::getGameId, userLog.getGameId())
                .eq(GameTencentAppApiBackLog::getUserId, userLog.getUserId())
                .eq(GameTencentAppApiBackLog::getAdAccountId, userLog.getAdAccountId())
                .eq(GameTencentAppApiBackLog::getBackLog, "回传成功")
        ) > 0;
        if (isBack) {
            return Tuple2.with(BackStatusEnum.SUCCESS, "回传成功");
        }
        if (userLog.getCallbackId() == null || userLog.getCallbackId() < 1) {
            return Tuple2.with(BackStatusEnum.FAILED, "用户匹配不到广告");
        }

        GameTencentAppCallback callback = gameTencentAppCallbackService.getById(userLog.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(userLog.getAdAccountId())
                .userActionSetId(userLog.getUserActionSetId())
                .action(UserActionV3RpcDTO.builder()
                        .actionTime(userLog.getRegisterTime())
                        .actionType(ActionTypeEnum.ACTIVATE_APP.getActionType())
                        .userId(userId)
                        .trace(UserActionV3RpcDTO.TraceRpcDTO.builder()
                                .clickId(callback.getClickId())
                                .build())
                        .build())
                .build();

        GameTencentAppApiBackLog gameTencentBackLog = GameTencentAppApiBackLog.builder()
                .gameId(userLog.getGameId())
                .userId(userLog.getUserId())
                .adAccountId(userLog.getAdAccountId())
                .actionTime(userLog.getRegisterTime())
                .createTime(LocalDateTime.now())
                .actionType(ActionTypeEnum.REGISTER.getActionType())
                .imei(userLog.getImei())
                .oaid(userLog.getOaid())
                .androidId(userLog.getAndroidId())
                .idfa(userLog.getIdfa())
                .caid(userLog.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());
    }
}
