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

import com.red.circle.console.app.convertor.WalletAppConvertor;
import com.red.circle.console.app.dto.clienobject.user.UserFreightSellerCO;
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.dto.user.UserProfileDTO;
import com.red.circle.other.inner.endpoint.user.user.UserProfileClient;
import com.red.circle.wallet.inner.endpoint.freight.FreightGoldClient;
import com.red.circle.wallet.inner.model.cmd.UserFreightSellerPageQryCmd;
import com.red.circle.wallet.inner.model.dto.UserFreightSellerDTO;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 经销商卖家信息 服务实现类.
 * </p>
 *
 * @author zongpubin on 2023-07-14 15:28
 */
@Service
@RequiredArgsConstructor
public class UserFreightSellerServiceImpl implements
    UserFreightSellerService {

  private final UserProfileClient userProfileClient;
  private final FreightGoldClient freightGoldClient;
  private final WalletAppConvertor walletAppConvertor;

  @Override
  public PageResult<UserFreightSellerCO> pageFreightSeller(UserFreightSellerPageQryCmd query) {
    PageResult<UserFreightSellerDTO> userFreightSellerPage = ResponseAssert.requiredSuccess(
        freightGoldClient.pageFreightSeller(query));

    PageResult<UserFreightSellerCO> pageResult = userFreightSellerPage.convert(
        walletAppConvertor::toUserFreightSellerCO);

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

    Map<Long, UserProfileDTO> userBaseInfoMap = getUserBaseInfoMap(pageResult);

    return pageResult.convert(userFreightSeller -> {
      UserProfileDTO userBaseInfo = userBaseInfoMap.get(userFreightSeller.getUserId());
      userFreightSeller.setUserBaseInfo(userBaseInfo);
      return userFreightSeller;
    });
  }

  @Override
  public void removeFreightSeller(Long id) {
    freightGoldClient.removeFreightSeller(id);
  }

  private Map<Long, UserProfileDTO> getUserBaseInfoMap(
      PageResult<UserFreightSellerCO> userFreightSellerPage) {
    Set<Long> userIds = userFreightSellerPage.getRecords().stream()
        .map(UserFreightSellerCO::getUserId).collect(
            Collectors.toSet());
    return ResponseAssert.requiredSuccess(userProfileClient.mapByUserIds(userIds));
  }
}
