package com.red.circle.other.app.command.game.ludo;

import com.red.circle.common.business.core.enums.SysOriginPlatformEnum;
import com.red.circle.common.business.dto.cmd.app.AppIdLongCmd;
import com.red.circle.component.redis.service.RedisService;
import com.red.circle.framework.core.asserts.ResponseAssert;
import com.red.circle.framework.core.response.CommonErrorCode;
import com.red.circle.other.app.common.game.GameLudoCommon;
import com.red.circle.other.infra.database.mongo.entity.game.ludo.GameLudoRun;
import com.red.circle.other.infra.database.mongo.entity.game.ludo.GameStatus;
import com.red.circle.other.infra.database.mongo.entity.game.ludo.GameStatusEvent;
import com.red.circle.other.infra.database.mongo.service.game.GameLudoRunService;
import com.red.circle.other.inner.asserts.GameErrorCode;
import com.red.circle.tool.core.collection.CollectionUtils;
import com.red.circle.tool.core.num.ArithmeticUtils;
import com.red.circle.wallet.inner.endpoint.wallet.WalletGoldClient;
import com.red.circle.wallet.inner.model.cmd.GoldReceiptCmd;
import com.red.circle.wallet.inner.model.enums.GoldOrigin;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * 主动解散游戏.
 *
 * @author pengliang on 2021/8/18
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class GameLudoLatestDisbandCmdExe {

  private final RedisService redisService;
  private final GameLudoCommon gameLudoCommon;
  private final WalletGoldClient walletGoldClient;
  private final GameLudoRunService gameLudoRunService;

  public void execute(AppIdLongCmd cmd) {
    String lockKey = "LUDO_DISBAND:" + cmd.getId();
    try {
      // 2067 操作冲突
      ResponseAssert.isTrue(CommonErrorCode.OPERATION_CONFLICT,
          redisService.lock(lockKey, 60));
      GameLudoRun gameLudoRun = gameLudoRunService.get(cmd.getId());
      // 8004 游戏不存在
      ResponseAssert.notNull(GameErrorCode.GAME_NOT_EXIST, gameLudoRun);
      gameLudoRun.setGameStatus(GameStatus.END);
      gameLudoRun.setGameStatusEvent(GameStatusEvent.TIMEOUT_DISBAND);
      gameLudoCommon.historyProcessing(gameLudoRun);
    } finally {
      redisService.unlock(lockKey);
    }
  }

  /**
   * 退款
   */
  private void refund(GameLudoRun gameLudoRun) {
    if (CollectionUtils.isNotEmpty(gameLudoRun.getPlayers())) {
      if (ArithmeticUtils.gtZero(gameLudoRun.getJoinAmount())) {
        gameLudoRun.getPlayers()
            .forEach(player -> walletGoldClient.changeBalance(GoldReceiptCmd.builder()
                .appIncome()
                .eventId(gameLudoRun.getId())
                .userId(player.getPlayerProfile().getId())
                .sysOrigin(SysOriginPlatformEnum.valueOf(gameLudoRun.getSysOrigin()))
                .origin(GoldOrigin.GAME_LUDO_REFUND)
                .amount(gameLudoRun.getJoinAmount())
                .build()));
      }
    }
  }


}
