package com.zxhl.cms.googlepay

import android.app.Activity
import android.util.Log
import com.android.billingclient.api.*
import com.android.billingclient.api.BillingClient.BillingResponseCode
import com.android.billingclient.api.BillingClient.SkuType
import com.zxhl.cms.AppContext
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.other.AnyEntity
import com.zxhl.cms.net.model.uc.GooglePayEntity
import com.zxhl.cms.utils.EventUtils
import org.json.JSONObject


/**
 * @author (wangXuewei)
 * @datetime 2022-03-09 15:12 GMT+8
 * @detail :
 */
class GooglePayHelper {
    private val TAG = "GooglePayHelper"
    private var mActivity: Activity;
    private var mPayCallBack: GooglePayCallBack? = null;
    private var mAutoPayCallBack: GooglePayCallBack? = null;//补单监听
    private var productId = ""
    private var obfuscatedAccountid = ""

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

    /**
     * 购买监听
     */
    private val purchasesUpdatedListener =
        PurchasesUpdatedListener { billingResult, purchases ->
            // To be implemented in a later section.
            Log.d(TAG, "购买监听 code ${billingResult.responseCode}")
            Log.d(TAG, "购买监听 size ${purchases?.size}")
            EventUtils.onEvent(
                "GooglePayGotoPayE",
                "Google支付结束回调结果 code${billingResult.responseCode}"
            )
            if (billingResult.responseCode == BillingResponseCode.OK) {
                //支付成功 同步后台
                if (!purchases.isNullOrEmpty()) {
                    for (i in 0 until purchases.size) {
                        val purchase = purchases[i];
                        val googleJson = JSONObject(purchase.originalJson)
                        val proId = googleJson.optString("productId") ?: productId
                        val accountId =
                            googleJson.optString("obfuscatedAccountId") ?: obfuscatedAccountid
                        val googlePayResult = GooglePayResult()
                        googlePayResult.packageName = purchase.packageName
                        googlePayResult.orderId = purchase.orderId
                        googlePayResult.productId = proId
                        googlePayResult.obfuscatedAccountid = accountId
                        googlePayResult.developerPayload = purchase.developerPayload
                        googlePayResult.purchaseTime = purchase.purchaseTime.toString()
                        googlePayResult.purchaseState = purchase.purchaseState.toString()
                        googlePayResult.purchaseToken = purchase.purchaseToken
                        //购买成功 消耗掉
                        consume(googlePayResult, purchase)
                    }
                }else{
                    mPayCallBack?.onError("支付异常: google支付成功,未获取到商品结果信息")
                }
            } else if (billingResult.responseCode == BillingResponseCode.ITEM_ALREADY_OWNED) {
                //未消耗掉
                queryPurchases(2)
//                mPayCallBack?.onError("商品未消耗掉 查询补单")
            } else if (billingResult.responseCode == BillingResponseCode.USER_CANCELED) {
                mPayCallBack?.onCancel()
            } else {
                mPayCallBack?.onError("支付异常: code:" + billingResult.responseCode + " msg:" + billingResult.debugMessage)
//                when (billingResult.responseCode) {
//                    BillingResponseCode.SERVICE_TIMEOUT -> {
//                        //服务连接超时
//                    }
//                    BillingResponseCode.FEATURE_NOT_SUPPORTED -> {
//                    }
//                    BillingResponseCode.SERVICE_DISCONNECTED -> {
//                        //服务未连接
//                    }
//                    BillingResponseCode.USER_CANCELED -> {
//                        //取消
//                    }
//                    BillingResponseCode.SERVICE_UNAVAILABLE -> {
//                        //服务不可用
//                    }
//                    BillingResponseCode.BILLING_UNAVAILABLE -> {
//                        //购买不可用
//                    }
//                    BillingResponseCode.ITEM_UNAVAILABLE -> {
//                        //商品不存在
//
//                    }
//                    BillingResponseCode.DEVELOPER_ERROR -> {
//                        //提供给 API 的无效参数
//                    }
//                    BillingResponseCode.ERROR -> {
//                        //错误
//                    }
//                    BillingResponseCode.ITEM_NOT_OWNED -> {
//                        //不可购买
//                    }
//                }
            }
        }

    private var billingClient = BillingClient.newBuilder(AppContext.get())
        .setListener(purchasesUpdatedListener)
        .enablePendingPurchases()
        .build()

