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.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.WeChatPayEntity
import com.zxhl.novel.utils.server.PayResultEntity
import org.json.JSONObject


object WeChatPay {
    var api:IWXAPI? = null
    /**
     * 微信支付
     */
    fun startWeChatPay(result: WeChatPayEntity) {
        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
        }
//        println("判断当前版本是否支持微信支付" + isPaySupported.toString())



        api?.registerApp(Constant.WX_APPID)

        Log.d("PAY_GET", ("  " + api == null).toString())



        wx(result)
    }

    private fun wx(result: WeChatPayEntity?) {

        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")
                var path:String="/pages/pay/index?token=" + entity?.token + "&pkg_name=com.zhangxin.starlight"
                val req = WXLaunchMiniProgram.Req()
                val g = Gson()
                val obj: JsonObject = g.fromJson(entity?.payload, JsonObject::class.java)
                req.userName = obj.get("appid").toString()// 填小程序原始id
                Log.e("MXL","appid:"+obj.get("appid").toString()+"path:"+path)

                req.path = path//拉起小程序页面的可带参路径，不填默认拉起小程序首页，对于小游戏，可以只传入 query 部分，来实现传参效果，如：传入 "?foo=bar"。

                req.miniprogramType =
                    WXLaunchMiniProgram.Req.MINIPTOGRAM_TYPE_RELEASE // 可选打开 开发版，体验版和正式版

                api!!.sendReq(req)
                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 = 2//微信支付类型
        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)
    }
}