package com.red.circle.order.app.command.pay.app.receipt;

import com.red.circle.common.business.core.enums.SysOriginPlatformEnum;
import com.red.circle.component.pay.apple.LatestEffectiveBody;
import com.red.circle.component.pay.apple.PendingRenewalInfo;
import com.red.circle.component.pay.apple.VerifyReceiptBody;
import com.red.circle.framework.core.request.RequestClientEnum;
import com.red.circle.order.domain.gateway.InAppPurchaseGateway;
import com.red.circle.order.infra.database.rds.entity.order.OrderAbnormalLog;
import com.red.circle.order.infra.database.rds.service.order.OrderAbnormalLogService;
import com.red.circle.tool.core.collection.CollectionUtils;
import com.red.circle.tool.core.json.JacksonUtils;
import com.red.circle.tool.core.text.StringUtils;
import java.util.List;
import java.util.Objects;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

/**
 * @author pengliang on 2020/4/3 10:37
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class ApplePurchaseServiceImpl implements ApplePurchaseService {

  private final OrderAbnormalLogService orderAbnormalLogService;
  private final InAppPurchaseGateway inAppPurchaseGateway;

  @Override
  public void checkAutomaticRenewalSubscription(SysOriginPlatformEnum sysOrigin,
      VerifyReceiptBody verifyReceiptBody, String productId) {
//    AutoSubscription autoSubscription = appleCheckSubscriptionExtractCmdExe
//        .execute(AppleCheckSubscriptionCmd.builder()
//            .sysOrigin(sysOrigin)
//            .verifyReceiptBody(verifyReceiptBody)
//            .productId(productId)
//            .build());
//    if (autoSubscription.isAutoRenew()) {
//      sendPurchaseCommodityProcessCmdExe.execute(SendPurchaseCommodityProcess.builder()
//          .extractInAppPurchaseReceipt(autoSubscription.getExtractInAppPurchaseReceipt())
//          .productConfig(platformPackageProductConfigGetQueryExe
//              .execute(autoSubscription.toProductConfigPackageGetCmd()))
//          .build());
//    }
    log.error("checkAutomaticRenewalSubscription已废弃");
  }

  @Override
  public void resetAppleReceipt(SysOriginPlatformEnum sysOrigin,
      VerifyReceiptBody verifyReceiptBody, String productId) {
    // 刷新指定产品单据
    if (StringUtils.isNotBlank(productId)) {
      restAppleReceiptByProductId(sysOrigin, productId, verifyReceiptBody);
      return;
    }

    // 刷新所有等待订阅单据
    resetAllApplePendingRenewalInfo(sysOrigin, verifyReceiptBody);
  }

  private void restAppleReceiptByProductId(SysOriginPlatformEnum sysOrigin, String productId,
      VerifyReceiptBody verifyReceiptBody) {
    LatestEffectiveBody latestEffectiveBody = verifyReceiptBody
        .getLatestReceiptPurchaseDateMsDesc(productId);
    String originalTransactionId = latestEffectiveBody.getOriginalTransactionId();
    if (Objects.isNull(latestEffectiveBody.getOriginalTransactionId())) {
      log.warn("not found originalTransactionId:{},{}", productId, verifyReceiptBody);
      return;
    }
    inAppPurchaseGateway
        .addAppleReceipt(inAppPurchaseGateway.getUserIdByOriginOrderId(originalTransactionId)
            , sysOrigin, latestEffectiveBody);
  }

  private void resetAllApplePendingRenewalInfo(SysOriginPlatformEnum sysOrigin,
      VerifyReceiptBody verifyReceiptBody) {
    List<PendingRenewalInfo> pendingRenewalInfos = verifyReceiptBody.getPendingRenewalInfo();
    if (CollectionUtils.isEmpty(pendingRenewalInfos)) {
      log.warn("PendingRenewalInfo is null");
      return;
    }

    // 获取关联用户
    PendingRenewalInfo pendingRenewalInfo = pendingRenewalInfos.get(0);
    Long userId = inAppPurchaseGateway
        .getUserIdByOriginOrderId(pendingRenewalInfo.getOriginalTransactionId());
    if (Objects.isNull(userId)) {
      log.warn("not found order info:{}", pendingRenewalInfo.getOriginalTransactionId());
      orderAbnormalLogService.saveUnique(new OrderAbnormalLog()
          .setSysOrigin(sysOrigin.name())
          .setPlatform(RequestClientEnum.iOS.getClientName())
          .setOrderId(pendingRenewalInfo.getOriginalTransactionId())
          .setOriginalOrderId(pendingRenewalInfo.getOriginalTransactionId())
          .setCertificate(JacksonUtils.toJson(verifyReceiptBody.getLatestReceipt()))
          .setProductCode(pendingRenewalInfo.getProductId())
      );
      return;
    }

    pendingRenewalInfos.forEach(pendingRenewalInfoObj -> {
      // 刷新等待自动续费状态
      inAppPurchaseGateway
          .resetApplePendingRenewalInfo(userId, sysOrigin, pendingRenewalInfoObj);
    });
  }

}
