package com.zxhl.cms.utils

import android.text.TextUtils
import com.google.gson.Gson
import com.google.gson.JsonObject
import com.tencent.mm.opensdk.constants.Build
import com.tencent.mm.opensdk.modelbiz.WXLaunchMiniProgram
import com.tencent.mm.opensdk.modelpay.PayReq
import com.tencent.mm.opensdk.openapi.IWXAPI
import com.tencent.mm.opensdk.openapi.WXAPIFactory
import com.tencent.mm.opensdk.utils.Log
import com.zxhl.cms.AppContext
import com.zxhl.cms.common.Constant
import com.zxhl.cms.net.model.uc.PayMinEntity
import com.zxhl.cms.net.model.uc.WeChatPayEntity
import com.zxhl.cms.net.model.uc.PayResultEntity


object WeChatPay {
    var api:IWXAPI? = null
    /**
     * 微信小程序敏支付
     */
    fun startWeChatProgromPay(result: PayMinEntity,paytype:String) {
        if(TextUtils.isEmpty(Constant.WX_APPID)){
            EventUtils.onEvent("member_page_pay_fail", "WX_APPID is null")
            Utils.showToast(AppContext.get(), "暂不支持微信支付")
            return
        }
        api = getIWXAPI()
        //判断当前版本是否支持微信支付
        val isPaySupported = api?.getWXAppSupportAPI()!! >= Build.PAY_SUPPORTED_SDK_INT
        if (!isPaySupported) {
            Utils.showToast(AppContext.get(), "请安装微信客户端")
            EventUtils.onEvent("member_page_pay_fail", "请安装微信客户端")
            return
        }
        api?.registerApp(Constant.WX_APPID)
        wx(result,paytype)
    }
    /**
     * 微信原生支付和连连支付走这个方法
     */
    fun startWeChatPay(result: WeChatPayEntity?,paytype:String) {
        if(TextUtils.isEmpty(Constant.WX_APPID)){
            EventUtils.onEvent("member_page_pay_fail", "WX_APPID is null")
            Utils.showToast(AppContext.get(), "暂不支持微信支付")
            return
        }
        api = getIWXAPI()
        //判断当前版本是否支持微信支付
        val isPaySupported = api?.getWXAppSupportAPI()!! >= Build.PAY_SUPPORTED_SDK_INT
        if (!isPaySupported) {
            Utils.showToast(AppContext.get(), "请安装微信客户端")
            EventUtils.onEvent("member_page_pay_fail", "请安装微信客户端")
            return
        }
        api?.registerApp(Constant.WX_APPID)
        wx2(result,paytype)
    }

