package cn.yyxx.eyuancomm.impl.channel.huawei

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.content.IntentSender
import cn.yyxx.eyuancomm.comm.entity.ResultInfo
import cn.yyxx.eyuancomm.comm.entity.SdkChargeInfo
import cn.yyxx.eyuancomm.comm.network.SdkRequest
import cn.yyxx.eyuancomm.comm.utils.Logger
import cn.yyxx.eyuancomm.comm.widget.ScaleLoadingDialog
import cn.yyxx.support.JsonUtils
import com.huawei.hms.iap.Iap
import com.huawei.hms.iap.IapApiException
import com.huawei.hms.iap.entity.OrderStatusCode
import com.huawei.hms.iap.entity.OwnedPurchasesReq
import com.huawei.hms.iap.entity.ProductInfoReq
import com.huawei.hms.iap.entity.PurchaseIntentReq
import com.huawei.hms.support.api.client.Status
import org.json.JSONObject
import java.net.URLEncoder

/**
 * @author #Suyghur.
 * Created on 2022/02/16
 */
class HuaweiInAppPay {

    private var loadingDialog: ScaleLoadingDialog? = null
    private var callback: InAppPayCallback? = null

    companion object {
        val instance: HuaweiInAppPay by lazy(mode = LazyThreadSafetyMode.SYNCHRONIZED) {
            HuaweiInAppPay()
        }
    }

    fun charge(activity: Activity, chargeInfo: SdkChargeInfo, callback: InAppPayCallback) {
        showLoadingDialog(activity)
        this.callback = callback
        Iap.getIapClient(activity).isEnvReady.addOnSuccessListener {
            // 获取接口请求的结果
//            obtainProductInfo(activity, chargeInfo, callback)
            obtainOwnedPurchases(activity, chargeInfo)
        }.addOnFailureListener { e ->
            dismissLoadingDialog()
            if (e is IapApiException) {
                val status: Status = e.status
                when (status.statusCode) {
                    OrderStatusCode.ORDER_HWID_NOT_LOGIN -> {
                        // 未登录帐号
                        Logger.e("未登录帐号")
                        if (status.hasResolution()) {
                            try {
                                // 6666是您自定义的常量
                                // 启动IAP返回的登录页面
                                status.startResolutionForResult(activity, 6666)
                            } catch (exp: IntentSender.SendIntentException) {
                            }
                        }
                    }
                    OrderStatusCode.ORDER_ACCOUNT_AREA_NOT_SUPPORTED -> {
                        // 用户当前登录的华为帐号所在的服务地不在华为IAP支持结算的国家/地区中
                        Logger.e("用户当前登录的华为帐号所在的服务地不在华为IAP支持结算的国家/地区中")
                    }
                    else -> {
                        // 其他外部错误
                        Logger.e("其他外部错误")
                    }
                }
            } else {
                // 其他外部错误
                Logger.e("其他外部错误")
            }
        }
    }

    /**
     * 查询未消耗的阻塞订单
     */
    private fun obtainOwnedPurchases(activity: Activity, chargeInfo: SdkChargeInfo) {
        // 构造一个OwnedPurchasesReq对象
        val ownedPurchasesReq = OwnedPurchasesReq()
        // priceType: 0：消耗型商品; 1：非消耗型商品; 2：订阅型商品
        ownedPurchasesReq.priceType = 0
        // 调用obtainOwnedPurchases接口获取所有已购但未发货的消耗型商品的购买信息
        Iap.getIapClient(activity).obtainOwnedPurchases(ownedPurchasesReq).addOnSuccessListener { result ->
            // 获取接口请求成功的结果
            if (result.inAppPurchaseDataList.isNullOrEmpty()) {
                obtainProductInfo(activity, chargeInfo)
            } else {
                // 永远保持只有一笔未消耗订单
                val purchaseData = result.inAppPurchaseDataList[0]
                val signature = result.inAppSignature[0]
                notifyOrder2Backend(activity, purchaseData, signature) { resultInfo ->
                    dismissLoadingDialog()
                    if (resultInfo.code == 1) {
                        // 重新消耗成功，继续发起支付
                        obtainProductInfo(activity, chargeInfo)
                    } else {
                        // 消耗失败
                        callback?.onResult(-1, "obtainOwnedPurchases: 支付发生异常")
                    }
                }
            }
        }.addOnFailureListener { e ->
            dismissLoadingDialog()
            callback?.onResult(-1, "obtainOwnedPurchases: 支付发生异常")
            if (e is IapApiException) {
                val apiException = e as IapApiException
                val status: Status = apiException.status
                val returnCode = apiException.statusCode
            } else {
                // 其他外部错误
            }
        }
    }

