//package com.base.filerecoveryrecyclebin.billing
//
//import android.content.Context
//import android.util.Log
//import androidx.lifecycle.DefaultLifecycleObserver
//import androidx.lifecycle.LifecycleOwner
//import androidx.lifecycle.MutableLiveData
//import com.android.billingclient.api.BillingClient
//import com.android.billingclient.api.BillingClientStateListener
//import com.android.billingclient.api.BillingResult
//import com.android.billingclient.api.ProductDetails
//import com.android.billingclient.api.ProductDetailsResponseListener
//import com.android.billingclient.api.Purchase
//import com.android.billingclient.api.PurchasesResponseListener
//import com.android.billingclient.api.PurchasesUpdatedListener
//import com.android.billingclient.api.QueryPurchasesParams
//import com.base.filerecoveryrecyclebin.bean.BiliConstants
//import com.base.filerecoveryrecyclebin.bean.BillingResponse
//import com.base.filerecoveryrecyclebin.help.BaseApplication
//import kotlinx.coroutines.CoroutineScope
//import kotlinx.coroutines.Dispatchers
//import kotlinx.coroutines.SupervisorJob
//import kotlinx.coroutines.flow.MutableStateFlow
//import kotlinx.coroutines.flow.asStateFlow
//import kotlinx.coroutines.launch
//
//class BillingClientLifecycle(
//    private val applicationContext: Context,
//    private val coroutineScope: CoroutineScope = CoroutineScope(SupervisorJob() + Dispatchers.Default)
//) : DefaultLifecycleObserver,
//    PurchasesUpdatedListener,
//    BillingClientStateListener,
//    PurchasesResponseListener,
//    ProductDetailsResponseListener {
//
//    private val TAG = "BillingClientLifecycle"
//
//    /**
//     * Instantiate a new BillingClient instance.
//     */
//    private lateinit var billingClient: BillingClient
//
//    //订阅价格
//    private val _subscriptionPurchases = MutableStateFlow<List<Purchase>>(emptyList())
//    val subscriptionPurchases = _subscriptionPurchases.asStateFlow()
//
//    //基础商品信息
//    val basicSubProductWithProductDetails = MutableLiveData<ProductDetails?>()
//
//    //高级商品信息
//    val premiumSubProductWithProductDetails = MutableLiveData<ProductDetails?>()
//
//
//    override fun onCreate(owner: LifecycleOwner) {
//        Log.d(TAG, "onCreate")
//        billingClient = BillingClient.newBuilder(BaseApplication.context)
//            .setListener(this)
////            .enablePendingPurchases() // Not used for subscriptions.
//            .build()
//        if (!billingClient.isReady) {
//            Log.d(TAG, "BillingClient: Start connection...")
//            billingClient.startConnection(this)
//        }
//    }
//
//    override fun onDestroy(owner: LifecycleOwner) {
//        Log.d(TAG, "onDestroy")
//        if (billingClient.isReady) {
//            Log.d(TAG, "BillingClient can only be used once -- closing connection")
//            // BillingClient can only be used once.
//            // After calling endConnection(), we must create a new BillingClient.
//            billingClient.endConnection()
//        }
//    }
//
//    /**
//     * 更新价格监听
//     * PurchasesUpdatedListener
//     */
//    override fun onPurchasesUpdated(billingResult: BillingResult, purchases: MutableList<Purchase>?) {
//        val responseCode = billingResult.responseCode
//        val debugMessage = billingResult.debugMessage
//
//        Log.d(TAG, "onPurchasesUpdated: $responseCode $debugMessage")
//        when (responseCode) {
//            BillingClient.BillingResponseCode.OK -> {
//                if (purchases == null) {
//                    Log.d(TAG, "onPurchasesUpdated: null purchase list")
//                    processPurchases(null)
//                } else {
//                    processPurchases(purchases)
//                }
//            }
//
//            BillingClient.BillingResponseCode.USER_CANCELED -> {
//                Log.i(TAG, "onPurchasesUpdated: User canceled the purchase")
//            }
//
//            BillingClient.BillingResponseCode.ITEM_ALREADY_OWNED -> {
//                Log.i(TAG, "onPurchasesUpdated: The user already owns this item")
//            }
//
//            BillingClient.BillingResponseCode.DEVELOPER_ERROR -> {
//                Log.e(
//                    TAG, "onPurchasesUpdated: Developer error means that Google Play does " +
//                            "not recognize the configuration. If you are just getting started, " +
//                            "make sure you have configured the application correctly in the " +
//                            "Google Play Console. The product ID must match and the APK you " +
//                            "are using must be signed with release keys."
//                )
//            }
//        }
//    }
//
//    private var cachedPurchasesList: List<Purchase>? = null
//
//    /**
//     * 重新发布价格
//     */
//    private fun processPurchases(purchasesList: List<Purchase>?) {
//        purchasesList?.let { list ->
//            if (isUnchangedPurchaseList(list)) {
//                Log.d(TAG, "processPurchases: Purchase list has not changed")
//                return
//            }
//
//            coroutineScope.launch {
//                val subscriptionPurchaseList = list.filter { purchase ->
//                    purchase.products.any { product ->
//                        product in listOf(BiliConstants.PREMIUM_PRODUCT, BiliConstants.BASIC_PRODUCT)
//                    }
//                }
//
//                _subscriptionPurchases.emit(subscriptionPurchaseList)
//            }
//        }
//    }
//
//    /**
//     * 对比旧的价格
//     */
//    private fun isUnchangedPurchaseList(purchasesList: List<Purchase>): Boolean {
//        val isUnchanged = purchasesList == cachedPurchasesList
//        if (!isUnchanged) {
//            cachedPurchasesList = purchasesList
//        }
//        return isUnchanged
//    }
//
//
//    /**
//     * BillingClientStateListener
//     */
//    override fun onBillingServiceDisconnected() {
//        Log.d(TAG, "onBillingServiceDisconnected")
//    }
//
//    /**
//     * BillingClientStateListener
//     */
//    override fun onBillingSetupFinished(billingResult: BillingResult) {
//        Log.d(TAG, "onBillingSetupFinished")
//        val responseCode = billingResult.responseCode
//        val debugMessage = billingResult.debugMessage
//        Log.d(TAG, "onBillingSetupFinished: $responseCode $debugMessage")
//
//        if (responseCode == BillingClient.BillingResponseCode.OK) {
//            querySubscriptionPurchases()
//        }
//    }
//
//    /**
//     * 查询订阅价格
//     */
//    private fun querySubscriptionPurchases() {
//        if (!billingClient.isReady) {
//            Log.e(TAG, "querySubscriptionPurchases: BillingClient is not ready")
//            billingClient.startConnection(this)
//        }
//
//        billingClient.queryPurchasesAsync(
//            QueryPurchasesParams.newBuilder()
//                .setProductType(BillingClient.ProductType.SUBS)
//                .build(), this
//        )
//    }
//
//    companion object {
//        @Volatile
//        private var INSTANCE: BillingClientLifecycle? = null
//        fun getInstance(applicationContext: Context): BillingClientLifecycle =
//            INSTANCE ?: synchronized(this) {
//                INSTANCE ?: BillingClientLifecycle(applicationContext).also { INSTANCE = it }
//            }
//    }
//
//    /**
//     * PurchasesResponseListener
//     * 购买价格响应
//     */
//    override fun onQueryPurchasesResponse(billingResult: BillingResult, purchasesList: MutableList<Purchase>) {
//        processPurchases(purchasesList)
//    }
//
//    /**
//     * ProductDetailsResponseListener
//     * 产品细节响应
//     */
//    override fun onProductDetailsResponse(
//        billingResult: BillingResult,
//        productDetailsList: MutableList<ProductDetails>
//    ) {
//        val response = BillingResponse(billingResult.responseCode)
//        val debugMessage = billingResult.debugMessage
//
//        when {
//            response.isOk -> {
//                processProductDetails(productDetailsList)
//            }
//
//            response.isTerribleFailure -> {
//                // These response codes are not expected.
//                Log.w(
//                    TAG,
//                    "onProductDetailsResponse - Unexpected error: ${response.code} $debugMessage"
//                )
//            }
//
//            else -> {
//                Log.e(TAG, "onProductDetailsResponse: ${response.code} $debugMessage")
//            }
//
//        }
//    }
//
//    private val LIST_OF_SUBSCRIPTION_PRODUCTS = listOf(
//        BiliConstants.BASIC_PRODUCT,
//        BiliConstants.PREMIUM_PRODUCT,
//    )
//
//    private fun processProductDetails(productDetailsList: MutableList<ProductDetails>) {
//        if (productDetailsList.isEmpty()) {
//            val productDetailsCount = LIST_OF_SUBSCRIPTION_PRODUCTS.size
//            Log.e(
//                TAG,
//                "productDetailsCount=$productDetailsCount, Check to see if the products you requested are correctly published in the Google Play Console."
//            )
//            postProductDetails(emptyList())
//        } else {
//            postProductDetails(productDetailsList)
//        }
//    }
//
//    private fun postProductDetails(productDetailsList: List<ProductDetails>) {
//        productDetailsList.forEach { productDetails ->
//            when (productDetails.productType) {
//                BillingClient.ProductType.SUBS -> {//订阅
//                    if (productDetails.productId == BiliConstants.PREMIUM_PRODUCT) {
//                        premiumSubProductWithProductDetails.postValue(productDetails)
//                    } else if (productDetails.productId == BiliConstants.BASIC_PRODUCT) {
//                        basicSubProductWithProductDetails.postValue(productDetails)
//                    }
//                }
//            }
//        }
//    }
//
//
//}