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

import com.red.circle.common.business.enums.GenderEnum;
import com.red.circle.console.app.convertor.UserAppConvertor;
import com.red.circle.console.app.dto.clienobject.user.UserCheckInLogCO;
import com.red.circle.framework.core.asserts.ResponseAssert;
import com.red.circle.framework.dto.PageResult;
import com.red.circle.other.inner.endpoint.material.props.PropsSourceClient;
import com.red.circle.other.inner.model.dto.material.PropsResourcesDTO;
import com.red.circle.tool.core.collection.CollectionUtils;
import com.red.circle.other.inner.model.cmd.user.UserCheckInLogQryCmd;
import com.red.circle.other.inner.model.dto.user.UserCheckInLogDTO;
import com.red.circle.other.inner.model.dto.user.UserProfileDTO;
import com.red.circle.other.inner.endpoint.user.user.UserExpandClient;
import com.red.circle.other.inner.endpoint.user.user.UserProfileClient;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 用户签到日志 服务实现类.
 * </p>
 *
 * @author houyong
 * @since 2020-06-08
 */

@Service
@RequiredArgsConstructor
public class UserCheckInLogServiceImpl implements UserCheckInLogService {

  private final UserExpandClient userExpandClient;
  private final UserAppConvertor userAppConvertor;
  private final PropsSourceClient propsSourceClient;
  private final UserProfileClient userProfileClient;

  @Override
  public PageResult<UserCheckInLogCO> getCheckInLog(UserCheckInLogQryCmd query) {

    PageResult<UserCheckInLogDTO> resultPage = ResponseAssert.requiredSuccess(
        userExpandClient.getCheckInLog(query));
    PageResult<UserCheckInLogCO> result = resultPage.convert(userAppConvertor::toUserCheckInLogCO);
    if (CollectionUtils.isEmpty(resultPage.getRecords())) {
      return result;
    }

    Map<Long, UserProfileDTO> userBaseInfoMap = ResponseAssert.requiredSuccess(userProfileClient
        .mapByUserIds(result
            .getRecords()
            .stream().map(UserCheckInLogCO::getUserId).collect(Collectors.toSet())));

    Map<Long, PropsResourcesDTO> roomPropsConfigMap = ResponseAssert.requiredSuccess(
        propsSourceClient.mapByIds(result.getRecords().stream().map(UserCheckInLogCO::getPropsId)
            .collect(Collectors.toSet())
        )
    );

    return result.convert(userCheckInLog -> {
      UserProfileDTO user = userBaseInfoMap.get(userCheckInLog.getUserId());
      if (Objects.nonNull(user)) {
        userCheckInLog.setUserNickname(user.getUserNickname());
        userCheckInLog.setUserSexName(GenderEnum.getGenderEnum(user.getUserSex()).getName());
      }
      PropsResourcesDTO roomPropsConfig = roomPropsConfigMap.get(userCheckInLog.getPropsId());
      if (Objects.nonNull(roomPropsConfig)) {
        userCheckInLog.setPropsSourceRecord(roomPropsConfig);
      }
      return userCheckInLog;
    });
  }
}
