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

import com.red.circle.common.business.core.enums.ReceiptType;
import com.red.circle.common.business.core.enums.SysOriginPlatformEnum;
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.framework.web.props.EnvProperties;
import com.red.circle.mq.business.model.event.wallet.WalletReceiptSyncEvent;
import com.red.circle.mq.rocket.business.streams.WalletAssetGoldSyncSinkV2;
import com.red.circle.other.inner.endpoint.activity.TemporaryActivityCountClient;
import com.red.circle.other.inner.model.cmd.activity.TemporaryActivityCountCmd;
import com.red.circle.tool.core.date.DateUtils;
import com.red.circle.tool.core.http.RcHttpClient;
import com.red.circle.wallet.domain.wallet.WalletBizType;
import com.red.circle.wallet.infra.database.cache.service.WalletGoldCacheService;
import com.red.circle.wallet.infra.database.rds.service.WalletGoldAssetRecordService;
import com.red.circle.wallet.infra.tool.WalletAssetSyncTool;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import java.util.Objects;

/**
 * 钱包资产同步.
 *
 * @author pengliang on 2023/7/2
 */
@Slf4j
@RequiredArgsConstructor
@RocketMqMessageListener(groupId = WalletAssetGoldSyncSinkV2.INPUT, tag = WalletAssetGoldSyncSinkV2.TAG)
public class WalletAssetSyncListenerV2 implements MessageListener {

  private final RcHttpClient rcHttpClient = RcHttpClient.newRcHttpClient();
  private final EnvProperties envProperties;
  private final MessageEventProcess messageEventProcess;
  private final WalletAssetSyncTool walletAssetSyncTool;
  private final WalletGoldCacheService walletGoldCacheService;
  private final WalletGoldAssetRecordService walletGoldAssetRecordService;
  private final TemporaryActivityCountClient temporaryActivityCountClient;

  @Override
  public Action consume(ConsumerMessage message) {
    long startTime = System.currentTimeMillis();
    Action action = messageEventProcess.consume(
        MessageEventProcessDescribe.builder()
            .logTag("钱包资产同步")
            // .consumeMsgTimeoutMinute(60)
            .repeatConsumeMinute(3)
            .repeatConsumeTag("WalletAssetSync")
            .checkConsumeTag(WalletAssetGoldSyncSinkV2.TAG)
            .message(message)
            .build(),
        WalletReceiptSyncEvent.class,
        receipt -> {
          if (Objects.equals(WalletBizType.toEnum(receipt.getBizType()), WalletBizType.GOLD)) {

            // 移除用户流水缓存
            walletGoldCacheService.removeFirstLatestGoldAssetRecord(receipt.getSysOrigin(),
                receipt.getUserId());

            // 同步流水余额
            if (walletGoldAssetRecordService.existsRecent(receipt.getAssetRecordId())) {
              log.warn("syncWalletGold 重复消费");
              return;
            }

            walletAssetSyncTool.syncGold(receipt);

            // 同步流水
            if (!Objects.equals(receipt.getCloseDelayAsset(), true)) {
              walletAssetSyncTool.saveWalletGoldAssetRecord(receipt);
            }

            // 移除事件标记
            walletGoldCacheService.removeEvent(receipt.getAssetRecordId(), receipt.getEventId());
            // 统计每一项消费详情
            walletGoldCacheService.countConsumeDaily(receipt.getSysOrigin(),
                receipt.getEventType(),
                receipt.getReceiptType().getType(),
                receipt.getAmount().getPennyAmount());
          }
        });
    long processTime = System.currentTimeMillis() - startTime;

    if (processTime >= 3000) {
      log.warn("syncWalletGold: 同步耗时 {}ms", processTime);
    }

    return action;
  }

  /**
   * 房间红包活动.
   */
  private void countGameRoomRedPacket(WalletReceiptSyncEvent event) {

    if (!SysOriginPlatformEnum.YOLO.getSysOrigin().equals(event.getSysOrigin())) {
      return;
    }

    boolean isActivityTime = isActivityTime(1706821200000L, 1707944400000L);

    if (!isActivityTime) {
      return;
    }

    if (!Objects.equals(event.getEventType(), "SEND_RED_PACKET")) {
      return;
    }

    if (!ReceiptType.EXPENDITURE.eq(event.getReceiptType())) {
      return;
    }

    temporaryActivityCountClient.incr(new TemporaryActivityCountCmd()
            .setSysOrigin(event.getSysOrigin())
            .setUserId(event.getUserId())
            .setActivityType("SEND_RED_PACKET")
            .setCountType("SEND_RED_PACKET")
            .setQuantity(event.getAmount().getDollarAmount().longValue()));
  }

  /**
   * 游戏活动20240827.
   */
  private void countGameKing20240420(WalletReceiptSyncEvent event) {
//    if (!SysOriginPlatformEnum.LOTFUN.getSysOrigin().equals(event.getSysOrigin())) {
//      return;
//    }

    boolean isActivityTime = isActivityTime(1753056000000L, 1753660800000L);
    log.warn("event {}，{}" , event, isActivityTime);

    if (!isActivityTime) {
      return;
    }

    if (!Objects.equals(event.getEventType(), "BAISHUN_GAME_1085")) {
      return;
    }

    if (!ReceiptType.INCOME.eq(event.getReceiptType())) {
      return;
    }

    log.warn("event.getAmount().getDollarAmount().longValue() {}" , event.getAmount().getDollarAmount().longValue());
    temporaryActivityCountClient.incr(new TemporaryActivityCountCmd()
            .setSysOrigin(event.getSysOrigin())
            .setUserId(event.getUserId())
            .setActivityType("BAISHUN_GAME_1085")
            .setCountType("RANK")
            .setQuantity(event.getAmount().getDollarAmount().longValue()));
  }

  /**
   * @return true 活动时间，false 非活动时间.
   */
  private boolean isActivityTime(long startTime, long endTime) {
    long nowTime = DateUtils.now().getTime();
    if (envProperties.isProd()) {
      return nowTime >= startTime && nowTime <= endTime;
    }
    return true;
  }

}
