package com.zanxiang.game.module.sdk.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.zanxiang.game.back.base.ServerInfo;
import com.zanxiang.game.back.base.pojo.dto.*;
import com.zanxiang.game.back.base.pojo.vo.OrderBackQueryRpcVO;
import com.zanxiang.game.back.base.rpc.*;
import com.zanxiang.game.module.base.pojo.enums.AccountTypeEnum;
import com.zanxiang.game.module.base.pojo.enums.GameCategoryEnum;
import com.zanxiang.game.module.mybatis.entity.*;
import com.zanxiang.game.module.sdk.constant.RedisKeyConstant;
import com.zanxiang.game.module.sdk.enums.CallBackTypeEnum;
import com.zanxiang.game.module.sdk.pojo.dto.PlatformOrderDTO;
import com.zanxiang.game.module.sdk.pojo.param.CallBackControlParam;
import com.zanxiang.game.module.sdk.pojo.param.UserData;
import com.zanxiang.game.module.sdk.service.*;
import com.zanxiang.module.redis.service.IDistributedLockComponent;
import com.zanxiang.module.util.JsonUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @author : lingfeng
 * @time : 2022-11-10
 * @description : 回传
 */
@Slf4j
@Service
public class CallBackServiceImpl implements ICallBackService {

    @DubboReference(providedBy = ServerInfo.SERVER_DUBBO_NAME)
    private ITencentAppApiBackRpc tencentAppApiBackRpc;

    @DubboReference(providedBy = ServerInfo.SERVER_DUBBO_NAME)
    private ITencentUserActionBackRpc tencentUserActionBackRpc;

    @DubboReference(providedBy = ServerInfo.SERVER_DUBBO_NAME)
    private ITencentMiniGameBackRpc tencentMiniGameBackRpc;

    @DubboReference(providedBy = ServerInfo.SERVER_DUBBO_NAME)
    private ITtMiniGameBackRpc ttMiniGameBackRpc;

    @DubboReference(providedBy = ServerInfo.SERVER_DUBBO_NAME)
    private ITtAppBackRpc ttAppBackRpc;

    @Autowired
    private IAgentService agentService;

    @Autowired
    private IGameService gameService;

    @Autowired
    private IGameAppletService gameAppletService;

    @Autowired
    private IUserService userService;

    @Autowired
    private IGameExtService gameExtService;

    @Autowired
    private IOrderService orderService;

    @Autowired
    private IGameBackLogService gameBackLogService;

    @Autowired
    private IDistributedLockComponent distributedLockComponent;

    @Autowired
    private IUserEventService userEventService;

    @Override
    public Map<String, Object> callBackJudge(CallBackControlParam param, UserData userData) {
        log.error("事件回传判断请求, param : {},  userData : {}", JsonUtil.toString(param), JsonUtil.toString(userData));
        Map<String, Object> resultMap = new HashMap<>(7);
        resultMap.put("callBackTypeEnum", param.getCallBackTypeEnum().getValue());
        resultMap.put("userId", userData.getUserId());
        resultMap.put("gameId", userData.getGameId());
        //事件类型枚举
        CallBackTypeEnum callBackTypeEnum = param.getCallBackTypeEnum();
        Game game = gameService.getById(userData.getGameId());
        //判断游戏状态, 对接上包过程中, 全量回传
        if (this.isUserEvent(game, userData.getUserId())) {
            resultMap.put("callBack", Boolean.TRUE);
            if (Objects.equals(callBackTypeEnum, CallBackTypeEnum.CALL_BACK_PAY_ORDER)) {
                PlatformOrderDTO platformOrderDTO = orderService.getByOrderId(param.getOrderId());
                if (platformOrderDTO != null) {
                    resultMap.put("amount", Collections.singletonList(platformOrderDTO.getAmount().intValue()));
                }
            }
            return resultMap;
        }
        //线程锁
        String lockKey = RedisKeyConstant.CALL_BACK_JUDGE_LOCK + callBackTypeEnum.getValue() + "_" + userData.getUserId();
        if (Objects.equals(callBackTypeEnum, CallBackTypeEnum.CALL_BACK_ACTIVATE)) {
            lockKey = lockKey + "_" + param.getRoleId();
        }
        if (Objects.equals(callBackTypeEnum, CallBackTypeEnum.CALL_BACK_PAY_ORDER)) {
            lockKey = lockKey + "_" + param.getOrderId();
        }
        //上锁
        if (!distributedLockComponent.doLock(lockKey, 0L, 1L, TimeUnit.MINUTES)) {
            log.error("重复请求触发线程锁, 直接返回false, lockKey : {}", lockKey);
            resultMap.put("callBack", Boolean.FALSE);
            return resultMap;
        }
        //查询玩家
        User user = userService.getById(userData.getUserId());
        //不存在渠道
        Agent agent = agentService.getById(user.getAgentId());
        if (agent == null) {
            resultMap.put("callBack", Boolean.FALSE);
            return resultMap;
        }
        //判断回传
        try {
            this.checkCallBack(user.getId(), agent, callBackTypeEnum, resultMap, param);
        } catch (Exception e) {
            log.error("事件回传判断, 出现异常, param : {},  userData : {}, e : {}", JsonUtil.toString(param),
                    JsonUtil.toString(userData), e.getMessage(), e);
            resultMap.put("callBack", Boolean.FALSE);
        }
        //返回结果
        return resultMap;
    }

