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.domain.gateway.props.ActivitySourceGroupGateway;
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.service.activity.ActivityReceiveRewardLogService;
import com.red.circle.other.inner.enums.activity.PropsActivityTypeEnum;
import com.red.circle.other.inner.model.dto.activity.props.ActivityPropsRule;
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;

/**
 * CP奖励领取.
 *
 * @author pengliang on 2021/6/24
 */
@Component
@RequiredArgsConstructor
public class CpRewardReceiveCmdExe {

  private final PropsActivitySendCommon activitySendCommon;
  private final ActivitySourceGroupGateway activitySourceGroupGateway;
  private final ActivityReceiveRewardLogService activityReceiveRewardLogService;

  public void execute(AppIdLongCmd cmd) {
    ActivityPropsRule ruleConfig = activitySourceGroupGateway.getByRuleId(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
            .existsThisMonth(cmd.getReqUserId(), ruleConfig.getId(),
                PropsActivityTypeEnum.CP_REWARD));

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

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