package com.red.circle.console.app.service.app.user;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.red.circle.framework.core.asserts.ResponseAssert;
import com.red.circle.framework.dto.PageResult;
import com.red.circle.other.inner.endpoint.live.RoomMikeTypeClient;
import com.red.circle.other.inner.model.cmd.live.MikeTypePropsQryCmd;
import com.red.circle.other.inner.model.dto.live.RoomMikeTypeDTO;
import com.red.circle.other.inner.model.dto.user.UserProfileDTO;
import com.red.circle.other.inner.endpoint.user.user.UserProfileClient;
import java.util.Collection;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 活动房间麦克风类型 服务实现类.
 * </p>
 *
 * @author zongpubin on 2023-04-21 10:55
 */
@RequiredArgsConstructor
@Service
public class RoomMikeTypeServiceImpl implements
    RoomMikeTypeService {

  private final UserProfileClient userProfileClient;
  private final RoomMikeTypeClient roomMikeTypeClient;

  @Override
  public PageResult<RoomMikeTypeDTO> pageRoomMikeTypeList(MikeTypePropsQryCmd query) {

    PageResult<RoomMikeTypeDTO> getPage = ResponseAssert.requiredSuccess(
        roomMikeTypeClient.pageRoomMikeTypeList(query));

    if (CollectionUtils.isEmpty(getPage.getRecords())) {
      return getPage;
    }

    Set<Long> userIds = Stream
        .of(getPage.getRecords().stream().map(RoomMikeTypeDTO::getUserId)
            .collect(Collectors.toSet())).flatMap(Collection::stream)
        .collect(Collectors.toSet());

    Map<Long, UserProfileDTO> userBaseInfoMap = ResponseAssert.requiredSuccess(
        userProfileClient.mapByUserIds(userIds));

    Map<String, String> mikeCoverMap = ResponseAssert.requiredSuccess(
        roomMikeTypeClient.getMikeTypeByType(
            query.getSysOrigin()));

    return getPage.convert(roomMikeType -> {
      roomMikeType.setMikeCover(mikeCoverMap.get(roomMikeType.getMikeType()));
      UserProfileDTO buyer = userBaseInfoMap.get(roomMikeType.getUserId());
      if (Objects.nonNull(buyer)) {
        roomMikeType.setBuyerNickname(buyer.getUserNickname());
        roomMikeType.setUserId(buyer.getId());
      }
      return roomMikeType;
    });
  }
}
