package com.red.circle.wallet.inner.service.freight.impl;

import com.red.circle.other.inner.endpoint.user.user.UserProfileClient;
import com.red.circle.other.inner.model.dto.user.UserProfileDTO;
import com.red.circle.wallet.infra.database.rds.entity.freight.FreightBalanceRunningWater;
import com.red.circle.wallet.infra.database.rds.service.freight.FreightBalanceRunningWaterService;
import com.red.circle.wallet.inner.convertor.FreightBalanceRunningWaterInnerConvertor;
import com.red.circle.wallet.inner.model.dto.FreightBalanceRunningWaterDTO;
import com.red.circle.wallet.inner.service.freight.FreightBalanceRunningWaterClientService;
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 2023/12/26
 */
@Service
@RequiredArgsConstructor
public class FreightBalanceRunningWaterClientServiceImpl implements
    FreightBalanceRunningWaterClientService {

  private final FreightBalanceRunningWaterService freightBalanceRunningWaterService;
  private final FreightBalanceRunningWaterInnerConvertor freightBalanceRunningWaterInnerConvertor;
  private final UserProfileClient userProfileClient;

  @Override
  public List<FreightBalanceRunningWaterDTO> flowByUserId(Long userId, Long lastId) {
    List<FreightBalanceRunningWater> runningWaters = freightBalanceRunningWaterService.flowByUserId(userId, lastId);
    List<FreightBalanceRunningWaterDTO> runningWaterDTO = freightBalanceRunningWaterInnerConvertor.toListFreightBalanceRunningWaterDTO(runningWaters);

    Set<Long> acceptUserIdList = runningWaterDTO.stream().map(FreightBalanceRunningWaterDTO::getAcceptUserId).collect(Collectors.toSet());
    Map<Long, UserProfileDTO> userProfileDTOMap = userProfileClient.mapByUserIds(acceptUserIdList).getBody();

    runningWaterDTO.forEach(dto -> {
      UserProfileDTO profileDTO = userProfileDTOMap.get(dto.getAcceptUserId());
      if (profileDTO != null) {
        dto.setAccount(profileDTO.getAccount());
      }
    });
    return runningWaterDTO;
  }

  @Override
  public List<FreightBalanceRunningWaterDTO> flowBySellerId(Long sellerId, Long lastId) {
    return freightBalanceRunningWaterInnerConvertor.toListFreightBalanceRunningWaterDTO(
        freightBalanceRunningWaterService.flowBySellerId(sellerId, lastId)
    );
  }

  @Override
  public List<FreightBalanceRunningWaterDTO> flowByUserIdAndDate(Long userId, Long lastId,
      String currentDate) {
    return freightBalanceRunningWaterInnerConvertor.toListFreightBalanceRunningWaterDTO(
        freightBalanceRunningWaterService.flowByUserIdAndDate(userId, lastId, currentDate)
    );
  }

  @Override
  public void save(FreightBalanceRunningWaterDTO dto) {
    freightBalanceRunningWaterService.save(
        freightBalanceRunningWaterInnerConvertor.toFreightBalanceRunningWater(dto)
    );
  }
}
