package com.red.circle.other.app.command.activity;

import com.red.circle.common.business.dto.cmd.app.AppIdLongCmd;
import com.red.circle.common.business.enums.SendPropsOrigin;
import com.red.circle.framework.core.asserts.ResponseAssert;
import com.red.circle.framework.core.response.CommonErrorCode;
import com.red.circle.other.infra.common.activity.PropsActivitySendCommon;
import com.red.circle.other.infra.common.activity.send.SendRewardGroup;
import com.red.circle.other.infra.database.rds.entity.activity.ActivityReceiveRewardLog;
import com.red.circle.other.infra.database.rds.entity.activity.PropsActivityRuleConfig;
import com.red.circle.other.infra.database.rds.service.activity.ActivityReceiveRewardLogService;
import com.red.circle.other.infra.database.rds.service.activity.PropsActivityRuleConfigService;
import com.red.circle.other.inner.enums.activity.PropsActivityTypeEnum;
import com.red.circle.other.inner.model.dto.activity.rule.RoomRewardContent;
import com.red.circle.tool.core.num.ArithmeticUtils;
import java.math.BigDecimal;
import java.util.Objects;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

/**
 * 房间奖励领取.
 *
 * @author pengliang on 2021/6/24
 */
@Component
@RequiredArgsConstructor
public class RoomRewardReceiveCmdExe {

  private final PropsActivitySendCommon sendPropsManager;
  private final PropsActivityRuleConfigService propsActivityRuleConfigService;
  private final ActivityReceiveRewardLogService activityReceiveRewardLogService;

  public void execute(AppIdLongCmd cmd) {
    PropsActivityRuleConfig ruleConfig = propsActivityRuleConfigService.getById(cmd.getId());
    // 1034 没有找到映射信息
    ResponseAssert.notNull(CommonErrorCode.NOT_FOUND_MAPPING_INFO, ruleConfig);

    RoomRewardContent roomRewardContent = RoomRewardContent
        .serializable(ruleConfig.getJsonData());

    // 2040 配置错误
    ResponseAssert.isTrue(CommonErrorCode.CONFIGURATION_ERROR,
        Objects.nonNull(roomRewardContent) && ArithmeticUtils
            .gt(roomRewardContent.getQuantity(), BigDecimal.ZERO));

    // 1035 不可重复领取
    ResponseAssert.isFalse(CommonErrorCode.NON_REPEATABLE,
        activityReceiveRewardLogService
            .exists(cmd.getReqUserId(), ruleConfig.getId(),
                PropsActivityTypeEnum.ROOM_REWARD));

    sendPropsManager.sendActivityGroup(SendRewardGroup.builder()
        .trackId(ruleConfig.getId())
        .sysOrigin(cmd.requireReqSysOriginEnum())
        .acceptUserId(cmd.getReqUserId())
        .resourceGroupId(ruleConfig.getResourceGroupId())
        .origin(SendPropsOrigin.ROOM_REWARD)
        .build());

    activityReceiveRewardLogService.save(new ActivityReceiveRewardLog()
        .setUserId(cmd.getReqUserId())
        .setReceiveId(ruleConfig.getId())
        .setSysOrigin(cmd.getReqSysOrigin().getOrigin())
        .setType(PropsActivityTypeEnum.ROOM_REWARD.name())
    );
  }
}
