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

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zanxiang.game.module.base.pojo.dto.GameServerDTO;
import com.zanxiang.game.module.base.rpc.IGameServerRpc;
import com.zanxiang.game.module.manage.service.IGameServerService;
import com.zanxiang.game.module.manage.service.IGameService;
import com.zanxiang.game.module.manage.service.IGameSupperService;
import com.zanxiang.game.module.mybatis.entity.Game;
import com.zanxiang.game.module.mybatis.entity.GameServer;
import com.zanxiang.game.module.mybatis.entity.GameSupper;
import com.zanxiang.module.util.bean.BeanUtil;
import com.zanxiang.module.util.pojo.ResultVO;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;

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

/**
 * @author : lingfeng
 * @time : 2024-05-23
 * @description : 游戏区服接口
 */
@DubboService
public class GameServerRpcImpl implements IGameServerRpc {

    @Autowired
    private IGameSupperService gameSupperService;

    @Autowired
    private IGameService gameService;

    @Autowired
    private IGameServerService gameServerService;

    @Override
    public ResultVO<GameServerDTO> getAllServerList() {
        //超父游戏列表
        List<Long> supperGameIdList = gameSupperService.list(new LambdaQueryWrapper<GameSupper>()
                .select(GameSupper::getId)
        ).stream().map(GameSupper::getId).collect(Collectors.toList());
        //区服列表
        List<GameServerDTO.SuperGameServerBean> superGameServerList = new ArrayList<>();
        supperGameIdList.forEach(supperGameId -> {
            //查询超父对应的子游戏
            List<Long> gameIdList = gameService.list(new LambdaQueryWrapper<Game>()
                    .select(Game::getId)
                    .eq(Game::getSuperGameId, supperGameId)
            ).stream().map(Game::getId).collect(Collectors.toList());
            //超父对应的区服
            List<GameServerDTO.GameServerBean> gameServerBeanList = gameServerService.list(new LambdaQueryWrapper<GameServer>()
                    .eq(GameServer::getGameId, supperGameId)
                    .eq(GameServer::getIsSourceServer, Boolean.TRUE)
            ).stream().map(gameServer -> {
                GameServerDTO.GameServerBean gameServerBean = BeanUtil.copy(gameServer, GameServerDTO.GameServerBean.class);
                gameServerBean.setSuperGameId(supperGameId);
                return gameServerBean;
            }).collect(Collectors.toList());
            //添加到集合
            superGameServerList.add(GameServerDTO.SuperGameServerBean.builder()
                    .superGameId(supperGameId)
                    .gameIdList(gameIdList)
                    .sourceGameServerList(gameServerBeanList)
                    .build());
        });
        //返回
        return ResultVO.ok(GameServerDTO.builder().superGameServerList(superGameServerList).build());
    }
}
