package com.red.circle.other.app.listener.strategy;

import com.red.circle.external.inner.endpoint.message.NewsletterClient;
import com.red.circle.external.inner.model.cmd.message.NewsletterResultCmd;
import com.red.circle.external.inner.model.enums.message.NewsletterEvent;
import com.red.circle.mq.business.model.event.approval.ApprovalContent;
import com.red.circle.mq.business.model.event.approval.ApprovalEvent;
import com.red.circle.other.infra.database.rds.service.approval.ApprovalUserViolationHistoryService;
import com.red.circle.other.infra.database.rds.service.dynamic.DynamicMessageService;
import com.red.circle.tool.core.collection.CollectionUtils;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

/**
 * 动态-举报
 *
 * @author pengshigang on 2022/4/18
 */
@Component("DYNAMIC_REPORT_APPROVAL")
@RequiredArgsConstructor
public class ApprovalDynamicReportStrategy implements ApprovalStrategy {

  private final NewsletterClient newsletterClient;
  private final DynamicMessageService dynamicMessageService;
  private final ApprovalUserViolationHistoryService approvalUserViolationHistoryService;

  @Override
  public void doOperation(ApprovalEvent param) {

    if (Objects.isNull(param) || CollectionUtils.isEmpty(param.getWaitApprovalUser())) {
      return;
    }
    ApprovalContent dto = param.getWaitApprovalUser().get(0);
    if (Objects.isNull(dto)) {
      return;
    }
    Set<Long> userIds = getUserIds(param);

    //保存数据
    dynamicMessageService.saveBatch(dto.getContent(), dto.getContentId(), userIds, dto.getTags());

    //发送消息标记
    dynamicMessageService.mapByUserIdsByContentId(userIds)
        .forEach((key, list) -> newsletterClient
            .send(new NewsletterResultCmd()
                .setUserIds(List.of(key))
                .setEvent(NewsletterEvent.DYNAMIC_MESSAGE_QUANTITY)
                .setData(list.size())
            )
        );

  }

  private Set<Long> getUserIds(ApprovalEvent param) {
    return param.getWaitApprovalUser().parallelStream().map(ApprovalContent::getUserId).collect(
        Collectors.toSet());
  }

}