    //检查之前的商品是否被消费
    fun init(autoPayCallBack: GooglePayCallBack) {
        mAutoPayCallBack = autoPayCallBack
        //已经连接查询订单
        if (billingClient.isReady) {
            Log.d(TAG, "init 已连接")
            queryPurchases(1)
        } else {
            //开始连接
            Log.d(TAG, "init 开始连接")
            billingClient.startConnection(object : BillingClientStateListener {
                override fun onBillingSetupFinished(billingResult: BillingResult) {
                    if (billingResult.responseCode == BillingResponseCode.OK) {
                        //BillingClient准备好了。你可以在这里查询购买情况。
                        Log.d(TAG, "init 连接成功")
                        queryPurchases(1)
                    } else {
                        Log.d(TAG, "init 连接失败 code:" + billingResult.responseCode)
                        mAutoPayCallBack?.onError("初始化连接失败 code:" + billingResult.responseCode + " msg:" + billingResult.debugMessage)
                    }
                }

                override fun onBillingServiceDisconnected() {
                    Log.d(TAG, "init onBillingServiceDisconnected")
                    mAutoPayCallBack?.onError("初始化连接失败 onBillingServiceDisconnected")
                }
            })
        }
    }

    /**
     * 购买商品
     */
    private fun purchase(mSku: String, orderId: String) {

        EventUtils.onEvent("GooglePayPurchaseS", "预备购买Google商品")

        productId = mSku
        obfuscatedAccountid = orderId
        if (billingClient.isReady) {
            val skuList: MutableList<String> = ArrayList()
            skuList.add(mSku)
            val params = SkuDetailsParams.newBuilder()
            params.setSkusList(skuList).setType(SkuType.INAPP)

            EventUtils.onEvent("GooglePayQuerySkuS", "开始查询Google商品")

            billingClient.querySkuDetailsAsync(
                params.build()
            ) { billingResult, skuDetailsList ->
                // Process the result.
                if (billingResult.responseCode == BillingResponseCode.OK) {
                    if (!skuDetailsList.isNullOrEmpty()) {
                        for (i in 0 until skuDetailsList.size) {
                            val skuDetails = skuDetailsList[i]
                            if (mSku == skuDetails.sku) {
                                val flowParams = BillingFlowParams.newBuilder()
                                    .setSkuDetails(skuDetails)
//                                    .setObfuscatedProfileId()
                                    .setObfuscatedAccountId(orderId)
                                    .build()

                                EventUtils.onEvent(
                                    "GooglePayGotoPayS",
                                    "查询成功，开始吊起Google支付"
                                )
                                //吊起支付
                                val responseCode =
                                    billingClient.launchBillingFlow(
                                        mActivity,
                                        flowParams
                                    ).responseCode
                                Log.d(TAG, "purchase 去支付 code $responseCode")

                                EventUtils.onEvent(
                                    "GooglePayQuerySkuE",
                                    "查询商品结束 吊起支付Code:${responseCode}"
                                )

                                EventUtils.onEvent(
                                    "GooglePayPurchaseE",
                                    "预备购买结束"
                                )
                                break
                            } else {
                                if (i == skuDetailsList.size - 1) {
                                    EventUtils.onEvent(
                                        "GooglePayQuerySkuE",
                                        "查询商品结束 未匹配到对应的商品:${mSku}"
                                    )

                                    mPayCallBack?.onError("GooglePay 未匹配到对应的商品${mSku}")
                                }
                            }
                        }

                    } else {
                        Log.d(TAG, "purchase 未查询到商品")
                        EventUtils.onEvent(
                            "GooglePayQuerySkuE",
                            "未查询到Google商品列表"
                        )

                        mPayCallBack?.onError("GooglePay 未查询到Google商品列表")
                    }
                } else {
                    Log.d(TAG, "purchase 查询连接失败 cede" + billingResult.responseCode)
                    EventUtils.onEvent(
                        "GooglePayQuerySkuE",
                        "商品查询连接失败 cede${billingResult.responseCode}"
                    )

                    mPayCallBack?.onError("GooglePay error code:" + billingResult.responseCode + " msg:" + billingResult.debugMessage)
                }
            }
        } else {
            EventUtils.onEvent(
                "GooglePayPurchaseE",
                "预备购买未连接到Google"
            )
            billingClient.startConnection(object : BillingClientStateListener {
                override fun onBillingSetupFinished(billingResult: BillingResult) {
                    if (billingResult.responseCode == BillingResponseCode.OK) {
                        //BillingClient准备好了。你可以在这里查询购买情况。
                        purchase(mSku, orderId)
                    } else {
                        EventUtils.onEvent(
                            "GooglePayPurchaseE",
                            "预备购买重连失败 code:${billingResult.responseCode}"
                        )

                        mPayCallBack?.onError("purchase 购买 连接失败 code:" + billingResult.responseCode + " msg:" + billingResult.debugMessage)
                    }
                }

                override fun onBillingServiceDisconnected() {
                    EventUtils.onEvent(
                        "GooglePayPurchaseE",
                        "预备购买重连失败 Disconnected"
                    )

                    mPayCallBack?.onError("purchase 购买连接失败 onBillingServiceDisconnected")
                }
            })
        }
    }