    private boolean isUserEvent(Game game, Long userId) {
        if (Objects.equals(game.getStatus(), 2)) {
            return true;
        }
        //查询玩家
        User user = userService.getById(userId);
        //判断是否测试过事件用户
        return userEventService.count(new LambdaQueryWrapper<UserEvent>()
                .eq(UserEvent::getGameId, game.getId())
                .and(qw -> qw.eq(UserEvent::getUsername, user.getUsername())
                        .or().eq(UserEvent::getMobile, user.getMobile())
                )
        ) > 0;
    }

    private void checkCallBack(Long userId, Agent agent, CallBackTypeEnum callBackTypeEnum, Map<String, Object> resultMap,
                               CallBackControlParam param) {
        switch (callBackTypeEnum) {
            case CALL_BACK_REGISTER:
                // 注册
                TtAppUserBackQueryRpcDTO userTransform = this.transform(userId, agent);
                resultMap.put("callBack", ttAppBackRpc.userBackQuery(userTransform).getData());
                break;
            case CALL_BACK_LOGIN_IN:
                // 登录
                resultMap.put("callBack", Boolean.FALSE);
                break;
            case CALL_BACK_ACTIVATE:
                // 激活(创角)
                if (Strings.isBlank(param.getRoleId())) {
                    resultMap.put("callBack", Boolean.FALSE);
                    resultMap.put("roleId", "unknown");
                    break;
                }
                TtAppRoleRegisterBackQueryRpcDTO roleTransform = this.transform(userId, agent, param.getRoleId());
                resultMap.put("roleId", param.getRoleId());
                resultMap.put("callBack", ttAppBackRpc.roleRegisterBackQuery(roleTransform).getData());
                break;
            case CALL_BACK_PAY_ORDER:
                // 支付
                if (Strings.isBlank(param.getOrderId())) {
                    resultMap.put("callBack", Boolean.FALSE);
                    resultMap.put("orderId", "unknown");
                    break;
                }
                TtAppOrderBackQueryRpcDTO orderTransform = this.transform(userId, param.getOrderId(), agent);
                OrderBackQueryRpcVO orderBackQueryRpcVO = ttAppBackRpc.orderBackQuery(orderTransform).getData();
                resultMap.put("orderId", param.getOrderId());
                resultMap.put("callBack", orderBackQueryRpcVO.getDoBack());
                resultMap.put("backMsg", orderBackQueryRpcVO.getBackMsg());
                if (Objects.equals(orderBackQueryRpcVO.getDoBack(), Boolean.TRUE)) {
                    //传过来的金额是分, 换算成元, 存在小数直接舍弃
                    List<Long> backMoney = orderBackQueryRpcVO.getBackMoney()
                            .stream().map(money -> money / 100)
                            .collect(Collectors.toList());
                    resultMap.put("amount", backMoney);
                }
                break;
            default:
                // 处理未知类型
                resultMap.put("callBack", Boolean.FALSE);
        }
    }

