package com.red.circle.order.app.command.pay.app.strategy.commodity;

import com.red.circle.framework.core.asserts.ResponseAssert;
import com.red.circle.order.app.command.pay.app.model.AppCommodity;
import com.red.circle.order.app.dto.clientobject.PurchaseReceiptCO;
import com.red.circle.order.infra.database.enums.ProductGroupEnum;
import com.red.circle.tool.core.json.JacksonUtils;
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.dto.WalletReceiptResDTO;
import com.red.circle.wallet.inner.model.enums.GoldOrigin;
import java.util.Objects;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

/**
 * 糖果积分
 *
 * @author pengliang on 2020/1/6 14:23
 */
@Slf4j
@RequiredArgsConstructor
@Service("CANDY")
public class GoldStrategy implements CommodityStrategy {

  private final WalletGoldClient walletGoldClient;

  @Override
  public PurchaseReceiptCO doOperation(AppCommodity appCommodity) {
    log.info("CandyStrategy:{}", JacksonUtils.toJson(appCommodity));
    return new PurchaseReceiptCO()
        .setProductId(appCommodity.getProductConfigProductId())
        .setProductGroup(ProductGroupEnum.CANDY.name())
        .setObtainAmount(appCommodity.getProductConfigCandy())
        .setBalanceAmount(changeBalance(appCommodity).getBalance().getDollarAmount());
  }

  private WalletReceiptResDTO changeBalance(
      AppCommodity appCommodity) {
    return ResponseAssert.requiredSuccess(
        walletGoldClient.changeBalance(
            GoldReceiptCmd.builder()
                .appIncome()
                .userId(appCommodity.getAcceptUserId())
                .eventId(appCommodity.getPurchaseId())
                .sysOrigin(appCommodity.getPurchaseSysOrigin())
                .origin(getGoldOrigin(appCommodity))
                .originDescribe(appCommodity.getOriginDescription())
                .amount(appCommodity.getProductConfigCandy())
                .build()
        )
    );
  }

  private GoldOrigin getGoldOrigin(AppCommodity cmd) {
    return Objects.nonNull(cmd.getFiendId())
        ? GoldOrigin.FRIENDS_GIVE_GOLD_COINS : GoldOrigin.BUY_GOLD;
  }

}
