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

import com.red.circle.console.app.convertor.UserAppConvertor;
import com.red.circle.framework.core.asserts.ResponseAssert;
import com.red.circle.framework.dto.PageResult;
import com.red.circle.tool.core.collection.CollectionUtils;
import com.red.circle.other.inner.model.cmd.user.CpApplyQryCmd;
import com.red.circle.other.inner.model.dto.user.UserCpApplyDTO;
import com.red.circle.other.inner.model.dto.user.UserProfileDTO;
import com.red.circle.other.inner.endpoint.user.user.UserCpClient;
import com.red.circle.other.inner.endpoint.user.user.UserProfileClient;
import java.util.Collection;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

/**
 * @author pengliang on 2022/9/22
 */
@Service
@RequiredArgsConstructor
public class UserCpServiceImpl implements UserCpService {

  private final UserCpClient userCpClient;
  private final UserAppConvertor userAppConvertor;
  private final UserProfileClient userProfileClient;

  @Override
  public PageResult<UserCpApplyDTO> pageCpApply(CpApplyQryCmd query) {

    PageResult<UserCpApplyDTO> pageResult = ResponseAssert.requiredSuccess(
        userCpClient.pageCpApply(query));
    if (CollectionUtils.isEmpty(pageResult.getRecords())) {
      return pageResult;
    }

    Map<Long, UserProfileDTO> userProfileMap = ResponseAssert.requiredSuccess(
        userProfileClient.mapByUserIds(
            Stream.of(pageResult.getRecords().stream().map(UserCpApplyDTO::getSendApplyUserId)
                        .collect(Collectors.toList()),
                    pageResult.getRecords().stream().map(UserCpApplyDTO::getAcceptApplyUserId)
                        .collect(Collectors.toList())
                ).flatMap(Collection::stream)
                .collect(Collectors.toSet())));

    return pageResult.convert(cpApply -> {
      cpApply.setSendApplyUser(userProfileMap.get(cpApply.getSendApplyUserId()));
      cpApply.setAcceptApplyUser(userProfileMap.get(cpApply.getAcceptApplyUserId()));
      return cpApply;
    });
  }

}