    @Override
    public void userCallBack(User user, Map<String, String> urlParamMap) {
        //判断游戏是否开启广告回传, 未开启, 不回传
        GameExt gameExt = gameExtService.getByGameId(user.getGameId());
        if (!Objects.equals(gameExt.getAdCallBackSwitch(), Boolean.TRUE)) {
            return;
        }
        //自然量, 或者跳转链接参数不存在, 不做回传处理
        if (user.getAgentId() == 0L || CollectionUtils.isEmpty(urlParamMap)) {
            return;
        }
        //查询用户渠道信息
        Agent agent = agentService.getById(user.getAgentId());
        if (agent == null) {
            log.error("用户回传不存在渠道信息, userId : {}", user.getId());
            return;
        }
        //查询小游戏信息或者H5游戏相关公众号信息
        GameApplet gameApplet = gameAppletService.getOne(new LambdaQueryWrapper<GameApplet>()
                .eq(GameApplet::getGameId, agent.getGameId()));
        log.error("用户注册回传, userId : {}", user.getId());
        try {
            //腾讯H5回传
            if (Objects.equals(agent.getAccountType(), AccountTypeEnum.TENCENT_H5.getValue())) {
                TencentUserDTO tencentUserDTO = this.transform(user, agent, gameApplet);
                tencentUserActionBackRpc.backUser(tencentUserDTO);
                gameBackLogService.addLog(user.getId(), null, "腾讯H5用户回传提交", JsonUtil.toString(tencentUserDTO));
            }
            //腾讯小游戏回传
            if (Objects.equals(agent.getAccountType(), AccountTypeEnum.TENCENT_MINI_GAME.getValue())) {
                TencentUserDTO tencentUserDTO = this.transform(user, agent, gameApplet);
                //解析设置clickId
                Map<String, String> channelMap = agentService.channelTransform(user.getChannel());
                tencentUserDTO.setClickId(channelMap.get("gdt_vid"));
                tencentMiniGameBackRpc.backUser(tencentUserDTO);
                gameBackLogService.addLog(user.getId(), null, "腾讯小游戏用户回传提交", JsonUtil.toString(tencentUserDTO));
            }
            //腾讯APP私域
            if (Objects.equals(agent.getAccountType(), AccountTypeEnum.TENCENT_APP_API.getValue())) {
                TencentUserAppApiRpcDTO tencentUserAppApiRpcDTO = this.transform(user, agent, urlParamMap.get("callbackId"));
                tencentAppApiBackRpc.backUser(tencentUserAppApiRpcDTO);
                gameBackLogService.addLog(user.getId(), null, "腾讯APP私域用户回传提交", JsonUtil.toString(tencentUserAppApiRpcDTO));
            }
            //头条回传
            if (CollectionUtils.isNotEmpty(urlParamMap) && Objects.equals(agent.getAccountType(), AccountTypeEnum.BYTE.getValue())) {
                Game game = gameService.getById(agent.getGameId());
                //判断是微信小游戏
                if (Objects.equals(game.getCategory(), GameCategoryEnum.CATEGORY_WX_APPLET.getId())) {
                    TtUserActiveRpcDTO activeReportRpcDTO = this.transform(user, agent, gameApplet, urlParamMap);
                    ttMiniGameBackRpc.userActiveReport(activeReportRpcDTO);
                    gameBackLogService.addLog(user.getId(), null, "头条用户回传提交", JsonUtil.toString(activeReportRpcDTO));
                }
            }
            //头条APP直投回传
            if (CollectionUtils.isNotEmpty(urlParamMap) && Objects.equals(agent.getAccountType(), AccountTypeEnum.BYTE_APP.getValue())) {
                TtUserActiveAppRpcDTO ttUserActiveAppRpcDTO = this.transform(user, agent);
                ttAppBackRpc.userActiveReport(ttUserActiveAppRpcDTO);
                gameBackLogService.addLog(user.getId(), null, "头条APP用户回传提交", JsonUtil.toString(ttUserActiveAppRpcDTO));
            }
        } catch (Exception e) {
            log.error("用户回传异常, userId : {}, e : {}", user.getId(), e.getMessage());
        }
    }

