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

import com.red.circle.framework.core.asserts.ResponseAssert;
import com.red.circle.framework.dto.PageResult;
import com.red.circle.other.inner.endpoint.dynamic.DynamicBlacklistClient;
import com.red.circle.other.inner.model.cmd.dynamic.DynamicBlacklistCmd;
import com.red.circle.other.inner.model.cmd.dynamic.DynamicBlacklistQryCmd;
import com.red.circle.other.inner.model.dto.dynamic.PageDynamicBlacklistDTO;
import com.red.circle.other.inner.asserts.user.UserErrorCode;
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.stream.Collectors;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 动态-黑名单 服务实现类.
 * </p>
 *
 * @author pengshigang
 * @since 2022-06-30
 */
@Service
@RequiredArgsConstructor
public class DynamicBlacklistServiceImpl implements DynamicBlacklistService {

  private final UserProfileClient userProfileClient;
  private final DynamicBlacklistClient dynamicBlacklistClient;


  @Override
  public void deleteByUserId(Long userId) {
    ResponseAssert.requiredSuccess(dynamicBlacklistClient.deleteByUserId(userId));
  }

  @Override
  public void add(DynamicBlacklistCmd param) {

    UserProfileDTO userProfile = ResponseAssert.requiredSuccess(userProfileClient
        .getByAccount(param.getSysOrigin(), param.getAccount()));

    ResponseAssert.notNull(UserErrorCode.ACCOUNT_NOT_MATCH, userProfile);
    param.setUserId(userProfile.getId());
    ResponseAssert.requiredSuccess(dynamicBlacklistClient.add(param));
  }

  @Override
  public PageResult<UserProfileDTO> page(DynamicBlacklistQryCmd query) {
    PageResult<PageDynamicBlacklistDTO> pageResult = ResponseAssert.requiredSuccess(
        dynamicBlacklistClient.pageDynamicBlacklist(query));
    Map<Long, UserProfileDTO> userMap = ResponseAssert.requiredSuccess(
        userProfileClient.mapByUserIds(
            pageResult.getRecords().stream().map(PageDynamicBlacklistDTO::getUserId)
                .collect(Collectors.toSet())));

    return pageResult.convert(blacklist -> {
      UserProfileDTO userProfile = userMap.get(blacklist.getUserId());
      userProfile.setCreateTime(blacklist.getCreateTime());
      return userProfile;
    });

  }

}
