package com.red.circle.order.app.service;

import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.androidpublisher.AndroidPublisher;
import com.google.api.services.androidpublisher.AndroidPublisherScopes;
import com.google.api.services.androidpublisher.model.*;
import com.google.firestore.v1.StructuredQuery;
import com.red.circle.common.business.core.enums.SysOriginPlatformEnum;
import com.red.circle.common.business.dto.cmd.IdStringCmd;
import com.red.circle.component.pay.google.GoogleNoticeOriginCmd;
import com.red.circle.component.pay.google.notice.GoogleNotice;
import com.red.circle.framework.core.asserts.ResponseAssert;
import com.red.circle.framework.core.response.ResponseErrorCode;
import com.red.circle.mq.business.model.event.task.TaskApprovalEvent;
import com.red.circle.mq.rocket.business.producer.TaskMqMessage;
import com.red.circle.order.app.command.pay.app.execute.AppInAppPurchaseCmdExe;
import com.red.circle.order.app.command.pay.app.execute.AppleAutoSubscriptionNoticeCmdExe;
import com.red.circle.order.app.command.pay.app.execute.GoogleCheckOneTimeProductNoticeCmdExe;
import com.red.circle.order.app.command.pay.web.AirwallexServerNoticeCmdExe;
import com.red.circle.order.app.command.pay.web.ClipspayServerNoticeCmdExe;
import com.red.circle.order.app.command.pay.web.CollectionReceiptQueryExe;
import com.red.circle.order.app.command.pay.web.PayPalServerNoticeCmdExe;
import com.red.circle.order.app.command.pay.web.PayWebPlaceAnOrderCmdExe;
import com.red.circle.order.app.command.pay.web.PayerMaxServerNoticeReceivePaymentCmdExe;
import com.red.circle.order.app.command.pay.web.PayerMaxServerNoticeRefundNoticeCmdExe;
import com.red.circle.order.app.command.pay.web.PaynicornServerNoticeCmdExe;
import com.red.circle.order.app.command.pay.web.ReceiptPayWebPlaceAnOrderReceiptCmdExe;
import com.red.circle.order.app.dto.clientobject.PayMaxResponseCO;
import com.red.circle.order.app.dto.clientobject.PayerMaxResponseV2CO;
import com.red.circle.order.app.dto.clientobject.PurchaseReceiptCO;
import com.red.circle.order.app.dto.clientobject.pay.PlaceAnOrderResponseCO;
import com.red.circle.order.app.dto.cmd.AbstractPurchaseCmd;
import com.red.circle.order.app.dto.cmd.PayPlaceAnOrderCmd;
import com.red.circle.order.app.dto.cmd.PayPlaceAnOrderReceiptCmd;
import com.red.circle.tool.core.date.LocalDateTimeUtils;
import com.red.circle.tool.core.json.JacksonUtils;

import java.io.IOException;
import java.util.Collections;
import java.util.Map;
import java.util.Objects;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