    @Override
    public void roleCallBack(GameUserRole gameUserRole) {
        //判断游戏是否开启广告回传, 未开启, 不回传
        GameExt gameExt = gameExtService.getByGameId(gameUserRole.getGameId());
        if (!Objects.equals(gameExt.getAdCallBackSwitch(), Boolean.TRUE)) {
            return;
        }
        //用户信息
        User user = userService.getById(gameUserRole.getUserId());
        //用户渠道信息
        Agent agent = agentService.getAgentByChannel(user.getChannel());
        if (agent == null) {
            return;
        }
        //查询小游戏信息或者H5游戏相关公众号信息
        GameApplet gameApplet = gameAppletService.getOne(new LambdaQueryWrapper<GameApplet>()
                .eq(GameApplet::getGameId, agent.getGameId()));
        log.error("用户创角回传, userId : {}", user.getId());
        try {
            //腾讯H5回传
            if (Objects.equals(agent.getAccountType(), AccountTypeEnum.TENCENT_H5.getValue())) {
                TencentRoleRegisterRpcDTO tencentRoleRegisterRpcDTO = this.transform(user, agent, gameApplet, gameUserRole);
                tencentUserActionBackRpc.backRoleRegister(tencentRoleRegisterRpcDTO);
                gameBackLogService.addLog(user.getId(), gameUserRole.getRoleId(), "腾讯H5创角回传提交", JsonUtil.toString(tencentRoleRegisterRpcDTO));
            }
            //腾讯小游戏回传
            if (Objects.equals(agent.getAccountType(), AccountTypeEnum.TENCENT_MINI_GAME.getValue())) {
                TencentRoleRegisterRpcDTO tencentRoleRegisterRpcDTO = this.transform(user, agent, gameApplet, gameUserRole);
                tencentMiniGameBackRpc.backRoleRegister(tencentRoleRegisterRpcDTO);
                gameBackLogService.addLog(user.getId(), gameUserRole.getRoleId(), "腾讯小游戏创角回传提交", JsonUtil.toString(tencentRoleRegisterRpcDTO));
            }
            //腾讯APP私域
            if (Objects.equals(agent.getAccountType(), AccountTypeEnum.TENCENT_APP_API.getValue())) {
                TencentRoleRegisterAppApiRpcDTO tencentRoleRegisterAppApiRpcDTO = this.transform(gameUserRole, user, agent);
                tencentAppApiBackRpc.backRoleRegister(tencentRoleRegisterAppApiRpcDTO);
                gameBackLogService.addLog(user.getId(), null, "腾讯APP私域创角回传提交", JsonUtil.toString(tencentRoleRegisterAppApiRpcDTO));
            }
            //头条回传
            if (Objects.equals(agent.getAccountType(), AccountTypeEnum.BYTE.getValue())) {
                Game game = gameService.getById(agent.getGameId());
                //判断是微信小游戏
                if (Objects.equals(game.getCategory(), GameCategoryEnum.CATEGORY_WX_APPLET.getId())) {
                    TtRoleRegisterRpcDTO ttRoleRegisterRpcDTO = this.transform(user, agent, gameUserRole, gameApplet);
                    ttMiniGameBackRpc.roleRegisterReport(ttRoleRegisterRpcDTO);
                    gameBackLogService.addLog(user.getId(), gameUserRole.getRoleId(), "头条创角回传提交", JsonUtil.toString(ttRoleRegisterRpcDTO));
                }
            }
            //头条APP直投回传
            if (Objects.equals(agent.getAccountType(), AccountTypeEnum.BYTE_APP.getValue())) {
                TtRoleRegisterAppRpcDTO ttRoleRegisterAppRpcDTO = this.transform(user, agent, gameUserRole);
                ttAppBackRpc.roleRegisterReport(ttRoleRegisterAppRpcDTO);
                gameBackLogService.addLog(user.getId(), gameUserRole.getRoleId(), "头条APP创角回传提交", JsonUtil.toString(ttRoleRegisterAppRpcDTO));
            }
        } catch (Exception e) {
            log.error("创角回传异常, userId : {}, e : {}", user.getId(), e.getMessage());
        }
    }

