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

import com.red.circle.common.business.core.enums.DynamicEventTypeEnum;
import com.red.circle.component.mq.MessageEventProcess;
import com.red.circle.component.mq.MessageEventProcessDescribe;
import com.red.circle.component.mq.config.RocketMqMessageListener;
import com.red.circle.component.mq.service.Action;
import com.red.circle.component.mq.service.ConsumerMessage;
import com.red.circle.component.mq.service.MessageListener;
import com.red.circle.mq.business.model.event.dynamic.DynamicEvent;
import com.red.circle.mq.rocket.business.streams.DynamicSink;
import com.red.circle.other.app.common.room.DynamicCommon;
import com.red.circle.other.infra.database.rds.entity.dynamic.DynamicContent;
import com.red.circle.other.infra.database.rds.service.dynamic.DynamicContentService;
import java.util.Objects;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

/**
 * 动态.
 *
 * @author pengshigang on 2022/4/13
 */
@Slf4j
@RocketMqMessageListener(groupId = DynamicSink.INPUT, tag = DynamicSink.TAG)
@RequiredArgsConstructor
public class RcDynamicListener implements MessageListener {

  private final DynamicCommon dynamicCommon;
  private final MessageEventProcess messageEventProcess;
  private final DynamicContentService dynamicContentService;

  @Override
  public Action consume(ConsumerMessage message) {
    return messageEventProcess.consume(
        MessageEventProcessDescribe.builder()
            .logTag("语音房会话")
            .consumeMsgTimeoutMinute(30)
            .repeatConsumeMinute(10)
            .repeatConsumeTag("Dynamic")
            .checkConsumeTag(DynamicSink.TAG)
            .message(message)
            .build(),
        DynamicEvent.class,
        this::business);
  }

  private void business(DynamicEvent dynamicEvent) {

    DynamicContent content = dynamicContentService.getById(dynamicEvent.getDynamicContentId());
    if (Objects.isNull(content) || content.getDel()) {
      return;
    }

    // 创建动态时给好友时间轴添加动态
    if (DynamicEventTypeEnum.CREATE.eq(dynamicEvent.getType())) {
      dynamicCommon.toFollowUserAddDynamic(dynamicEvent);
      return;
    }

    // 取消关注时，删除自己时间轴中对方的动态数据
    if (DynamicEventTypeEnum.UNFOLLOW.eq(dynamicEvent.getType())) {
      dynamicCommon.unfollow(dynamicEvent.getUserId(), dynamicEvent.getFollowUserId());
      return;
    }

    // 关注用户时，将对方时间轴中的动态数据存入自己列表
    if (DynamicEventTypeEnum.FOLLOW.eq(dynamicEvent.getType())) {
      dynamicCommon.follow(dynamicEvent.getUserId(), dynamicEvent.getFollowUserId());
      return;
    }

    // 删除自己动态内容
    if (DynamicEventTypeEnum.DELETE.eq(dynamicEvent.getType())) {
      dynamicCommon.deleteOwnDynamic(dynamicEvent.getDynamicContentId());
      return;
    }

    // 系统删除-违规
    if (DynamicEventTypeEnum.SYSTEM_DELETE.eq(dynamicEvent.getType())) {
      dynamicCommon.systemDeleteDynamic(dynamicEvent.getDynamicContentId());
    }

  }


}
