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

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.room.LiveVoiceSessionEvent;
import com.red.circle.mq.rocket.business.streams.LiveVoiceSessionSink;
import com.red.circle.other.app.common.live.OnlineRoomCommon;
import com.red.circle.other.infra.database.mongo.entity.live.ActiveVoiceRoom;
import com.red.circle.other.infra.database.mongo.service.live.RoomProfileManagerService;
import com.red.circle.tool.core.date.DateFormatConstant;
import com.red.circle.tool.core.date.LocalDateTimeUtils;
import com.red.circle.tool.core.parse.DataTypeUtils;
import com.red.circle.tool.core.regex.RegexConstant;
import com.red.circle.tool.core.text.StringUtils;
import java.sql.Timestamp;
import java.util.Objects;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

/**
 * 语音房会话.
 *
 * @author pengliang on 2020/12/16
 */

@Slf4j
@RocketMqMessageListener(groupId = LiveVoiceSessionSink.INPUT, tag = LiveVoiceSessionSink.TAG)
@RequiredArgsConstructor
public class LiveVoiceSessionListener implements MessageListener {

  private final OnlineRoomCommon onlineRoomCommon;
  private final MessageEventProcess messageEventProcess;
  private final RoomProfileManagerService roomProfileManagerService;

  @Override
  public Action consume(ConsumerMessage message) {
    return messageEventProcess.consume(
        MessageEventProcessDescribe.builder()
            .logTag("语音房会话")
            .consumeMsgTimeoutMinute(10)
            .repeatConsumeMinute(1)
            .repeatConsumeTag("LiveVoiceSession")
            .checkConsumeTag(LiveVoiceSessionSink.TAG)
            .message(message)
            .build(),
        LiveVoiceSessionEvent.class,
        eventBody -> {
          log.info("[语言房会话] param:{}", eventBody);
          String sessionId = eventBody.getSessionId();
          if (!checkSessionIdPass(sessionId)) {
            return;
          }
          if (eventBody.checkLanguageHall()) {
            ActiveVoiceRoom activeVoiceRoom = onlineRoomCommon.addHeartbeatOnlineRoomProfileById(
                DataTypeUtils.toLong(sessionId));

            if (Objects.isNull(activeVoiceRoom)) {
              return;
            }

            roomProfileManagerService.updateRoomActiveTime(activeVoiceRoom.getId());

//        Timestamp nowTime = TimestampUtils.now();
//        Timestamp latestTime = Optional.ofNullable(statisticsRoomActiveService.getLatestActiveTime(
//                activeVoiceRoom.getId()))
//            .orElse(nowTime);

//        RoomActiveIndexDTO aggregation = giftGiveRunningWaterService.countRoomActiveIndex(
//            activeVoiceRoom.getId(),
//            latestTime, nowTime);
//
//        statisticsRoomActiveService.add(StatisticsRoomActive.builder()
//            .id(IdWorkerUtils.getIdStr())
//            .roomId(activeVoiceRoom.getId())
//            .userId(activeVoiceRoom.getUserId())
//            .sysOrigin(activeVoiceRoom.getSysOrigin())
//            .createTime(nowTime)
//            .roomActiveIndex(RoomActiveIndex.builder()
//                .onlineUserQuantity(activeVoiceRoom.getOnlineQuantity())
//                .sendGiftUserQuantity(Objects.nonNull(aggregation.getSendGiftUserQuantity())
//                    ? aggregation.getSendGiftUserQuantity() : 0L)
//                .sendGiftAmount(Objects.nonNull(aggregation.getSendGiftAmount())
//                    ? aggregation.getSendGiftAmount() : BigDecimal.ZERO)
//                .timeRange(getTimeRange(latestTime, nowTime))
//                .build())
//            .expiredTime(TimestampUtils.nowPlusDays(7))
//            .build());
          }
        });

  }

  private boolean checkSessionIdPass(String sessionId) {
    return StringUtils.isNotBlank(sessionId) && sessionId.matches(RegexConstant.NUMBER);
  }

  private String getTimeRange(Timestamp latestTime, Timestamp nowTime) {
    String startTime = getFormat(latestTime);
    String endTime = getFormat(nowTime);
    return startTime + "~" + endTime;
  }

  private String getFormat(Timestamp time) {
    return LocalDateTimeUtils.format(LocalDateTimeUtils.convert(time.getTime())
        , DateFormatConstant.yyyy_MM_dd_HH_mm_ss);
  }

}