    @Override
    public void orderCallBack(PlatformOrderDTO platformOrderDTO) {
        //判断游戏是否开启广告回传, 未开启, 不回传
        GameExt gameExt = gameExtService.getByGameId(platformOrderDTO.getGameId());
        if (!Objects.equals(gameExt.getAdCallBackSwitch(), Boolean.TRUE)) {
            return;
        }
        //用户信息
        User user = userService.getById(platformOrderDTO.getUserId());
        //用户渠道信息
        Agent agent = agentService.getAgentByChannel(user.getChannel());
        if (agent == null) {
            log.error("订单回传不存在渠道信息, orderId : {}", platformOrderDTO.getOrderId());
            return;
        }
        //查询小游戏信息或者H5游戏相关公众号信息
        GameApplet gameApplet = gameAppletService.getOne(new LambdaQueryWrapper<GameApplet>()
                .eq(GameApplet::getGameId, agent.getGameId()));
        log.error("用户订单回传, orderId : {}", platformOrderDTO.getOrderId());
        try {
            //腾讯H5回传
            if (Objects.equals(agent.getAccountType(), AccountTypeEnum.TENCENT_H5.getValue())) {
                TencentOrderDTO tencentOrderDTO = this.transform(platformOrderDTO, user, agent, gameApplet);
                tencentUserActionBackRpc.backOrder(tencentOrderDTO);
                gameBackLogService.addLog(user.getId(), platformOrderDTO.getOrderId(), "腾讯H5订单回传提交", JsonUtil.toString(tencentOrderDTO));
            }
            //腾讯小游戏回传
            if (Objects.equals(agent.getAccountType(), AccountTypeEnum.TENCENT_MINI_GAME.getValue())) {
                TencentOrderDTO tencentOrderDTO = this.transform(platformOrderDTO, user, agent, gameApplet);
                //解析设置clickId
                Map<String, String> channelMap = agentService.channelTransform(user.getChannel());
                tencentOrderDTO.setClickId(channelMap.get("gdt_vid"));
                tencentMiniGameBackRpc.backOrder(tencentOrderDTO);
                gameBackLogService.addLog(user.getId(), platformOrderDTO.getOrderId(), "腾讯小游戏订单回传提交", JsonUtil.toString(tencentOrderDTO));
            }
            //腾讯APP私域
            if (Objects.equals(agent.getAccountType(), AccountTypeEnum.TENCENT_APP_API.getValue())) {
                TencentOrderAppApiRpcDTO tencentOrderAppApiRpcDTO = this.transform(user, agent, platformOrderDTO);
                tencentAppApiBackRpc.backOrder(tencentOrderAppApiRpcDTO);
                gameBackLogService.addLog(user.getId(), platformOrderDTO.getOrderId(), "腾讯APP私域订单回传提交", JsonUtil.toString(tencentOrderAppApiRpcDTO));
            }
            //头条回传
            if (Objects.equals(agent.getAccountType(), AccountTypeEnum.BYTE.getValue())) {
                //判断游戏类型
                Game game = gameService.getById(agent.getGameId());
                if (Objects.equals(game.getCategory(), GameCategoryEnum.CATEGORY_WX_APPLET.getId())) {
                    TtOrderRpcDTO ttOrderRpcDTO = this.transform(platformOrderDTO, user.getOpenId(), agent, gameApplet, user.getCreateTime());
                    ttMiniGameBackRpc.orderReport(ttOrderRpcDTO);
                    gameBackLogService.addLog(user.getId(), platformOrderDTO.getOrderId(), "头条订单回传提交", JsonUtil.toString(ttOrderRpcDTO));
                }
            }
            //头条APP直投回传
            if (Objects.equals(agent.getAccountType(), AccountTypeEnum.BYTE_APP.getValue())) {
                TtOrderAppRpcDTO ttOrderAppRpcDTO = this.transform(platformOrderDTO, user, agent);
                ttAppBackRpc.orderReport(ttOrderAppRpcDTO);
                gameBackLogService.addLog(user.getId(), platformOrderDTO.getOrderId(), "头条APP订单回传提交", JsonUtil.toString(ttOrderAppRpcDTO));
            }
        } catch (Exception e) {
            log.error("订单回传异常, orderId : {}, e : {}", platformOrderDTO.getOrderId(), e.getMessage());
        }
    }