    private fun obtainProductInfo(activity: Activity, chargeInfo: SdkChargeInfo) {
        val productIdList: MutableList<String> = ArrayList()
        // 查询的商品必须是您在AppGallery Connect网站配置的商品
        productIdList.add(chargeInfo.productId)
        val req = ProductInfoReq()
        // priceType: 0：消耗型商品; 1：非消耗型商品; 2：订阅型商品
        req.priceType = 0
        req.productIds = productIdList
        // 获取调用接口的Activity对象
        // 调用obtainProductInfo接口获取AppGallery Connect网站配置的商品的详情信息
        Iap.getIapClient(activity).obtainProductInfo(req).addOnSuccessListener {
            // 获取接口请求成功时返回的商品详情信息
            createPurchaseIntent(activity, chargeInfo)
        }.addOnFailureListener { e ->
            dismissLoadingDialog()
            Logger.e(e.localizedMessage)
            callback?.onResult(-1, "obtainProductInfo: 支付发生异常")
            if (e is IapApiException) {
                val apiException = e as IapApiException
                val returnCode = apiException.statusCode
            } else {
                // 其他外部错误
            }
        }
    }

    private fun createPurchaseIntent(activity: Activity, chargeInfo: SdkChargeInfo) {
        // 构造一个PurchaseIntentReq对象
        val req = PurchaseIntentReq()
        // 通过createPurchaseIntent接口购买的商品必须是您在AppGallery Connect网站配置的商品。
        req.productId = chargeInfo.productId
        // priceType: 0：消耗型商品; 1：非消耗型商品; 2：订阅型商品
        req.priceType = 0
        req.developerPayload = chargeInfo.orderId
        // 获取调用接口的Activity对象
        // 调用createPurchaseIntent接口创建托管商品订单
        Iap.getIapClient(activity).createPurchaseIntent(req).addOnSuccessListener { result ->
            // 获取创建订单的结果
            if (result.status.hasResolution()) {
                try {
                    // 启动IAP返回的收银台页面
                    result.status.startResolutionForResult(activity, 8888)
                } catch (exp: IntentSender.SendIntentException) {
                    callback?.onResult(-1, "支付发生异常")
                }
            } else {
                callback?.onResult(-1, "支付发生异常")
            }
        }.addOnFailureListener { e ->
            dismissLoadingDialog()
            Logger.d(e.localizedMessage)
            callback?.onResult(-1, "createPurchaseIntent: 支付发生异常")
            if (e is IapApiException) {
                val apiException = e as IapApiException
                val status: Status = apiException.status
                val returnCode = apiException.statusCode
            } else {
                // 其他外部错误
            }
        }
    }

    private fun notifyOrder2Backend(activity: Activity, purchaseData: String, signature: String, onResponse: (ResultInfo) -> Unit) {
        val jsonObject = JSONObject()
        with(JSONObject(purchaseData)) {
            if (JsonUtils.hasJsonKey(this, "developerPayload")) {
                jsonObject.put("order_id", getString("developerPayload"))
            } else {
                jsonObject.put("order_id", "")
            }
            val notifyData = JSONObject()
            notifyData.put("purchase_data", purchaseData)
            notifyData.put("signature", signature)
            jsonObject.put("order_notify_data", notifyData.toString())
        }
        SdkRequest.instance.notifyOrder(activity, jsonObject, onResponse)
    }

    fun onActivityResult(activity: Activity, requestCode: Int, resultCode: Int, data: Intent?) {
        if (requestCode == 6666) {
            // 判断环境支付环境
        } else if (requestCode == 8888) {
            if (data != null) {
                // 调用parsePurchaseResultInfoFromIntent方法解析支付结果数据
                val purchaseResultInfo = Iap.getIapClient(activity).parsePurchaseResultInfoFromIntent(data)
                when (purchaseResultInfo.returnCode) {
                    OrderStatusCode.ORDER_STATE_CANCEL -> {
                        Logger.d("cancel")
                        dismissLoadingDialog()
                        callback?.onResult(-1, "支付发生异常")
                    }
                    OrderStatusCode.ORDER_STATE_FAILED, OrderStatusCode.ORDER_PRODUCT_OWNED, OrderStatusCode.ORDER_STATE_DEFAULT_CODE -> {
                        dismissLoadingDialog()
                        callback?.onResult(-1, "支付发生异常")
                    }
                    OrderStatusCode.ORDER_STATE_SUCCESS -> {
                        // 支付成功
                        with(purchaseResultInfo) {
                            // consumeOwnedPurchase(activity, inAppPurchaseData, inAppDataSignature)
                            // 通知服务端支付流程完成，验证订单并确认交易
                            notifyOrder2Backend(activity, inAppPurchaseData, inAppDataSignature) { resultInfo ->
                                dismissLoadingDialog()
                                if (resultInfo.code == 1) {
                                    callback?.onResult(0, "支付流程完成")
                                } else {
                                    callback?.onResult(-1, "支付发生异常")
                                }
                            }
                        }
                    }
                    else -> {
                        dismissLoadingDialog()
                        callback?.onResult(-1, "支付发生异常")
                    }
                }
            }
        }
    }

    private fun showLoadingDialog(context: Context) {
        loadingDialog?.apply {
            dismiss()
            loadingDialog = null
        }
        loadingDialog = ScaleLoadingDialog(context, "")
        loadingDialog?.show()
    }

    private fun dismissLoadingDialog() {
        loadingDialog?.apply {
            dismiss()
            loadingDialog = null
        }
    }


    interface InAppPayCallback {
        fun onResult(code: Int, result: String)
    }
}