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

import com.red.circle.component.pay.apple.LatestReceiptInfo;
import com.red.circle.component.pay.apple.ServerToServerNoticeBody;
import com.red.circle.component.pay.apple.ServerToServerNoticeCmd;
import com.red.circle.component.pay.apple.UnifiedReceipt;
import com.red.circle.order.app.common.RecycleReimburseOrderProductCommon;
import com.red.circle.tool.core.json.JacksonUtils;
import java.util.Objects;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

/**
 * 取消了订阅或用户升级了订阅
 *
 * @author pengliang on 2020/7/22
 */
@Slf4j
@Component("CANCEL")
@RequiredArgsConstructor
public class CancelStrategy implements AppleServerToServerStrategy {

  private final RecycleReimburseOrderProductCommon recycleReimburseOrderProductCommon;

  /**
   * 验证订阅类型是否退款，找到未过期订单中出现 CancellationDateMs 字段
   */
  @Override
  public void doOperation(ServerToServerNoticeCmd cmd) {
    ServerToServerNoticeBody body = cmd.getBody();
    // 如果存在WebOrderLineItemId 和 cancellationDateMs 查看检查退款信息
    if (Objects.nonNull(body.getWebOrderLineItemId()) && Objects
        .nonNull(body.getCancellationDateMs())) {
      UnifiedReceipt unifiedReceipt = body.getUnifiedReceipt();
      LatestReceiptInfo latestReceiptInfo = unifiedReceipt
          .getLatestInfoByWebOrderLineItemId(body.getWebOrderLineItemId());
      if (Objects.isNull(latestReceiptInfo)) {
        log.warn("Not Found LatestReceiptInfo [webOrderLineItemId:{}]",
            body.getWebOrderLineItemId());
        return;
      }
      if (Objects.nonNull(latestReceiptInfo.getCancellationDateMs())) {
        recycleReimburseOrderProductCommon.recyclePlatformOrderId(
            latestReceiptInfo.getTransactionId());
        return;
      }
      log.warn("LatestReceiptInfo Not CANCEL:{}", JacksonUtils.toJson(latestReceiptInfo));
      return;
    }

    // 找到对应商品未过期单据，存在取消时间单据处理退款
    UnifiedReceipt unifiedReceipt = body.getUnifiedReceipt();
    LatestReceiptInfo latestReceiptInfo = unifiedReceipt
        .getNotExpiredLatestInfo(body.getAutoRenewProductId());
    if (Objects.nonNull(latestReceiptInfo) && Objects
        .nonNull(latestReceiptInfo.getCancellationDateMs())) {
      recycleReimburseOrderProductCommon.recyclePlatformOrderId(
          latestReceiptInfo.getTransactionId());
    }
  }
}