    /**
     * 消耗商品
     *
     * @param purchaseToken 商品token
     */
    private fun consume(googlePayResult: GooglePayResult, purchase: Purchase) {
        EventUtils.onEvent(
            "GooglePayConsumeS",
            "支付成功，开始消耗商品"
        )
        if (billingClient.isReady) {
            val consumeParams =
                ConsumeParams.newBuilder()
                    .setPurchaseToken(googlePayResult.purchaseToken)
                    .build()
            billingClient.consumeAsync(
                consumeParams
            ) { billingResult, s ->
                if (billingResult.responseCode == BillingResponseCode.OK) {
                    // Handle the success of the consume operation.
//                    Log.d(TAG, "consume 1消耗成功${googlePayResult.purchaseToken}")
                    EventUtils.onEvent(
                        "GooglePayConsumeE",
                        "消耗商品成功"
                    )
                    //同步后台 消耗掉
                    updateToService(googlePayResult, purchase)
                    productId = ""
                    obfuscatedAccountid = ""
                } else {
                    EventUtils.onEvent(
                        "GooglePayConsumeE",
                        "商品消耗失败 code${billingResult.responseCode}}"
                    )

                    Log.d(TAG, "consume 消耗失败 code:" + billingResult.responseCode)
                    mPayCallBack?.onError("consume 消耗失败 code:" + billingResult.responseCode + " msg:" + billingResult.debugMessage)//支付成功
                }
            }
        } else {
            EventUtils.onEvent(
                "GooglePayConsumeE",
                "消耗商品 未连接Google"
            )
            EventUtils.onEvent(
                "GooglePayConsumeS",
                "支付成功，开始重连消耗商品"
            )
            billingClient.startConnection(object : BillingClientStateListener {
                override fun onBillingSetupFinished(billingResult: BillingResult) {
                    if (billingResult.responseCode == BillingResponseCode.OK) {
                        //重连后 消耗掉
                        val consumeParams =
                            ConsumeParams.newBuilder()
                                .setPurchaseToken(googlePayResult.purchaseToken)
                                .build()
                        billingClient.consumeAsync(
                            consumeParams
                        ) { billingResult, s ->
                            if (billingResult.responseCode == BillingResponseCode.OK) {
                                // Handle the success of the consume operation.
                                Log.d(TAG, "consume 消耗成功${googlePayResult.purchaseToken}")

                                EventUtils.onEvent(
                                    "GooglePayConsumeE",
                                    "重连成功 消耗商品成功"
                                )

                                //同步后台 消耗掉
                                updateToService(googlePayResult, purchase)
                                productId = ""
                                obfuscatedAccountid = ""
                            } else {
                                Log.d(TAG, "consume 消耗失败 code:" + billingResult.responseCode)

                                EventUtils.onEvent(
                                    "GooglePayConsumeE",
                                    "重连成功 消耗商品失败code:${billingResult.responseCode}}"
                                )

                                mPayCallBack?.onError("重连成功 消耗商品失败code:${billingResult.responseCode}")
                            }
                        }
                    } else {
//                        Log.d(TAG, "consume init 连接失败 code:" + billingResult.responseCode)
                        EventUtils.onEvent(
                            "GooglePayConsumeE",
                            "消耗商品 重连失败code:${billingResult.responseCode}"
                        )

                        mPayCallBack?.onError("consume 消耗连接失败 code:" + billingResult.responseCode + " msg:" + billingResult.debugMessage)
                    }
                }

                override fun onBillingServiceDisconnected() {
                    // Try to restart the connection on the next request to
                    // Google Play by calling the startConnection() method.
                    EventUtils.onEvent(
                        "GooglePayConsumeE",
                        "消耗商品重连失败 Disconnected"
                    )

                    mPayCallBack?.onError("consume onBillingServiceDisconnected")
                }
            })
        }
    }

