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

import com.google.api.services.androidpublisher.model.ProductPurchase;
import com.red.circle.common.business.core.enums.SysOriginPlatformEnum;
import com.red.circle.component.pay.google.GoogleNoticeOriginCmd;
import com.red.circle.component.pay.google.GoogleVerifyService;
import com.red.circle.component.pay.google.notice.GoogleNotice;
import com.red.circle.component.pay.google.notice.OneTimeProductNotification;
import com.red.circle.framework.core.request.RequestClientEnum;
import com.red.circle.order.app.common.RecycleReimburseOrderProductCommon;
import com.red.circle.order.domain.gateway.InAppPurchaseGateway;
import com.red.circle.order.infra.database.mongo.order.InAppPurchaseDetailsService;
import com.red.circle.order.infra.database.mongo.order.entity.assist.InAppPurchaseEventNotice;
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.date.TimestampUtils;
import com.red.circle.tool.core.json.JacksonUtils;
import com.red.circle.tool.core.sequence.IdWorkerUtils;
import java.util.Objects;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * 检测google消耗商品是否有取消退订情况
 *
 * @author pengliang on 2020/11/23
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class GoogleCheckOneTimeProductNoticeCmdExe {

  private final GoogleVerifyService googleVerifyService;
  private final OrderAbnormalLogService orderAbnormalLogService;
  private final InAppPurchaseGateway inAppPurchaseGateway;
  private final InAppPurchaseDetailsService inAppPurchaseDetailsService;
  private final RecycleReimburseOrderProductCommon recycleReimburseOrderProductCommon;

  public void execute(GoogleNoticeOriginCmd cmd) {
    GoogleNotice googleNotice = cmd.getGoogleNotice();
    OneTimeProductNotification oneNotice = googleNotice.getOneTimeProductNotification();
    // 获取单据状态
    ProductPurchase productPurchase = googleVerifyService
        .checkPurchase(SysOriginPlatformEnum.valueOf(cmd.getSysOrigin()),
            googleNotice.getPackageName(), oneNotice.getSku(),
            oneNotice.getPurchaseToken());
    if (Objects.isNull(productPurchase)) {
      log.warn("OneTimeProductNotification is error:{}", googleNotice.toJson());
      return;
    }

    inAppPurchaseDetailsService.addPayNoticesByOrderId(productPurchase.getOrderId(),
        new InAppPurchaseEventNotice()
            .setEventId("custom-" + IdWorkerUtils.getIdStr())
            .setNoticeType(googleNotice.customizeNoticeType())
            .setNoticeData(googleNotice)
            .setCreateTime(TimestampUtils.now())
    );

    if (Objects.equals(productPurchase.getAcknowledgementState(), 0)) {
      log.warn("OneTimeProductNotification is AcknowledgementState=0");
      return;
    }

    // 验证订单是否存在
    Long userId = inAppPurchaseGateway.getUserIdByOrderId(productPurchase.getOrderId());
    if (Objects.isNull(userId)) {
      log.warn("OneTimeProductNotification order not found:{}", productPurchase.getOrderId());
      orderAbnormalLogService.saveUnique(new OrderAbnormalLog()
          .setSysOrigin(cmd.getSysOrigin())
          .setPlatform(RequestClientEnum.Android.getClientName())
          .setOrderId(productPurchase.getOrderId())
          .setOriginalOrderId(GoogleVerifyService.toOriginalOrderId(productPurchase.getOrderId()))
          .setCertificate(JacksonUtils.toJson(googleNotice))
      );
      return;
    }

    // 刷新单据
    inAppPurchaseGateway.addGoogleLatestPurchase(
        SysOriginPlatformEnum.valueOf(cmd.getSysOrigin()), userId, productPurchase);

    // 验证是否存在退订
    if (Objects.equals(productPurchase.getPurchaseState(), 1)) {
      recycleReimburseOrderProductCommon.recyclePlatformOrderId(productPurchase.getOrderId());
    }

  }
}
