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.game.GameTurntableEvent;
import com.red.circle.mq.rocket.business.streams.GameTurntableAutoEndSink;
import com.red.circle.other.app.common.game.GameTurntableCommon;
import com.red.circle.other.infra.database.rds.entity.game.GameTurntableRecord;
import com.red.circle.other.infra.database.rds.service.game.GameTurntableRecordService;
import java.util.Objects;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

/**
 * 转盘游戏队列监控.
 *
 * @author pengliang on 2021/3/19
 */
@Slf4j
@RocketMqMessageListener(topic = "${rocketmq.topics.RC_DEFAULT_APP_DELAYED}", groupId = GameTurntableAutoEndSink.INPUT, tag = GameTurntableAutoEndSink.TAG)
@RequiredArgsConstructor
public class GameTurntableAutoEndListener implements MessageListener {

  private final MessageEventProcess messageEventProcess;
  private final GameTurntableCommon gameTurntableCommon;
  private final GameTurntableRecordService gameTurntableRecordService;

  @Override
  public Action consume(ConsumerMessage message) {

    return messageEventProcess.consume(
        MessageEventProcessDescribe.builder()
            .logTag("游戏转盘")
            .consumeMsgTimeoutMinute(60)
            .repeatConsumeMinute(60)
            .repeatConsumeTag("GameTurntableAutoEnd")
            .checkConsumeTag(GameTurntableAutoEndSink.TAG)
            .message(message)
            .build(),
        GameTurntableEvent.class,
        eventBody -> {
            log.warn("游戏转盘{}", eventBody);
          GameTurntableRecord game = gameTurntableRecordService.getByGameId(eventBody.getGameId());
          if (Objects.isNull(game)) {
            return;
          }
          if (eventBody.checkAutoEnd()) {
            gameTurntableCommon.reimburse(eventBody.getSysOrigin(), eventBody.getGameId());
          }

          if (eventBody.checkSendReward()) {
            gameTurntableCommon.sendReward(eventBody.getSysOrigin(), eventBody.getGameId());
          }

        });

  }


}
