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

import com.red.circle.console.app.convertor.family.FamilyAppConvertor;
import com.red.circle.console.app.dto.clienobject.family.FamilyBaseInfoCO;
import com.red.circle.framework.core.asserts.ResponseAssert;
import com.red.circle.framework.dto.PageResult;
import com.red.circle.other.inner.endpoint.family.FamilyBaseInfoClient;
import com.red.circle.other.inner.model.cmd.famliy.FamilyBaseInfoQryCmd;
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 java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 家族客户端 服务实现类.
 * </p>
 *
 * @author pengshigang
 * @since 2022-06-30
 */
@Service
@RequiredArgsConstructor
public class FamilyBaseInfoServiceImpl implements FamilyBaseInfoService {

  private final UserProfileClient userProfileClient;
  private final FamilyAppConvertor familyAppConvertor;
  private final FamilyBaseInfoClient familyBaseInfoClient;


  /**
   * 分页.
   */
  @Override
  public PageResult<FamilyBaseInfoCO> pageData(
      FamilyBaseInfoQryCmd queryWhere) {

    PageResult<FamilyBaseInfoCO> infoPage = ResponseAssert.requiredSuccess(
            familyBaseInfoClient.pageData(queryWhere))
        .convert(familyAppConvertor::toFamilyBaseInfoCO);
    if (CollectionUtils.isEmpty(infoPage.getRecords())) {
      return infoPage;
    }
    Map<Long, UserProfileDTO> userMap = getUserMap(infoPage);

    return infoPage.convert(info -> {
      info.setUserBaseInfo(userMap.get(info.getCreateUser()));
      return info;
    });
  }

  /**
   * 解散家族.
   */
  @Override
  public void delFamily(Long familyId) {
    ResponseAssert.requiredSuccess(familyBaseInfoClient.delFamily(familyId));
  }

  private Map<Long, UserProfileDTO> getUserMap(PageResult<FamilyBaseInfoCO> infoPage) {
    return ResponseAssert.requiredSuccess(userProfileClient.mapByUserIds(getUserIds(infoPage)));
  }


  private Set<Long> getUserIds(PageResult<FamilyBaseInfoCO> infoPage) {
    return infoPage.getRecords().stream().map(FamilyBaseInfoCO::getCreateUser).collect(
        Collectors.toSet());
  }

}
