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

import com.google.api.services.androidpublisher.model.ProductPurchase;
import com.red.circle.component.pay.google.GooglePayProductParam;
import com.red.circle.component.pay.google.GoogleVerifyService;
import com.red.circle.framework.core.asserts.ResponseAssert;
import com.red.circle.framework.core.response.CommonErrorCode;
import com.red.circle.order.app.command.pay.app.model.ExtractInAppPurchaseReceipt;
import com.red.circle.order.app.command.pay.app.receipt.AssemblyOrder;
import com.red.circle.order.app.dto.cmd.AbstractPurchaseCmd;
import com.red.circle.order.app.dto.cmd.GooglePurchaseCmd;
import com.red.circle.order.domain.gateway.InAppPurchaseGateway;
import com.red.circle.order.inner.asserts.OrderErrorCode;
import java.util.Objects;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * 提取订单单据.
 *
 * @author pengliang on 2020/7/23
 */
@Slf4j
@Component("googleExtractAppPurchaseOrderStrategy")
@RequiredArgsConstructor
public class GoogleExtractAppPurchaseOrderStrategy implements ExtractAppPurchaseOrderStrategy {

  private final GoogleVerifyService googleVerifyService;
  private final InAppPurchaseGateway inAppPurchaseGateway;

  @Override
  public ExtractInAppPurchaseReceipt doOperation(AbstractPurchaseCmd cmd) {

    GooglePurchaseCmd playParam = (GooglePurchaseCmd) cmd;

    // 验证签名
    GooglePayProductParam signParam = googleVerifyService
        .verifySign(cmd.requireReqSysOriginChildEnum(), playParam.getPurchaseData(),
            playParam.getSignature());

    // 验证签名失败
    ResponseAssert.notNull(CommonErrorCode.VERIFY_SIGNATURE_FAILURE, signParam);

    return purchase(playParam, signParam);
  }

  /**
   * 状态码
   * acknowledgementState 应用内商品的确认状态。可能值为:0.尚未确认1.已确认
   * consumptionState 应用内商品的消费状态，可能值为:0.未消费1.已消费
   * purchaseState 订单的购买状态。可能的值有:0.已购买1.已取消 2.待处理
   */
  private ExtractInAppPurchaseReceipt purchase(GooglePurchaseCmd cmd,
      GooglePayProductParam signParam) {
    ProductPurchase productPurchase = googleVerifyService
        .checkPurchase(cmd.requireReqSysOriginChildEnum(), signParam.getPackageName(),
            signParam.getProductId(),
            signParam.getPurchaseToken());
    log.warn("productPurchase {}", productPurchase);

    if (Objects.isNull(productPurchase)) {
      throw new IllegalArgumentException("checkPurchase GoogleServer error.");
    }

    if (Objects.isNull(productPurchase.getPurchaseToken())) {
      productPurchase.setPurchaseToken(signParam.getPurchaseToken());
    }
    inAppPurchaseGateway
        .addGoogleLatestPurchase(cmd.requireReqSysOriginChildEnum(), cmd.requiredReqUserId(),
            productPurchase);

    ResponseAssert.isFalse(OrderErrorCode.ORDER_WAITING_FOR_PROCESSING,
            Objects.equals(productPurchase.getPurchaseState(), 2));

    ResponseAssert.isTrue(OrderErrorCode.ORDER_EXISTS_CREATED,
        Objects.equals(productPurchase.getPurchaseState(), 0));

    return AssemblyOrder.toGoogleExtractInAppPurchaseReceipt(cmd, signParam, productPurchase);
  }


}
