package com.swago.baseswago.libpay

import com.android.billingclient.api.*
import com.swago.baseswago.model.pay.PayModel
import com.swago.baseswago.util.ActivityManagerUtil
import com.swago.baseswago.util.AppContext
import com.swago.baseswago.util.LogUtil
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.lang.Exception

/**
 *@date 2021/11/8 20:13
 *description:
 */
object PayManager {

    val listener = ArrayList<IPayCallback>()
    private const val publicKey =
        "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAte27P9rNKgmkq7re77YpJi2f8wdr/Lullm02zJFCvQTyr0IKdAaRkDkW+2NagoKjpaVrBeF3RYr+a1NneUWeKL7u9S6ihXBOje+/+XgPbQ57HsB8s6bQcKK99Qw1aBRgnPKYm9ETnQ36v9i70MtFWxLY7OYoraIZN36hfYAELwJYZtSSbO8aLabKdEZYzikNGkUUNYALiX14BnH2O70N0NQxddR+OhG1IcnyUyTQimx/Wf/IaBVz9ere0xf4uP7HJaJhVxW32mg9Tyk9n851oJupuaPEn9n6jD2Dirmx3jzzQTWneD8IM5IVGrfak9zirrGz8CYynX7sU6ih0GKpFwIDAQAB"

    private var isConnected = false
    private var billingClient: BillingClient? = null

    fun init() {
        if (billingClient != null) return
        billingClient = BillingClient.newBuilder(AppContext.getContext()).enablePendingPurchases()
            .setListener { billingResult, data ->
                when (billingResult.responseCode) {
                    BillingClient.BillingResponseCode.OK -> {
                        val list: MutableList<Purchase> = ArrayList()
                        data?.forEach {
                            if (Security.verify(
                                    Security.generatePublicKey(publicKey),
                                    it.originalJson,
                                    it.signature
                                )
                            ) {
                                list.add(it)
                            }
                        }

                        GlobalScope.launch(Dispatchers.Main) {
                            listener.forEach {
                                it.onPaySuccess(list)
                            }
                        }
                    }

                    BillingClient.BillingResponseCode.USER_CANCELED -> {
                        GlobalScope.launch(Dispatchers.Main) {
                            listener.forEach {
                                it.onPayCancel()
                            }
                        }
                    }

                    else -> {
                        GlobalScope.launch(Dispatchers.Main) {
                            listener.forEach {
                                it.onPayError(billingResult.responseCode)
                            }
                        }
                    }
                }
            }.build()

        billingClient?.startConnection(object : BillingClientStateListener {
            override fun onBillingSetupFinished(p0: BillingResult) {
                if (p0.responseCode == BillingClient.BillingResponseCode.OK) {
                    isConnected = true
                    GlobalScope.launch(Dispatchers.Main) {
                        listener.forEach {
                            it.onConnectedServer()
                            LogUtil.d("链接到谷歌")
                        }
                    }
                    queryUnConsumeOrder("")
                } else {
                    GlobalScope.launch(Dispatchers.Main) {
                        listener.forEach {
                            it.onPayError(p0.responseCode)
                        }
                    }
                }
            }

            override fun onBillingServiceDisconnected() {
                isConnected = false
            }

        })
    }


    fun queryProductPrice(dataNet: List<PayModel>) {
        val list = ArrayList<String>()
        dataNet.forEach {
            list.add(it.google_product_id)
        }
        val skuDetailParams = SkuDetailsParams.newBuilder()
            .setType(BillingClient.SkuType.INAPP)
            .setSkusList(list)
            .build()
        billingClient?.querySkuDetailsAsync(skuDetailParams) { billingResult, data ->
            when (billingResult.responseCode) {
                BillingClient.BillingResponseCode.OK -> {
                    data?.let {
                        if (it.isNotEmpty()) {
                            it.forEach { skuDetails ->
                                dataNet.forEach {  dataSkuDetails ->
                                    if(skuDetails.sku == dataSkuDetails.google_product_id){
                                        dataSkuDetails.product_price = skuDetails.price
                                    }
                                }
                            }
                            listener.forEach {
                                it.onQueryProductPrice(dataNet)
                            }
                        }else{
                            listener.forEach {
                                //未查询到商品
                                it.onPayError(-5)
                            }
                        }
                    }
                }

                else -> {
                    GlobalScope.launch(Dispatchers.Main) {
                        listener.forEach {
                            it.onPayError(billingResult.responseCode)
                        }
                    }
                }
            }
        }
    }


