package com.zxhl.cms.pay.paypal

import android.app.Activity
import android.util.Log
import com.paypal.checkout.approve.OnApprove
import com.paypal.checkout.cancel.OnCancel
import com.paypal.checkout.createorder.*
import com.paypal.checkout.error.OnError
import com.paypal.checkout.order.*
import com.paypal.checkout.paymentbutton.PayPalButton
import com.zxhl.cms.net.ApiClient
import com.zxhl.cms.net.RxSchedulers
import com.zxhl.cms.net.callback.BaseObserver
import com.zxhl.cms.net.model.pay.GooglePayEntity
import com.zxhl.cms.paypal.PayPalPayCallBack
import kotlinx.android.synthetic.main.activity_member.*
import java.util.*


/**
 * @author (wangXuewei)
 * @datetime 2022-03-10 16:06 GMT+8
 * @detail :
 */
class PayPalHelper {

    private val TAG = "PayPalHelper"
    private var mActivity: Activity;
    private var mPayCallBack: PayPalPayCallBack? = null;
    private var mPayButton: PayPalButton? = null;//payPal按钮

    constructor(mActivity: Activity) {
        this.mActivity = mActivity
    }


    /**
     * payPal支付
     */
    fun payPalPay(
        goodsId: String,
        goodsPrice: String,
        payMode: String,
        payCallBack: PayPalPayCallBack,
        payView: PayPalButton
    ) {
        mPayButton = payView;
        mPayCallBack = payCallBack
        //向服务端获取订单ID
        ApiClient.userInfoAPi.googlePay(goodsId, "5", "", "", payMode)
            .compose(RxSchedulers.observableIO2Main())
            .subscribe(object : BaseObserver<GooglePayEntity>() {
                override fun onSuccess(result: GooglePayEntity?) {
                    if (result != null) {
                        startPay(result.outTradeNo, goodsPrice)
                    } else {
                        mPayCallBack?.onError("payPalPay 未获取到订单数据")
                    }
                }

                override fun onFailure(e: Throwable?, code: String?, errorMsg: String?) {
                    mPayCallBack?.onError("payPalPay 获取订单号接口异常 Error:$errorMsg")
                }
            })
    }

    private fun startPay(orderId: String, price: String) {
        mPayButton?.setup(
            createOrder = CreateOrder { createOrderActions ->
                val order =
                    Order(
                        intent = OrderIntent.CAPTURE,
                        appContext = AppContext(userAction = UserAction.PAY_NOW),
                        purchaseUnitList =
                        listOf(
                            PurchaseUnit(
                                //金额相关
                                amount = Amount(currencyCode = CurrencyCode.USD, value = price),
                                //发票编号
                                invoiceId = orderId
                                //引用ID
//                                referenceId = "" + System.currentTimeMillis(),
//                                customId = orderId,
//                                description = "这是一笔订单描述",
                                //收款人（商户的电子邮件地址,商家加密的PayPal账号ID）
//                                payee = Payee("",""),
//                                items = listOf(
//                                    Items
//                                        .Builder()
//                                        .name("测试订单")
//                                        .category(category = ItemCategory.DIGITAL_GOODS)
//                                        .quantity("1")
//                                        .build()
//                                ),
//                                payments = Payments(),
//                                shipping = Shipping(),
//                                softDescriptor = "简单说明"
                            )
                        )/*,
                        ProcessingInstruction.ORDER_COMPLETE_ON_PAYMENT_APPROVAL*/
                    )
//                createOrderActions.set(orderId)
                createOrderActions.create(order)
//                Log.i("id_PayPal_btn", "createOrderActions order: ${order.purchaseUnitList.size}")
            },
            onApprove = OnApprove { approval ->
                approval.orderActions.capture { captureOrderResult ->
//                    Log.e(TAG, "CaptureOrder CaptureOrderResult: $captureOrderResult")
//                    Log.e(TAG, "CaptureOrder approval.data.orderId: ${approval.data.payerId}")
//                    Log.e(TAG, "CaptureOrder approval.data.orderId: ${approval.data.paymentId}")
//                    Log.e(TAG, "CaptureOrder approval.data.orderId: ${approval.data.cart}")
//                    Log.e(TAG, "CaptureOrder approval.data.orderId: ${approval.data.payer}")
                    if (captureOrderResult is CaptureOrderResult.Success) {
                        var result =
                            if (!captureOrderResult.orderResponse?.purchaseUnits?.get(0)?.payments?.captures?.get(
                                    0
                                )?.id.isNullOrEmpty()
                            ) {
                                "{\"orderId\":\"${orderId}\",\"payPalId\":\"${
                                    captureOrderResult.orderResponse?.purchaseUnits?.get(
                                        0
                                    )?.payments?.captures?.get(0)?.id
                                }\"}"
                            } else {
                                "{\"orderId\":\"${orderId}\",\"payPalId\":\"\"}"
                            }
                        mPayCallBack?.onPaySuccess(result)
                    } else if (captureOrderResult is CaptureOrderResult.Error) {
                        mPayCallBack?.onError("PayPal 获取订单失败 msg: ${captureOrderResult.message} reason:${captureOrderResult.reason}")
                    }
                }
            },
            onError = OnError { errorInfo ->
                Log.e(TAG, "Wid_PayPal_btn OnError Error: $errorInfo")
                mPayCallBack?.onError("payPalError:$errorInfo")
            },
            onCancel = OnCancel {
                Log.e(TAG, " OnCancel Buyer canceled the PayPal experience.")
                mPayCallBack?.onCancel()
            }
        )
        mPayButton?.callOnClick()
    }


