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.uc.AliPayEntity
import com.zxhl.cms.pay.alipay.AlipayServer
import com.zxhl.cms.utils.EventUtils


/**
 * @author (wangXuewei)
 * @datetime 2022-03-09 15:12 GMT+8
 * @detail :
 */
class GooglePayHelper {
    private val TAG = "GooglePayHelper"
    private var mActivity: Activity;
    private var mSku: String = "box0001"

    constructor(mActivity: Activity, mSku: String) {
        this.mActivity = mActivity
//        this.mSku = mSku
    }

    /**
     * 购买监听
     */
    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}")
            if (billingResult.responseCode == BillingResponseCode.OK) {
                //支付成功 同步后台
                if (!purchases.isNullOrEmpty()) {
                    for (i in 0 until purchases.size) {
                        updateToService()
                    }
                }
            } else if (billingResult.responseCode == BillingResponseCode.ITEM_ALREADY_OWNED) {
                //未消耗掉
                //mConsume = "1"
                queryPurchases()
            } else {
                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() {
        //已经连接查询订单
        if (billingClient.isReady) {
            Log.d(TAG, "init 已连接")
            getOrderId()
        } else {
            //开始连接
            Log.d(TAG, "init 开始连接")
            billingClient.startConnection(object : BillingClientStateListener {
                override fun onBillingSetupFinished(billingResult: BillingResult) {
                    if (billingResult.responseCode == BillingResponseCode.OK) {
                        //BillingClient准备好了。你可以在这里查询购买情况。
                        Log.d(TAG, "init 连接成功")
                        getOrderId()
                    } else {
                        Log.d(TAG, "init 连接失败 code:" + billingResult.responseCode)
                    }
                }

                override fun onBillingServiceDisconnected() {
                    // Try to restart the connection on the next request to
                    // Google Play by calling the startConnection() method.
                    Log.d(TAG, "init onBillingServiceDisconnected")
                }
            })
        }

    }

    /**
     * 购买商品
     */
    private fun purchase() {
        if (billingClient.isReady) {
            val skuList: MutableList<String> = ArrayList()
            skuList.add(mSku)
            val params = SkuDetailsParams.newBuilder()
            params.setSkusList(skuList).setType(SkuType.INAPP)
            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]
                            Log.d(TAG, "purchase skuDetails $skuDetails")
                            if (mSku == skuDetails.sku) {
                                val flowParams = BillingFlowParams.newBuilder()
                                    .setSkuDetails(skuDetails)
//                                    .setObfuscatedProfileId()
//                                    .setObfuscatedAccountId()
                                    .build()
                                //吊起支付
                                val responseCode =
                                    billingClient.launchBillingFlow(
                                        mActivity,
                                        flowParams
                                    ).responseCode
                                Log.d(TAG, "purchase 去支付 code $responseCode")
                            }
                        }

                    } else {
                        Log.d(TAG, "purchase 未查询到商品")
                    }
                } else {
                    Log.d(TAG, "purchase 查询连接失败 cede" + billingResult.responseCode)
                }
            }
        }
    }

    /**
     * 消耗商品
     *
     * @param purchaseToken 商品token
     */
    private fun consume(purchaseToken: String) {
        if (billingClient.isReady) {
            val consumeParams =
                ConsumeParams.newBuilder()
                    .setPurchaseToken(purchaseToken)
                    .build()
            billingClient.consumeAsync(
                consumeParams
            ) { billingResult, s ->
                if (billingResult.responseCode == BillingResponseCode.OK) {
                    // Handle the success of the consume operation.
                    Log.d(TAG, "consume 消耗成功$purchaseToken")
                } else {
                    Log.d(TAG, "consume 消耗失败 code:" + billingResult.responseCode)
                }
            }
        } else {
            billingClient.startConnection(object : BillingClientStateListener {
                override fun onBillingSetupFinished(billingResult: BillingResult) {
                    if (billingResult.responseCode == BillingResponseCode.OK) {
                        //重连后 消耗掉
                        val consumeParams =
                            ConsumeParams.newBuilder()
                                .setPurchaseToken(purchaseToken)
                                .build()
                        billingClient.consumeAsync(
                            consumeParams
                        ) { billingResult, s ->
                            if (billingResult.responseCode == BillingResponseCode.OK) {
                                // Handle the success of the consume operation.
                                Log.d(TAG, "consume 消耗成功$purchaseToken")
                            } else {
                                Log.d(TAG, "consume 消耗失败 code:" + billingResult.responseCode)
                            }
                        }
                    } else {
                        Log.d(TAG, "consume init 连接失败 code:" + billingResult.responseCode)
                    }
                }

                override fun onBillingServiceDisconnected() {
                    // Try to restart the connection on the next request to
                    // Google Play by calling the startConnection() method.
                    Log.d(TAG, "consume init onBillingServiceDisconnected")
                }
            })
        }
    }

    /**
     * 补单操作 查询购买交易，以确保所有购买交易都得到成功处理，如购买未发货，或者未消耗
     */
    private fun queryPurchases() {
        if (billingClient.isReady) {
            billingClient.queryPurchasesAsync(
                SkuType.INAPP
            ) { billingResult, mutableList ->
                if (billingResult.responseCode == BillingResponseCode.OK) {
                    if (mutableList.isNullOrEmpty()) {
                        Log.d(TAG, "queryPurchases null")
                    } else {
                        for (i in 0 until mutableList.size) {
                            Log.d(TAG, "queryPurchases init " + mutableList[i].purchaseState)
                            if (mutableList[i].isAcknowledged) {
                                //已确认/已验证,消耗即可
                                consume(mutableList[i].purchaseToken)
                                if (mutableList[i].purchaseState == Purchase.PurchaseState.PURCHASED) {

                                }

                            } else {
                                //后端同步
                                //支付成功后 google回调没有收到 再次检查 后端同步
                            }
                        }
                    }
                } else {
                    Log.d(TAG, "queryPurchases null")
                }
            }
        } else {
            billingClient.startConnection(object : BillingClientStateListener {
                override fun onBillingSetupFinished(billingResult: BillingResult) {
                    if (billingResult.responseCode == BillingResponseCode.OK) {
                        //BillingClient准备好了。你可以在这里查询购买情况。
                        Log.d(TAG, "queryPurchases init 连接成功")
                    } else {
                        Log.d(TAG, "queryPurchases init 连接失败 code:" + billingResult.responseCode)
                    }
                }

                override fun onBillingServiceDisconnected() {
                    // Try to restart the connection on the next request to
                    // Google Play by calling the startConnection() method.
                    Log.d(TAG, "queryPurchases init onBillingServiceDisconnected")
                }
            })
        }
    }


    fun getOrderId() {
        //向服务端获取订单ID
        ApiClient.userInfoAPi.aliPay("39", "4", "", "", "6")
            .compose(RxSchedulers.observableIO2Main())
            .subscribe(object : BaseObserver<AliPayEntity>() {
                override fun onSuccess(result: AliPayEntity?) {

                }

                override fun onFailure(e: Throwable?, code: String?, errorMsg: String?) {
                    EventUtils.onEvent("member_page_pay_get_order_fail")
                }
            })
        purchase()
    }

    fun updateToService() {
        //支付成功 向后端同步 网络问题再次重试

        //同步成功 消耗掉
        consume("")

    }


    fun release() {
        if (billingClient.isReady) {
            billingClient.endConnection();
        }
    }

}