    private TencentRoleRegisterRpcDTO transform(User user, Agent agent, GameApplet gameApplet, GameUserRole gameUserRole) {
        return TencentRoleRegisterRpcDTO.builder()
                .backPolicyId(agent.getBackPolicyId())
                .gameId(agent.getGameId())
                .adAccountId(agent.getAccountId())
                .registerTime(gameUserRole.getCreateTime())
                .channel(agent.getAgentKey())
                .wechatOpenid(user.getOpenId())
                .wechatAppId(gameApplet == null ? null : gameApplet.getAppId())
                .userActionSetId(agent.getUserActionSetId())
                .roleId(gameUserRole.getRoleId())
                .roleName(gameUserRole.getRoleName())
                .roleLevel(gameUserRole.getRoleLevel())
                .build();
    }

    private TtRoleRegisterRpcDTO transform(User user, Agent agent, GameUserRole gameUserRole, GameApplet gameApplet) {
        return TtRoleRegisterRpcDTO.builder()
                .gameId(agent.getGameId())
                .backPolicyId(agent.getBackPolicyId())
                .accountReport(this.transform(agent))
                .wechatAppId(gameApplet == null ? null : gameApplet.getAppId())
                .wechatOpenId(user.getOpenId())
                .agentKey(agent.getAgentKey())
                .roleId(gameUserRole.getRoleId())
                .roleName(gameUserRole.getRoleName())
                .roleLevel(gameUserRole.getRoleLevel())
                .registerTime(gameUserRole.getCreateTime())
                .build();
    }

    private TencentUserDTO transform(User user, Agent agent, GameApplet gameApplet) {
        return TencentUserDTO.builder()
                .backPolicyId(agent.getBackPolicyId())
                .gameId(agent.getGameId())
                .adAccountId(agent.getAccountId())
                .registerTime(user.getCreateTime())
                .channel(agent.getAgentKey())
                .wechatOpenid(user.getOpenId())
                .wechatAppId(gameApplet == null ? null : gameApplet.getAppId())
                .userActionSetId(agent.getUserActionSetId())
                .build();
    }

    private TtUserActiveRpcDTO transform(User user, Agent agent, GameApplet gameApplet, Map<String, String> urlParamMap) {
        return TtUserActiveRpcDTO.builder()
                .gameId(agent.getGameId())
                .wechatAppId(gameApplet == null ? null : gameApplet.getAppId())
                .wechatOpenId(user.getOpenId())
                .accountReport(this.transform(agent))
                .agentKey(agent.getAgentKey())
                .backPolicyId(agent.getBackPolicyId())
                .activeTime(user.getCreateTime())
                .clueToken(urlParamMap.get("clue_token"))
                .projectId(Strings.isBlank(urlParamMap.get("project_id")) ? null : Long.valueOf(urlParamMap.get("project_id")))
                .promotionId(Strings.isBlank(urlParamMap.get("promotion_id")) ? null : Long.valueOf(urlParamMap.get("promotion_id")))
                .advertiserId(Strings.isBlank(urlParamMap.get("advertiser_id")) ? null : Long.valueOf(urlParamMap.get("advertiser_id")))
                .reqId(urlParamMap.get("req_id"))
                .build();
    }