    /**
     * 补单消耗商品
     *
     * @param purchaseToken 商品token
     */
    private fun consume2(googlePayResult: GooglePayResult, purchase: Purchase) {
        if (billingClient.isReady) {
            val consumeParams =
                ConsumeParams.newBuilder()
                    .setPurchaseToken(purchase.purchaseToken)
                    .build()
            billingClient.consumeAsync(
                consumeParams
            ) { billingResult, s ->
                if (billingResult.responseCode == BillingResponseCode.OK) {
                    // Handle the success of the consume operation.
                    Log.d(TAG, "consume 消耗成功${purchase.purchaseToken}")
                    //同步后台 消耗掉
                    updateToService2(googlePayResult, purchase)
                } else {
                    mAutoPayCallBack?.onError("补单消耗失败 code:${billingResult.responseCode} msg:${billingResult.debugMessage}")
                }
            }
        } else {
            billingClient.startConnection(object : BillingClientStateListener {
                override fun onBillingSetupFinished(billingResult: BillingResult) {
                    if (billingResult.responseCode == BillingResponseCode.OK) {
                        //重连后 消耗掉
                        val consumeParams =
                            ConsumeParams.newBuilder()
                                .setPurchaseToken(purchase.purchaseToken)
                                .build()
                        billingClient.consumeAsync(
                            consumeParams
                        ) { billingResult, s ->
                            if (billingResult.responseCode == BillingResponseCode.OK) {
                                // Handle the success of the consume operation.
                                Log.d(TAG, "consume 消耗成功${purchase.purchaseToken}")
                                //同步后台 消耗掉
                                updateToService2(googlePayResult, purchase)
                            } else {
                                mAutoPayCallBack?.onError("重连 补单消耗失败 code:${billingResult.responseCode} msg:${billingResult.debugMessage}")
                            }
                        }
                    } else {
                        mAutoPayCallBack?.onError("补单 连接失败 Error code:${billingResult.responseCode} msg:${billingResult.debugMessage}")
                    }
                }

                override fun onBillingServiceDisconnected() {
                    mAutoPayCallBack?.onError("补单 连接失败 Error onBillingServiceDisconnected")
                }
            })
        }
    }