    private fun wx2(result: WeChatPayEntity?,paytype: String) {
        Log.e("MXL","Paytype:"+paytype)
        if(TextUtils.equals(paytype,"2")){
            try {
                if (result != null) {
                    val req = PayReq()
                    var entity = result?.wakeup
                    req.appId = entity?.appId
                    req.partnerId =entity?.partnerId
                    req.prepayId = entity?.prepayId
                    req.nonceStr = entity?.nonceStr
                    req.timeStamp = entity?.timeStamp
                    req.packageValue = entity?.packageValue
                    req.extData = entity?.extData
                    req.sign = entity?.sign
                    //               Log.d("PAY_GET", "req：$req")
                    // 在支付之前，如果应用没有注册到微信，应该先调用IWXMsg.registerApp将应用注册到微信
                    if (api == null) {
                        Log.d("PAY_GET", "api==null")
                        api = getIWXAPI()
                    }
                    Log.d("PAY_GET", "api sendReq")
                    api?.sendReq(req)
                } else {
                    EventUtils.onEvent("member_page_pay_fail", "WeChatPayEntity is null")
                    Log.d("PAY_GET", "返回错误")
                    result(false, "")
                }
            } catch (e: Exception) {
                // TODO: handle exception
                Log.e("TAG", e.localizedMessage)
                result(false, "")
                Log.d("PAY_GET", "e.localizedMessage " + e.localizedMessage)
                EventUtils.onEvent("member_page_pay_fail", "调微信失败")
            }

        }else{
            try {
                if (result != null) {
                    var entity = result?.wakeup
                    // 在支付之前，如果应用没有注册到微信，应该先调用IWXMsg.registerApp将应用注册到微信
                    if (api == null) {
                        Log.d("PAY_GET", "api==null")
                        api = getIWXAPI()
                    }
                    Log.d("PAY_GET", "api sendReq")
                    var path:String="/pages/pay/index?token=" + entity?.token + "&pkg_name=com.zxhl.shop"
                    val req = WXLaunchMiniProgram.Req()
                    val g = Gson()
                    val obj: JsonObject = g.fromJson(entity?.payload, JsonObject::class.java)
                    val miniId= obj.get("appid").toString().replace("\"","")
                    req.userName ="${miniId}"// 填小程序原始id
//                req.userName = "gh_150c1f5238f7"// 填小程序原始id
                    Log.e("MXL",""+miniId)
                    req.path = path//拉起小程序页面的可带参路径，不填默认拉起小程序首页，对于小游戏，可以只传入 query 部分，来实现传参效果，如：传入 "?foo=bar"。
                    req.miniprogramType =
                        WXLaunchMiniProgram.Req.MINIPTOGRAM_TYPE_RELEASE // 可选打开 开发版，体验版和正式版
                    api?.sendReq(req)
                } else {
                    EventUtils.onEvent("member_page_pay_fail", "WeChatPayEntity is null")
                    Log.d("PAY_GET", "返回错误")
                    result(false, "")
                }
            } catch (e: Exception) {
                // TODO: handle exception
                Log.e("TAG", e.localizedMessage)
                result(false, "")
                Log.d("PAY_GET", "e.localizedMessage " + e.localizedMessage)
                EventUtils.onEvent("member_page_pay_fail", "调微信失败")
            }
        }



    }

    private fun wx(result: PayMinEntity?,paytype: String) {
        if(TextUtils.equals(paytype,"12")){
            try {
                if (result != null) {
                    //var entity = result?.wakeup
                    // 在支付之前，如果应用没有注册到微信，应该先调用IWXMsg.registerApp将应用注册到微信
                    if (api == null) {
                        Log.d("PAY_GET", "api==null")
                        api = getIWXAPI()
                    }
                    var path:String="/pages/pay/index?sendMsg=" + result?.wakeup
                    val req = WXLaunchMiniProgram.Req()
                    req.userName ="gh_55a696f51352"// 填小程序原始id
                    req.path = path//拉起小程序页面的可带参路径，不填默认拉起小程序首页，对于小游戏，可以只传入 query 部分，来实现传参效果，如：传入 "?foo=bar"。
                    Log.e("MXL","path:"+path)
                    req.miniprogramType =
                        WXLaunchMiniProgram.Req.MINIPTOGRAM_TYPE_RELEASE // 可选打开 开发版，体验版和正式版
                    api?.sendReq(req)
                } else {
                    EventUtils.onEvent("member_page_pay_fail", "WeChatPayEntity is null")
                    Log.d("PAY_GET", "返回错误")
                    result(false, "")
                }
            } catch (e: Exception) {
                // TODO: handle exception
                Log.e("TAG", e.localizedMessage)
                result(false, "")
                Log.d("PAY_GET", "e.localizedMessage " + e.localizedMessage)
                EventUtils.onEvent("member_page_pay_fail", "调微信失败")
            }
        }


    }
    fun result(isPaysuc: Boolean, txt: String){
//        if(!TextUtils.isEmpty(order)) {
//            var mPresenter = PayPresenter(this)
//            mPresenter?.verifyPay(order)
//        }
        var entity = PayResultEntity()
        entity.isPaySuc = isPaysuc
        entity.txt = txt
        entity.payType = 11//微信支付类型
        RxBus.get().post("MemberCenterFragment", entity)

        Log.d("PAY_GET", " RxBus.get().post(\"MemberCenterFragment\",entity)")
    }
    /**
     * 获取微信api
     */
    fun getIWXAPI(): IWXAPI {
        Log.d("PAY_GET", "  Constant.WX_APPID:" + Constant.WX_APPID)
        return WXAPIFactory.createWXAPI(AppContext.get(), Constant.WX_APPID)
    }
}