package com.zanxiang.game.module.manage.rpc.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zanxiang.game.module.base.pojo.enums.AccountTypeEnum;
import com.zanxiang.game.module.base.pojo.vo.AgentRpcVO;
import com.zanxiang.game.module.base.rpc.IAgentRpc;
import com.zanxiang.game.module.manage.pojo.dto.GameAppletDTO;
import com.zanxiang.game.module.manage.service.IAgentService;
import com.zanxiang.game.module.manage.service.IGameAppletService;
import com.zanxiang.game.module.mybatis.entity.Agent;
import com.zanxiang.module.util.bean.BeanUtil;
import com.zanxiang.module.util.pojo.ResultVO;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@DubboService
public class AgentRpcImpl implements IAgentRpc {

    @Autowired
    private IAgentService agentService;

    @Autowired
    private IGameAppletService gameAppletService;

    @Override
    public ResultVO<AgentRpcVO> getByByteAccountId(Long accountId) {
        return ResultVO.ok(toVOSimple(agentService.getOne(new LambdaQueryWrapper<Agent>()
                .eq(Agent::getAccountId, accountId)
                .in(Agent::getAccountType, Arrays.asList(AccountTypeEnum.BYTE.getValue(), AccountTypeEnum.BYTE_APP.getValue()))
        )));
    }

    @Override
    public ResultVO<AgentRpcVO> getByTencentAccountId(Long accountId) {
        return ResultVO.ok(toVOSimple(agentService.getOne(new LambdaQueryWrapper<Agent>()
                .eq(Agent::getAccountId, accountId)
                .in(Agent::getAccountType, Arrays.asList(AccountTypeEnum.TENCENT_H5.getValue(), AccountTypeEnum.TENCENT_MINI_GAME.getValue(), AccountTypeEnum.TENCENT_APP.getValue(), AccountTypeEnum.TENCENT_APP_API.getValue()))
        )));
    }

    @Override
    public ResultVO<List<AgentRpcVO>> getByAgentKeys(List<String> agentKeys) {
        if (CollectionUtils.isEmpty(agentKeys)) {
            return ResultVO.ok();
        }
        return ResultVO.ok(agentService.list(new LambdaQueryWrapper<Agent>()
                .in(Agent::getAgentKey, agentKeys)
        ).stream().map(this::toVOSimple).collect(Collectors.toList()));
    }

    private AgentRpcVO toVOSimple(Agent agent) {
        if (agent == null) {
            return null;
        }
        AgentRpcVO agentRpcVO = BeanUtil.copy(agent, AgentRpcVO.class);
        GameAppletDTO gameAppletDTO = gameAppletService.getByGameId(agent.getGameId());
        if (gameAppletDTO != null) {
            agentRpcVO.setAppId(gameAppletDTO.getAppId());
        }
        return agentRpcVO;
    }
}