//    private val TAG = "PayPaylHelper"
//    private var checkOrderMax: Int = 300//循环检测的最大次数
//    private var checkOrderCount: Int = -1//循环检测的初始次数
//    private var isCheckOrderFlag: Boolean = false//是否检测订单状态中
//    @RequiresApi(Build.VERSION_CODES.M)
//    private fun startPayPal(context: Activity, paypalOrderId: String) {
//        PayPalCheckout.start(CreateOrder { createOrderActions ->
//            createOrderActions.set(
//                paypalOrderId
//            )
//        }, null, null,
//            OnCancel {//实测取消订单后没走这个方法，走到了报错，报的returnUrl是空，但我们再paypal后台和sdk初始化均设置了的，而且在手机浏览器登录paypal买家账号后也是可以拉回我们app的，但是它还是会报这个错，无语子，估计还是paypal得bug
//                resetCheckPaypalOrder()
//                System.out.println("用户取消Paypal支付")
//            },
//            OnError { errorInfo ->
//                resetCheckPaypalOrder()
//                System.out.println("==========paypal onError=======ErrorInfo=======>: $errorInfo")
//                System.out.println(
//                    if (errorInfo?.reason.isNullOrBlank()) (if (errorInfo?.error?.message.isNullOrBlank())
//                        "Paypal支付未知错误" else errorInfo.error.message) else errorInfo!!.reason
//                )
//            })
//        checkOrderCount = 0
//        isCheckOrderFlag = true
//        startCheckPaypalOrder(context, paypalOrderId)
//    }
//
//    private fun startCheckPaypalOrder(context: Activity, paypalOrderId: String) {
//        System.out.println("======Stephen=======checkPaypalOrder====>Count:$checkOrderCount")
//        if (!isCheckOrderFlag) return
//        if (checkOrderCount >= checkOrderMax) {
//            resetCheckPaypalOrder()
//            System.out.println("Paypal订单支付等待超时")
//            return
//        }//end of if
//        ApiRequestMethod.checkPaypalOrder(paypalOrderId, object : RequestAllCallback<String> {
//            //这个是我们接口调用封装方法，换成你们自己的哈（REST v2订单详情接口：https://developer.paypal.com/api/orders/v2/#orders_get）
//            override fun onSuccess(data: String?) {//接口返回正确json形如：{"paypal_status":"CREATED"}
//                var isContinueLoop = true
//                val jsonObject = ToolUtils.instance.fromJsonToObj(data)
//                if (null != jsonObject && jsonObject.has("paypal_status")) {
//                    when (jsonObject.getString("paypal_status")) {
//                        "APPROVED" -> {//这个状态表示用户已经支付完成，后台开始捕获订单并开始执行确认了，实测这个状态有时差不多得持续1分多钟，快的话也是耗费20多秒，因此添加一个loading逻辑如下，此具体loading显示逻辑更换成你自己实际的loading框，注意loading框得依附在你自己App的当前支付界面上，因为你看到paypal的支付框实质是一个activity，依附在paypal上面会被误关闭
//                            if (!ToolUtils.instance.isLoadingShow()) ToolUtils.instance.showLoading(
//                                "确认支付结果中...",
//                                appendActivity = context
//                            )
//                        }
//                        "COMPLETED" -> {//这个状态表示后台捕获确认订单完成，也就是这笔订单真正的完成了
//                            isContinueLoop = false
//                            resetCheckPaypalOrder()
//                            System.out.println("Paypal订单支付成功")
//                        }
//                    }
//                }//end of if
//                if (isContinueLoop) {
////                ToolUtils.instance.delayExecute(1000L){//这个是我们延时调用封装方法，换成你们自己的哈
////                    checkOrderCount++
////                    startCheckPaypalOrder(context, paypalOrderId)
////                }
//                }//end of if
//            }
//
//            override fun onFailure(aliErrorResponse: AliErrorResponse, httpCode: Int): Boolean {
//                ToolUtils.instance.delayExecute(1000L) {
//                    checkOrderCount++
//                    startCheckPaypalOrder(context, paypalOrderId)
//                }
//                return false
//            }
//        })
//    }
//
//    private fun resetCheckPaypalOrder() {
//        checkOrderCount = 0
//        isCheckOrderFlag = false
//
////        ToolUtils.instance.closeLoading()//关闭loading框
//    }

}