    /**
     * 补单操作 查询购买交易，以确保所有购买交易都得到成功处理，如购买未发货，或者未消耗
     * type 1 初始化查询补单 2 实时支付成功回调补单
     */
    private fun queryPurchases(type: Int) {
        if (billingClient.isReady) {
            billingClient.queryPurchasesAsync(
                SkuType.INAPP
            ) { billingResult, mutableList ->
                if (billingResult.responseCode == BillingResponseCode.OK) {
                    if (mutableList.isNullOrEmpty()) {
                        if (type == 2) {
                            mPayCallBack?.onError("GooglePay支付回调补单未查询到需补单的商品")
                        }
                    } else {
                        for (i in 0 until mutableList.size) {
                            if (mutableList[i].purchaseState == Purchase.PurchaseState.PURCHASED) {
                                val purchase = mutableList[i];
                                val googleJson = JSONObject(purchase.originalJson)
                                val proId = googleJson.optString("productId") ?: ""
                                val accountId = googleJson.optString("obfuscatedAccountId") ?: ""
                                var googlePayResult = GooglePayResult()
                                googlePayResult.packageName = purchase.packageName
                                googlePayResult.orderId = purchase.orderId
                                googlePayResult.productId = proId
                                googlePayResult.obfuscatedAccountid = accountId
                                googlePayResult.developerPayload = purchase.developerPayload
                                googlePayResult.purchaseTime = purchase.purchaseTime.toString()
                                googlePayResult.purchaseState =
                                    purchase.purchaseState.toString()
                                googlePayResult.purchaseToken = purchase.purchaseToken
                                if (type == 2) {
                                    //已购买,消耗即可
                                    consume(googlePayResult, purchase)
                                } else if (type == 1) {
                                    //之前已购买,消耗即可
                                    consume2(googlePayResult, purchase)
                                }
                            } else {
                                if (i == mutableList.size - 1) {
                                    if (type == 2) {
                                        mPayCallBack?.onError("GooglePay支付回调补单商品状态异常 status${mutableList[i].purchaseState}")
                                    } else if (type == 1) {
                                        mAutoPayCallBack?.onError("GooglePay初始化查询补单商品状态异常 status${mutableList[i].purchaseState}")
                                    }
                                }
                            }
                        }
                    }
                } else {
                    if (type == 2) {
                        mPayCallBack?.onError("GooglePay支付补单查询异常 code${billingResult.responseCode} msg:${billingResult.debugMessage}")
                    } else if (type == 1) {
                        mAutoPayCallBack?.onError("GooglePay初始化补单查询异常 code${billingResult.responseCode} msg:${billingResult.debugMessage}")
                    }
                }
            }
        } else {
            billingClient.startConnection(object : BillingClientStateListener {
                override fun onBillingSetupFinished(billingResult: BillingResult) {
                    if (billingResult.responseCode == BillingResponseCode.OK) {
                        //BillingClient准备好了。你可以在这里查询购买情况。
                        billingClient.queryPurchasesAsync(
                            SkuType.INAPP
                        ) { billingResult, mutableList ->
                            if (billingResult.responseCode == BillingResponseCode.OK) {
                                if (mutableList.isNullOrEmpty()) {
                                    if (type == 2) {
                                        mPayCallBack?.onError("GooglePay支付回调补单未查询到需补单的商品")
                                    }
                                } else {
                                    for (i in 0 until mutableList.size) {
                                        if (mutableList[i].purchaseState == Purchase.PurchaseState.PURCHASED) {
                                            val purchase = mutableList[i];
                                            var googlePayResult = GooglePayResult()
                                            val googleJson = JSONObject(purchase.originalJson)
                                            val proId = googleJson.optString("productId") ?: ""
                                            val accountId =
                                                googleJson.optString("obfuscatedAccountId") ?: ""
                                            googlePayResult.packageName = purchase.packageName
                                            googlePayResult.orderId = purchase.orderId
                                            googlePayResult.productId = proId
                                            googlePayResult.obfuscatedAccountid = accountId
                                            googlePayResult.developerPayload =
                                                purchase.developerPayload
                                            googlePayResult.purchaseTime =
                                                purchase.purchaseTime.toString()
                                            googlePayResult.purchaseState =
                                                purchase.purchaseState.toString()
                                            googlePayResult.purchaseToken = purchase.purchaseToken
                                            if (type == 2) {
                                                //已购买,消耗即可
                                                consume(googlePayResult, purchase)
                                            } else if (type == 1) {
                                                //之前已购买,消耗即可
                                                consume2(googlePayResult, purchase)
                                            }
                                        } else {
                                            if (i == mutableList.size - 1) {
                                                if (type == 2) {
                                                    mPayCallBack?.onError("GooglePay支付回调补单商品状态异常 status${mutableList[i].purchaseState}")
                                                } else if (type == 1) {
                                                    mAutoPayCallBack?.onError("GooglePay初始化查询补单商品状态异常 status${mutableList[i].purchaseState}")
                                                }
                                            }
                                        }
                                    }
                                }
                            } else {
                                if (type == 2) {
                                    mPayCallBack?.onError("GooglePay支付补单查询异常 code${billingResult.responseCode} msg:${billingResult.debugMessage}")
                                } else if (type == 1) {
                                    mAutoPayCallBack?.onError("GooglePay初始化补单查询异常 code${billingResult.responseCode} msg:${billingResult.debugMessage}")
                                }
                            }
                        }
                    } else {
                        if (type == 2) {
                            mPayCallBack?.onError("GooglePay支付补单查询重连 连接异常 code${billingResult.responseCode} msg:${billingResult.debugMessage}")
                        } else if (type == 1) {
                            mAutoPayCallBack?.onError("GooglePay初始化补单查询重连 连接异常 code${billingResult.responseCode} msg:${billingResult.debugMessage}")
                        }
                    }
                }

                override fun onBillingServiceDisconnected() {
                    // Try to restart the connection on the next request to
                    // Google Play by calling the startConnection() method.
                    if (type == 2) {
                        mPayCallBack?.onError("GooglePay支付补单查询连接异常 重连失败 onBillingServiceDisconnected")
                    } else if (type == 1) {
                        mAutoPayCallBack?.onError("GooglePay初始化补单查询连接异常 重连失败 onBillingServiceDisconnected")
                    }
                }
            })
        }
    }