    fun consumeOrder(purchase: Purchase) {
        val params = ConsumeParams.newBuilder()
            .setPurchaseToken(purchase.purchaseToken)
            .build()
        billingClient?.consumeAsync(params) { billingResult, data ->
            when (billingResult.responseCode) {
                BillingClient.BillingResponseCode.OK -> {
                    GlobalScope.launch(Dispatchers.Main) {
                        listener.forEach {
                            it.consumeOrderSuccess()
                        }
                    }
                }

                else -> {
                    GlobalScope.launch(Dispatchers.Main) {
                        listener.forEach {
                            it.consumeOrderFail(billingResult.responseCode)
                        }
                    }
                }
            }
        }
    }

    /**
     * productId  谷歌商品id
     */
    fun queryUnConsumeOrder(productId: String) {
        billingClient?.let {
            it.queryPurchasesAsync(BillingClient.SkuType.INAPP) { billingResult, list ->
                when (billingResult.responseCode) {
                    BillingClient.BillingResponseCode.OK -> {
                        if (list.size != 0) {
                            val unConsumePurchase: MutableList<Purchase> = ArrayList()
                            list.onEach { purchase ->
                                if (Security.verify(
                                        Security.generatePublicKey(publicKey),
                                        purchase.originalJson,
                                        purchase.signature
                                    ) && purchase.purchaseState == 1
                                ) {
                                    unConsumePurchase.add(purchase)
                                }
                            }
                            GlobalScope.launch(Dispatchers.Main) {
                                listener.forEach { callback ->
                                    callback.onUnConsumeOrder(unConsumePurchase)
                                }
                            }
                        } else {
                            /**
                             * 不存在未消费
                             * 当productId空字符串的时候
                             * 代表着只是查询未消费订单
                             * 当productId不为空字符串，
                             * 代表着此时没有未消费的订单
                             * 然后去创建新的订单购买商品
                             */
                            if (productId.isNotEmpty()) {
                                GlobalScope.launch(Dispatchers.Main) {
                                    listener.forEach { callback ->
                                        callback.toCreateNewOrder(productId)
                                    }
                                }
                            }
                        }

                    }

                    else -> {
                        GlobalScope.launch(Dispatchers.Main) {
                            listener.forEach { callback ->
                                callback.onPayError(billingResult.responseCode)
                            }
                        }
                    }

                }
            }
        }
    }

    private fun queryProductIsExit(data: ArrayList<String>, userId: String, orderId: String) {
        val params = SkuDetailsParams.newBuilder()
        params.setSkusList(data).setType(BillingClient.SkuType.INAPP)
        billingClient?.querySkuDetailsAsync(params.build()) { billingResult, dataX ->
            when (billingResult.responseCode) {
                BillingClient.BillingResponseCode.OK -> {
                    //查询到商品然后支付
                    dataX?.onEach { productDetails ->
                        startPay(productDetails, userId, orderId)
                    }
                }

                else -> {
                    GlobalScope.launch(Dispatchers.Main) {
                        listener.forEach { callback ->
                            callback.onPayError(billingResult.responseCode)
                        }
                    }
                }
            }
        }
    }


    private fun startPay(productDetails: SkuDetails, userId: String, orderId: String) {
        try {
            // Retrieve a value for "skuDetails" by calling querySkuDetailsAsync().
            val flowParams = BillingFlowParams.newBuilder()
                .setObfuscatedAccountId(userId)
                .setObfuscatedProfileId(orderId)
                .setSkuDetails(productDetails)
                .build()
            billingClient?.launchBillingFlow(
                ActivityManagerUtil.get().currentActivity(),
                flowParams
            )
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }


    fun pay(productId: String, userId: String, orderId: String) {
        if (isConnected) {
            val idList = ArrayList<String>()
            idList.add(productId)
            //先去查ID对应的商品是否存在存在才去支付
            queryProductIsExit(idList, userId, orderId)
        }
    }

}