    private TencentOrderDTO transform(PlatformOrderDTO platformOrderDTO, User user, Agent agent, GameApplet gameApplet) {
        return TencentOrderDTO.builder()
                .backPolicyId(agent.getBackPolicyId())
                .gameId(agent.getGameId())
                .adAccountId(agent.getAccountId())
                .registerTime(user.getCreateTime())
                .rechargeMoney(platformOrderDTO.getAmount().longValue() * 100)
                .rechargeTime(platformOrderDTO.getCreateTime())
                .orderId(platformOrderDTO.getOrderId())
                .channel(agent.getAgentKey())
                .wechatOpenid(user.getOpenId())
                .wechatAppId(gameApplet == null ? null : gameApplet.getAppId())
                .orderStatus(platformOrderDTO.getStatus())
                .payTime(platformOrderDTO.getPayTime())
                .userActionSetId(agent.getUserActionSetId())
                .roleId(platformOrderDTO.getRoleId())
                .roleName(platformOrderDTO.getRoleName())
                .build();
    }

    private TtOrderRpcDTO transform(PlatformOrderDTO platformOrderDTO, String openId, Agent agent, GameApplet gameApplet, LocalDateTime regTime) {
        return TtOrderRpcDTO.builder()
                .gameId(agent.getGameId())
                .accountReport(this.transform(agent))
                .wechatAppId(gameApplet == null ? null : gameApplet.getAppId())
                .wechatOpenId(openId)
                .orderId(platformOrderDTO.getOrderId())
                .agentKey(agent.getAgentKey())
                .backPolicyId(agent.getBackPolicyId())
                .rechargeMoney(platformOrderDTO.getAmount().longValue() * 100)
                .orderStatus(platformOrderDTO.getStatus())
                .createTime(platformOrderDTO.getCreateTime())
                .payTime(platformOrderDTO.getPayTime())
                .regTime(regTime)
                .roleId(platformOrderDTO.getRoleId())
                .roleName(platformOrderDTO.getRoleName())
                .build();
    }

    private TtAccountRpcDTO transform(Agent agent) {
        return TtAccountRpcDTO.builder()
                .accountId(agent.getAccountId())
                .reportToken(agent.getReportToken())
                .reportUrl(agent.getReportUrl())
                .build();
    }

    private TtUserActiveAppRpcDTO transform(User user, Agent agent) {
        return TtUserActiveAppRpcDTO.builder()
                .gameId(agent.getGameId())
                .accountReport(this.transform(agent))
                .agentKey(agent.getAgentKey())
                .activeTime(user.getCreateTime())
                .backPolicyId(agent.getBackPolicyId())
                .userId(user.getId().toString())
                .mac(user.getMac())
                .imei(user.getImei())
                .oaid(user.getOaid())
                .androidId(user.getAndroidId())
                .idfa(user.getIdfa())
                .caid(user.getCaid())
                .build();
    }

    private TtOrderAppRpcDTO transform(PlatformOrderDTO platformOrderDTO, User user, Agent agent) {
        return TtOrderAppRpcDTO.builder()
                .gameId(agent.getGameId())
                .accountReport(this.transform(agent))
                .userId(user.getId().toString())
                .orderId(platformOrderDTO.getOrderId())
                .agentKey(agent.getAgentKey())
                .backPolicyId(agent.getBackPolicyId())
                .rechargeMoney(platformOrderDTO.getAmount().multiply(new BigDecimal(100)).longValue())
                .orderStatus(platformOrderDTO.getStatus())
                .regTime(user.getCreateTime())
                .createTime(platformOrderDTO.getCreateTime())
                .payTime(platformOrderDTO.getPayTime())
                .roleId(platformOrderDTO.getRoleId())
                .roleName(platformOrderDTO.getRoleName())
                .mac(user.getMac())
                .imei(user.getImei())
                .oaid(user.getOaid())
                .androidId(user.getAndroidId())
                .idfa(user.getIdfa())
                .caid(user.getCaid())
                .build();
    }

    private TtRoleRegisterAppRpcDTO transform(User user, Agent agent, GameUserRole gameUserRole) {
        return TtRoleRegisterAppRpcDTO.builder()
                .gameId(agent.getGameId())
                .userId(user.getId().toString())
                .backPolicyId(agent.getBackPolicyId())
                .accountReport(this.transform(agent))
                .agentKey(agent.getAgentKey())
                .roleId(gameUserRole.getRoleId())
                .roleName(gameUserRole.getRoleName())
                .roleLevel(gameUserRole.getRoleLevel())
                .registerTime(gameUserRole.getCreateTime())
                .mac(user.getMac())
                .imei(user.getImei())
                .oaid(user.getOaid())
                .androidId(user.getAndroidId())
                .idfa(user.getIdfa())
                .caid(user.getCaid())
                .build();
    }