    /**
     * google支付
     */
    fun googlePay(goodsId: String, payMode: String, payCallBack: GooglePayCallBack) {

        EventUtils.onEvent("GooglePayGetOrderIdS", "获取订单号")

        mPayCallBack = payCallBack
        //向服务端获取订单ID
        ApiClient.userInfoAPi.googlePay(goodsId, "4", "", "", payMode)
            .compose(RxSchedulers.observableIO2Main())
            .subscribe(object : BaseObserver<GooglePayEntity>() {
                override fun onSuccess(result: GooglePayEntity?) {
                    if (result != null) {

                        EventUtils.onEvent("GooglePayGetOrderIdE", "获取订单号_成功")

                        var sku = goodsId.replace("-", "_")
                        purchase("xymh_$sku", result.outTradeNo ?: "")

                    } else {

                        EventUtils.onEvent(
                            "GooglePayGetOrderIdE",
                            "未获取到订单数据"
                        )

                        mPayCallBack?.onError("GooglePay 未获取到订单数据")
                    }
                }

                override fun onFailure(e: Throwable?, code: String?, errorMsg: String?) {

                    EventUtils.onEvent(
                        "GooglePayGetOrderIdE",
                        "获取订单号接口异常:$errorMsg"
                    )

                    mPayCallBack?.onError("订单接口 Error:$errorMsg")
                }
            })
    }

    /**
     * google支付 成功后 同步给服务器
     */
    private fun updateToService(googlePayResult: GooglePayResult, purchase: Purchase) {
        EventUtils.onEvent(
            "GooglePayToServiceS",
            "google支付成功，开始同步后端校验"
        )
        //支付成功 向后端同步 网络问题再次重试
        ApiClient.shopApi.googlePaySuccess(googlePayResult)
            .compose(RxSchedulers.observableIO2Main())
            .subscribe(object : BaseObserver<Any>() {
                override fun onSuccess(result: Any?) {
//                    EventUtils.onEvent("googlepaysuccess_onsuccess")

                    EventUtils.onEvent(
                        "GooglePayToServiceE",
                        "google支付成功，后端校验成功"
                    )

                    mPayCallBack?.onPaySuccess(googlePayResult, purchase.originalJson)//支付成功
                }

                override fun onFailure(e: Throwable?, code: String?, errorMsg: String?) {
//                    EventUtils.onEvent("googlepaysuccess_onfailure", "${errorMsg}")

                    EventUtils.onEvent(
                        "GooglePayToServiceE",
                        "google支付成功，后端校验失败 code:$code msg:$errorMsg"
                    )

                    mPayCallBack?.onError("服务器同步失败 code:$code msg:$errorMsg")
                }
            })
    }

    /**
     * google支付 成功后 补单消耗 同步给服务器
     */
    private fun updateToService2(googlePayResult: GooglePayResult, purchase: Purchase) {
        //支付成功 向后端同步 网络问题再次重试
        ApiClient.shopApi.googlePaySuccess(googlePayResult)
            .compose(RxSchedulers.observableIO2Main())
            .subscribe(object : BaseObserver<Any>() {
                override fun onSuccess(result: Any?) {
//                    EventUtils.onEvent("googlepaysuccess_onsuccess")
                    mAutoPayCallBack?.onPaySuccess(googlePayResult, purchase.originalJson)//补单支付成功
                }

                override fun onFailure(e: Throwable?, code: String?, errorMsg: String?) {
//                    EventUtils.onEvent("googlepaysuccess_onfailure", "${errorMsg}")
                    mAutoPayCallBack?.onError("补单 服务器同步失败 code:$code msg:$errorMsg")
                }
            })
    }


    fun release() {
        if (billingClient.isReady) {
            billingClient.endConnection();
        }
        mPayCallBack = null
        mAutoPayCallBack = null
        Log.d(TAG, "billingClient release")
    }

}