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


/**
 * @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 = ""

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

    /**
     * 购买监听
     */
    private val purchasesUpdatedListener =
        PurchasesUpdatedListener { billingResult, purchases ->
            // To be implemented in a later section.
        }

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

    fun init() {
        //已经连接查询订单
        if (billingClient.isReady) {
            Log.d(TAG, "init 已连接")
            purchase()
        } else {
            //开始连接
            Log.d(TAG, "init 开始连接")
            billingClient.startConnection(object : BillingClientStateListener {
                override fun onBillingSetupFinished(billingResult: BillingResult) {
                    if (billingResult.responseCode == BillingClient.BillingResponseCode.OK) {
                        //BillingClient准备好了。你可以在这里查询购买情况。
                        Log.d(TAG, "init 连接成功")
                        //查询商品购买
                        purchase()
                    }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() {
        val skuList: MutableList<String> = ArrayList()
        skuList.add("premium_upgrade")
        skuList.add("gas")
        val params = SkuDetailsParams.newBuilder()
        params.setSkusList(skuList).setType(SkuType.INAPP)
        billingClient.querySkuDetailsAsync(
            params.build()
        ) { billingResult, skuDetailsList ->
            // Process the result.
            Log.d(TAG, "purchase billingResult " + billingResult.responseCode)

            if (billingResult.responseCode == BillingClient.BillingResponseCode.OK && !skuDetailsList.isNullOrEmpty()) {
                val skuDetails = skuDetailsList[0]
                val flowParams = BillingFlowParams.newBuilder()
                    .setSkuDetails(skuDetails)
                    .build()
                val responseCode =
                    billingClient.launchBillingFlow(mActivity, flowParams).responseCode
                Log.d(TAG, "purchase 去支付 code $responseCode")
            } else {
                Log.d(TAG, "purchase 查询失败")
            }
        }

    }

    fun handlePurchase(purchase: Purchase) {
// Purchase retrieved from BillingClient#queryPurchasesAsync or your PurchasesUpdatedListener.

        // Verify the purchase.
        // Ensure entitlement was not already granted for this purchaseToken.
        // Grant entitlement to the user.

        val consumeParams = ConsumeParams.newBuilder()
            .setPurchaseToken(purchase.purchaseToken)
            .build()

        val listener =
            ConsumeResponseListener { billingResult, purchaseToken ->
                if (billingResult.responseCode == BillingResponseCode.OK) {
                    // Handle the success of the consume operation.
                }
            }

        billingClient.consumeAsync(consumeParams, listener)

    }
}