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.LoginLogQryCmd;
import com.red.circle.other.inner.model.dto.user.UserLoginLoggerDTO;
import com.red.circle.other.inner.model.dto.user.UserProfileDTO;
import com.red.circle.other.inner.endpoint.user.user.UserLoginClient;
import com.red.circle.other.inner.endpoint.user.user.UserProfileClient;
import java.util.Map;
import java.util.stream.Collectors;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 用户登陆日志 服务实现类
 * </p>
 *
 * @author pengliang
 * @since 2019-11-08
 */

@Service
@RequiredArgsConstructor
public class UserLoginLoggerServiceImpl implements UserLoginLoggerService {

  private final UserLoginClient userLoginClient;
  private final UserProfileClient userProfileClient;

  @Override
  public PageResult<UserLoginLoggerDTO> pageUserLoginLoggerDTO(LoginLogQryCmd cmd) {
    PageResult<UserLoginLoggerDTO> userLoginLoggerPage = ResponseAssert.requiredSuccess(
        userLoginClient.pageLoginLogger(cmd));

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

    Map<Long, UserProfileDTO> userBaseInfoMap = ResponseAssert.requiredSuccess(
        userProfileClient.mapByUserIds(
            userLoginLoggerPage.getRecords().stream()
                .map(UserLoginLoggerDTO::getUserId).collect(Collectors.toSet())));
    return userLoginLoggerPage.convert(userLoginLogger ->
        userLoginLogger
            .setLoginTypeName(userLoginLogger.getLoginType())
            .setUserProfile(userBaseInfoMap.get(userLoginLogger.getUserId())));
  }
}