    private TtAppUserBackQueryRpcDTO transform(Long userId, Agent agent) {
        return TtAppUserBackQueryRpcDTO.builder()
                .gameId(agent.getGameId())
                .userId(userId.toString())
                .agentKey(agent.getAgentKey())
                .build();
    }

    private TtAppOrderBackQueryRpcDTO transform(Long userId, String orderId, Agent agent) {
        return TtAppOrderBackQueryRpcDTO.builder()
                .gameId(agent.getGameId())
                .userId(userId.toString())
                .orderId(orderId)
                .agentKey(agent.getAgentKey())
                .build();
    }

    private TtAppRoleRegisterBackQueryRpcDTO transform(Long userId, Agent agent, String roleId) {
        return TtAppRoleRegisterBackQueryRpcDTO.builder()
                .gameId(agent.getGameId())
                .userId(userId.toString())
                .agentKey(agent.getAgentKey())
                .roleId(roleId)
                .build();
    }

    private TencentUserAppApiRpcDTO transform(User user, Agent agent, String callbackId) {
        return TencentUserAppApiRpcDTO.builder()
                .backPolicyId(agent.getBackPolicyId())
                .userId(user.getId().toString())
                .gameId(agent.getGameId())
                .adAccountId(agent.getAccountId())
                .registerTime(user.getCreateTime())
                .channel(agent.getAgentKey())
                .mac(user.getMac())
                .imei(user.getImei())
                .oaid(user.getOaid())
                .androidId(user.getAndroidId())
                .idfa(user.getIdfa())
                .caid(user.getCaid())
                .regIp(user.getIp())
                .userActionSetId(agent.getUserActionSetId())
                .callbackId(Strings.isBlank(callbackId) ? null : Long.valueOf(callbackId))
                .build();
    }

    private TencentRoleRegisterAppApiRpcDTO transform(GameUserRole gameUserRole, User user, Agent agent) {
        return TencentRoleRegisterAppApiRpcDTO.builder()
                .backPolicyId(agent.getBackPolicyId())
                .userId(user.getId().toString())
                .gameId(agent.getGameId())
                .adAccountId(agent.getAccountId())
                .registerTime(user.getCreateTime())
                .channel(agent.getAgentKey())
                .roleId(gameUserRole.getRoleId())
                .roleName(gameUserRole.getRoleName())
                .roleLevel(gameUserRole.getRoleLevel())
                .mac(user.getMac())
                .imei(user.getImei())
                .oaid(user.getOaid())
                .androidId(user.getAndroidId())
                .idfa(user.getIdfa())
                .caid(user.getCaid())
                .build();
    }

    private TencentOrderAppApiRpcDTO transform(User user, Agent agent, PlatformOrderDTO platformOrderDTO) {
        return TencentOrderAppApiRpcDTO.builder()
                .backPolicyId(agent.getBackPolicyId())
                .userId(user.getId().toString())
                .gameId(agent.getGameId())
                .adAccountId(agent.getAccountId())
                .registerTime(user.getCreateTime())
                .rechargeMoney(platformOrderDTO.getAmount().multiply(new BigDecimal(100)).longValue())
                .rechargeTime(platformOrderDTO.getCreateTime())
                .orderId(platformOrderDTO.getOrderId())
                .channel(agent.getAgentKey())
                .orderStatus(platformOrderDTO.getStatus())
                .payTime(platformOrderDTO.getPayTime())
                .roleId(platformOrderDTO.getRoleId())
                .roleName(platformOrderDTO.getRoleName())
                .mac(user.getMac())
                .imei(user.getImei())
                .oaid(user.getOaid())
                .androidId(user.getAndroidId())
                .idfa(user.getIdfa())
                .caid(user.getCaid())
                .build();

    }
}
