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

import com.red.circle.common.business.dto.cmd.IdLongCmd;
import com.red.circle.console.app.convertor.activity.ActivityHallFameAppConvertor;
import com.red.circle.console.app.dto.cmd.app.activity.ActivityHallFameConsoleQryCmd;
import com.red.circle.console.app.dto.cmd.app.activity.ActivityHallFameSaveOrUpdateCmd;
import com.red.circle.console.inner.error.ConsoleErrorCode;
import com.red.circle.framework.core.asserts.ResponseAssert;
import com.red.circle.framework.dto.PageResult;
import com.red.circle.other.inner.endpoint.activity.ActivityHallFameClient;
import com.red.circle.other.inner.model.dto.activity.ActivityHallFameDTO;
import com.red.circle.tool.core.collection.CollectionUtils;
import com.red.circle.tool.core.parse.DataTypeUtils;
import com.red.circle.tool.core.text.StringUtils;
import com.red.circle.other.inner.endpoint.user.user.UserProfileClient;
import java.util.Arrays;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

/**
 * 名人堂.
 *
 * @author pengliang on 2023/10/9
 */
@Service
@RequiredArgsConstructor
public class ActivityHallFameServiceImpl implements ActivityHallFameService {

  private final UserProfileClient userProfileClient;
  private final ActivityHallFameClient activityHallFameClient;
  private final ActivityHallFameAppConvertor activityHallFameAppConvertor;

  @Override
  public void saveOrUpdate(ActivityHallFameSaveOrUpdateCmd cmd) {
    ResponseAssert.isFalse(ConsoleErrorCode.EXCEED_SPECIFY_QUANTITY_ERROR,
        cmd.getAccounts().split(",").length > 2);

    Set<Long> userIds = Arrays.stream(cmd.getAccounts().split(","))
        .filter(StringUtils::isNotBlank)
        .map(StringUtils::trim)
        .map(DataTypeUtils::toLong)
        .collect(Collectors.toSet());

    ResponseAssert.isTrue(ConsoleErrorCode.ACCOUNT_DOES_NOT_EXIST,
        CollectionUtils.isNotEmpty(userIds));

    int userSize = ResponseAssert.requiredSuccess(userProfileClient.listByUserId(userIds)).size();

    ResponseAssert.isTrue(ConsoleErrorCode.ACCOUNT_DOES_NOT_EXIST,
        Objects.equals(userSize, userIds.size()));

    cmd.setAccounts(StringUtils.join(userIds, ","));
    activityHallFameClient.saveOrUpdate(activityHallFameAppConvertor.toActivityHallFameDTO(cmd));
  }

  @Override
  public void deleteById(IdLongCmd cmd) {
    activityHallFameClient.deleteById(cmd.getId());
  }

  @Override
  public PageResult<ActivityHallFameDTO> pageQuery(ActivityHallFameConsoleQryCmd qryCmd) {
    return ResponseAssert.requiredSuccess(activityHallFameClient.pageQuery(
        activityHallFameAppConvertor.toActivityHallFameQryCmd(qryCmd)));
  }

}
