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 java.lang.Exception

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

    val listener = ArrayList<IPayCallback>()
    private const val publicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA184P/HXDtDi+3NgrxRkwIRU6tI2tiodETDzIyA/uwqgKwl/9JgXw2fZEFlsbEv1rUCVvvFGLGo7Z1GrUoR7WUAPktIuMWF330BurThfiwkpkSamzHEe+Pk/98/1YjZ8ltF2xaunUHZhRuE2WonrTy/rFvv/9PZtYd0xNFN5yOQwzFmT5nJvtpfCDWe2OhHXxuswG1bBn+faCcE0Rg1ZkSi36+0gDVvGjX/zQDgsXhwGJqFdVaJu7E7iR4zEGZLHquA931M0gYgGuF/tO9h8ppcaP1N7yR/ibek6KLcs969P47ENlRaL1QnrB3MSbomhhrtAzDLlV8YEIlukzsLrR7wIDAQAB"

    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)
                            }
                        }
                        listener.forEach {
                            it.onPaySuccess(list)
                        }
                    }

                    BillingClient.BillingResponseCode.USER_CANCELED -> {
                        listener.forEach {
                            it.onPayCancel()
                        }
                    }

                    else -> {
                        listener.forEach {
                            it.onPayError(billingResult.responseCode)
                        }
                    }
                }
            }.build()

        billingClient?.startConnection(object : BillingClientStateListener {
            override fun onBillingSetupFinished(p0: BillingResult) {
                if (p0.responseCode == BillingClient.BillingResponseCode.OK) {
                    isConnected = true
                    listener.forEach {
                        it.onConnectedServer()
                        LogUtil.d("链接到谷歌")
                    }
                    queryUnConsumeOrder("")
                } else {
                    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 params = SkuDetailsParams.newBuilder()
        params.setSkusList(list).setType(BillingClient.SkuType.INAPP)
        billingClient?.querySkuDetailsAsync(params.build()) { 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 -> {
                    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 -> {
                    listener.forEach {
                        it.consumeOrderSuccess()
                    }
                }

                else -> {
                    listener.forEach {
                        it.consumeOrderFail(billingResult.responseCode)
                    }
                }
            }
        }
    }

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

                }

                else -> {
                    listener.forEach { callback ->
                        callback.onPayError(result.responseCode)
                    }
                }

            }
        }
    }

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

                    else -> {
                        listener.forEach { callback ->
                            callback.onPayError(billingResult.responseCode)
                        }
                    }
                }
            }
        }
    }


    private fun startPay(skuDetails: SkuDetails, userId: String, orderId: String) {
        try {
            val skuDetails = SkuDetails(skuDetails.originalJson)
            val flowParams = BillingFlowParams.newBuilder()
                .setObfuscatedAccountId(userId)
                .setObfuscatedProfileId(orderId)
                .setSkuDetails(skuDetails)
                .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)
        }
    }

}