/**
 * 支付内购相关.
 *
 * @author pengliang on 2020/11/23
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class InAppPurchaseProductServiceImpl implements InAppPurchaseProductService {

  private final AppInAppPurchaseCmdExe appInAppPurchaseCmdExe;
  private final PayWebPlaceAnOrderCmdExe payWebPlaceAnOrderCmdExe;
  private final PayPalServerNoticeCmdExe payPalServerNoticeCmdExe;
  private final CollectionReceiptQueryExe collectionReceiptQueryExe;
  private final ClipspayServerNoticeCmdExe clipspayServerNoticeCmdExe;
  private final AirwallexServerNoticeCmdExe airwallexServerNoticeCmdExe;
  private final PaynicornServerNoticeCmdExe paynicornServerNoticeCmdExe;
  private final AppleAutoSubscriptionNoticeCmdExe appleAutoSubscriptionNoticeCmdExe;
  private final GoogleCheckOneTimeProductNoticeCmdExe googleCheckOneTimeProductNoticeCmdExe;
  private final ReceiptPayWebPlaceAnOrderReceiptCmdExe receiptPayWebPlaceAnOrderReceiptCmdExe;
  private final PayerMaxServerNoticeRefundNoticeCmdExe payerMaxServerNoticeRefundNoticeCmdExe;
  private final PayerMaxServerNoticeReceivePaymentCmdExe payerMaxServerNoticeReceivePaymentCmdExe;
  private final TaskMqMessage taskMqMessage;

  @Override
  public PurchaseReceiptCO purchase(AbstractPurchaseCmd cmd) {
    log.info("purchase:{}", JacksonUtils.toJson(cmd));
    //完成任务 钩子 9 充值 谷歌
    /*taskMqMessage.sendTask(TaskApprovalEvent.builder()
            .taskId(9)
            .userId(cmd.getReqUserId())
            .day(LocalDateTimeUtils.nowFormat("yyyy-MM-dd"))
            .build());*/
    return appInAppPurchaseCmdExe.execute(cmd);
  }

  @Override
  public void googleServerNotice(SysOriginPlatformEnum sysOrigin, byte[] body) {
    ResponseAssert
        .isTrue(ResponseErrorCode.REQUEST_PARAMETER_ERROR,
            Objects.nonNull(body) && body.length > 0);
    GoogleNotice googleNotice = GoogleNotice.serializable(body);

    if (Objects.isNull(googleNotice)) {
      log.warn("Parameter conversion failed.");
      return;
    }

    if (googleNotice.isTestNotice()) {
      log.warn("Google Test Notice:{}", JacksonUtils.toJson(googleNotice));
      return;
    }

    if (googleNotice.isOneTimeProductNotice()) {
      googleCheckOneTimeProductNoticeCmdExe
          .execute(getGoogleNoticeOriginCmd(sysOrigin, googleNotice));
      return;
    }

    if (googleNotice.isSubscriptionNotice()) {
      // google 订阅通知
      log.error("收到Google订阅通知，系统不支持: {}", googleNotice);
      return;
    }

    log.error("Unknown parameter handling:{}", googleNotice);
  }


  private GoogleNoticeOriginCmd getGoogleNoticeOriginCmd(SysOriginPlatformEnum sysOrigin,
      GoogleNotice googleNotice) {
    return GoogleNoticeOriginCmd.builder().sysOrigin(Objects.toString(sysOrigin))
        .googleNotice(googleNotice).build();
  }

  @Override
  public void appleServerNotice(SysOriginPlatformEnum sysOrigin, byte[] body) {
    appleAutoSubscriptionNoticeCmdExe.execute(sysOrigin, body);
  }

  @Override
  public PayerMaxResponseV2CO payerMaxServerNoticeReceivePayment(byte[] body) {
    return payerMaxServerNoticeReceivePaymentCmdExe.execute(body);
  }

  @Override
  public PayMaxResponseCO payerMaxServerNoticeReceivePaymentOld(byte[] body) {
    return payerMaxServerNoticeReceivePaymentCmdExe.executeOld(body);
  }

  @Override
  public PayMaxResponseCO payerMaxServerNoticeRefundNotice(byte[] body) {
    return payerMaxServerNoticeRefundNoticeCmdExe.execute(body);
  }

  @Override
  public PlaceAnOrderResponseCO placeAnOrder(PayPlaceAnOrderCmd cmd) {
    return payWebPlaceAnOrderCmdExe.execute(cmd);
  }

  @Override
  public PlaceAnOrderResponseCO payReceipt(PayPlaceAnOrderReceiptCmd cmd) {
    return receiptPayWebPlaceAnOrderReceiptCmdExe.execute(cmd);
  }

  @Override
  public Object collectionReceipt(IdStringCmd cmd) {
    return collectionReceiptQueryExe.execute(cmd);
  }

  @Override
  public void payPalNotice(byte[] body) {
    payPalServerNoticeCmdExe.execute(body);
  }

  @Override
  public void airwallexNotice(byte[] body) {
    airwallexServerNoticeCmdExe.execute(body);
  }

  @Override
  public String paynicornNotice(byte[] body) {
    return paynicornServerNoticeCmdExe.execute(body);
  }

  @Override
  public void clipspayServerNotice(Map<String, String> body) {
    clipspayServerNoticeCmdExe.execute(body);
  }

}
