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

import com.red.circle.common.business.core.enums.SysOriginPlatformEnum;
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.pet.PetFinishRewardReceive;
import com.red.circle.other.infra.database.rds.entity.pet.PetPool;
import com.red.circle.other.infra.database.rds.entity.pet.PetUserPetBag;
import com.red.circle.other.infra.database.rds.enums.pet.PetStageLevelEnum;
import com.red.circle.other.infra.database.rds.service.pet.PetFinishRewardReceiveService;
import com.red.circle.other.infra.database.rds.service.pet.PetPoolService;
import com.red.circle.other.infra.database.rds.service.pet.PetUserPetBagService;
import com.red.circle.other.inner.asserts.PropsErrorCode;
import java.util.Objects;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

/**
 * 宠物养成奖励领取.
 *
 * @author pengliang on 2021/10/26
 */
@Component
@RequiredArgsConstructor
public class PetReceiveFinishAwardCmdExe {

  private final PetPoolService petPoolService;
  private final PropsActivitySendCommon sendPropsManager;
  private final PetUserPetBagService petUserPetBagService;
  private final PetFinishRewardReceiveService petFinishRewardReceiveService;

  public void execute(AppIdLongCmd cmd) {
    PetUserPetBag bag = petUserPetBagService.getById(cmd.getId());
    // 1033 记录不存在
    ResponseAssert.notNull(CommonErrorCode.NOT_FOUND_RECORD_INFO, bag);
    // 2046 不可领取
    ResponseAssert.isTrue(PropsErrorCode.UNCLAIMABLE, Objects.equals(bag.getPetStage(),
        PetStageLevelEnum.FINISH.name()));
    // 1035 不可重复领取
    ResponseAssert.isFalse(CommonErrorCode.NON_REPEATABLE,
        petFinishRewardReceiveService.existsReceiveStatus(cmd.getReqUserId(), bag.getId()));
    PetPool petPool = petPoolService.getById(bag.getPetId());
    // 1033 记录不存在
    ResponseAssert.notNull(CommonErrorCode.NOT_FOUND_RECORD_INFO, petPool);

    sendPropsManager.sendActivityGroup(SendRewardGroup.builder()
        .trackId(bag.getId())
        .sysOrigin(SysOriginPlatformEnum.valueOf(cmd.getReqSysOrigin().getOrigin()))
        .acceptUserId(cmd.getReqUserId())
        .resourceGroupId(petPool.getRewardGroupId())
        .origin(SendPropsOrigin.PET_REWARD)
        .build());

    petFinishRewardReceiveService.save(new PetFinishRewardReceive()
        .setUserId(cmd.getReqUserId())
        .setPetId(bag.getPetId())
        .setPetBagId(bag.getId())
    );
  }

}
