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

import com.red.circle.console.app.dto.clienobject.team.RefundAnchorTrackRecordCO;
import com.red.circle.framework.dto.PageResult;
import com.red.circle.order.inner.endpoint.RoomRefundAnchorTrackRecordClient;
import com.red.circle.order.inner.model.cmd.RoomRefundAnchorTrackRecordPageQryCmd;
import com.red.circle.order.inner.model.dto.anchor.RoomRefundAnchorTrackRecordDTO;
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.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

/**
 * 主播系统日志服务 实现.
 *
 * @author pengliang on 2022/4/11
 */
@Service
@RequiredArgsConstructor
public class AnchorLogServiceImpl implements AnchorLogService {

  private final UserProfileClient userProfileClient;
  private final RoomRefundAnchorTrackRecordClient roomRefundAnchorTrackRecordClient;

  @Override
  public PageResult<RefundAnchorTrackRecordCO> opsPage(
      RoomRefundAnchorTrackRecordPageQryCmd cmd) {
    PageResult<RoomRefundAnchorTrackRecordDTO> resultResponse = roomRefundAnchorTrackRecordClient.opsPage(
        cmd).getBody();

    if (resultResponse.checkRecordsEmpty()) {
      return resultResponse.emptyRecords();
    }

    Set<Long> userIds = resultResponse.getRecords().stream()
        .map(row -> List.of(row.getAnchorUserId(), row.getRefunderUserId()))
        .flatMap(Collection::stream).collect(Collectors.toSet());

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

    return resultResponse.convert(trackRecord -> new RefundAnchorTrackRecordCO()
        .setTrackRecord(trackRecord)
        .setAnchorUserProfile(userProfileMap.get(trackRecord.getAnchorUserId()))
        .setRefundUserProfile(userProfileMap.get(trackRecord.getRefunderUserId())));
  }
}
