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

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.InviteUserQryCmd;
import com.red.circle.other.inner.model.dto.user.PageInviteUserRegisterDTO;
import com.red.circle.other.inner.model.dto.user.UserProfileDTO;
import com.red.circle.other.inner.endpoint.user.user.InviteUserClient;
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 lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 用户邀请用户注册信息表 服务实现类
 * </p>
 *
 * @author houyong
 * @since 2020-05-21
 */

@Slf4j
@RequiredArgsConstructor
@Service
public class UserInviteUserRegisterServiceImpl implements
    UserInviteUserRegisterService {

  private final InviteUserClient inviteUserClient;
  private final UserProfileClient userProfileClient;

  @Override
  public PageResult<PageInviteUserRegisterDTO> pageQuery(InviteUserQryCmd query) {

    PageResult<PageInviteUserRegisterDTO> resultPage = ResponseAssert.requiredSuccess(
        inviteUserClient.pageInviteUserRegisterAll(query));

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

    Set<Long> userIds = Stream.of(
            resultPage.getRecords().stream().map(PageInviteUserRegisterDTO::getInviteUserId)
                .filter(Objects::nonNull)
                .collect(Collectors.toSet()),
            resultPage.getRecords().stream().map(PageInviteUserRegisterDTO::getUserId)
                .filter(Objects::nonNull)
                .collect(Collectors.toSet()))
        .flatMap(Collection::stream)
        .collect(Collectors.toSet());

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

    return resultPage.convert(register -> new PageInviteUserRegisterDTO()
        .setId(register.getId())
        .setUserProfile(userProfileMap.get(register.getUserId()))
        .setBeUserProfile(userProfileMap.get(register.getInviteUserId()))
        .setDeviceId(register.getDeviceId())
        .setCommission(register.getCommission())
        .setCreateTime(register.getCreateTime())
    );
  }
}
