package com.xty.base.utils

import android.content.Context
import android.os.Handler
import android.os.Looper
import android.os.Message
import android.text.TextUtils
import android.view.LayoutInflater
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import android.widget.Toast
import androidx.lifecycle.ViewModelProvider
import com.alipay.sdk.app.PayTask
import com.google.android.material.bottomsheet.BottomSheetDialog
import com.tencent.mm.opensdk.modelbase.BaseResp
import com.tencent.mm.opensdk.modelpay.PayReq
import com.tencent.mm.opensdk.openapi.WXAPIFactory
import com.xty.base.R
import com.xty.base.act.BaseVmAct
import com.xty.base.model.PayBaseResult
import com.xty.base.vm.PayVm
import com.xty.common.BuildConfig
import com.xty.common.LogUtils
import com.xty.common.arouter.ARouterUrl
import com.xty.common.arouter.RouteManager
import com.xty.common.event.ReChangeEvent
import com.xty.common.event.WxPayEvent
import com.xty.common.util.SpannableUtils
import com.xty.network.model.WeixinPayBean
import org.greenrobot.eventbus.EventBus

open class PayUtils(var context: Context) {

    lateinit var bottomSheetDialog: BottomSheetDialog

    private var baseActivity: BaseVmAct<*> = context as BaseVmAct<*>
    private val SDK_PAY_FLAG = 1
    private val WEIXIN_PAY_FLAG = 2
     val mViewModel by lazy { ViewModelProvider(baseActivity).get(PayVm::class.java)}

    var price:Float? = null

    var isPayGoods:Boolean = false

    open   fun reChangeWatch(xPrice:Float,orderNo:String){
        isPayGoods = false
        bottomSheetDialog = BottomSheetDialog(context, R.style.Theme_ChartDialogManager)
        bottomSheetDialog?.let { dialog ->
            val view = LayoutInflater.from(context).inflate(R.layout.dialog_pay, null)
            dialog.setContentView(view)

            val tvprice = view.findViewById<TextView>(R.id.tvPrice)
            tvprice.text = SpannableUtils.setSpanMoney(xPrice)
            val ivClose = view.findViewById<ImageView>(R.id.close_button)
            ivClose.setOnClickListener {
                dialog.dismiss()
            }
            val tvZhifubao = view.findViewById<TextView>(R.id.tv_gouxuan_zhifubao)
            val tvWeixin = view.findViewById<TextView>(R.id.tv_gouxuan_weixin)
            tvWeixin.isSelected = true
            val tvDuihuanma = view.findViewById<TextView>(R.id.tv_gouxuan_duihuanma)
            val llWeixin = view.findViewById<LinearLayout>(R.id.llWeixin)
            val llZhifu = view.findViewById<LinearLayout>(R.id.llZhifu)
            val tvZhifu = view.findViewById<TextView>(R.id.tvZhifu)
            llZhifu.setOnClickListener {
                tvZhifubao.isSelected = true
                tvDuihuanma.isSelected = false
                tvWeixin.isSelected = false
                tvZhifu.text = "确认支付"
            }
            llWeixin.setOnClickListener {
                tvZhifubao.isSelected = false
                tvDuihuanma.isSelected = false
                tvWeixin.isSelected = true
                tvZhifu.text = "确认支付"
            }
            val llDuihuan = view.findViewById<LinearLayout>(R.id.llDuihuan)
            llDuihuan.setOnClickListener {
                tvWeixin.isSelected = false
                tvZhifubao.isSelected = false
                tvDuihuanma.isSelected = true
                tvZhifu.text = "去兑换"
            }

            tvZhifu.setOnClickListener {
                //支付
                if (tvZhifubao.isSelected) {
                    //支付宝
                    mViewModel.payWatch(orderNo, "ALIPAY_APP")
                } else if (tvWeixin.isSelected) {
                    //微信
                    mViewModel.payWatch(orderNo, "WEIXIN_APP")
                } else {

                }

                liveObserver()
            }
        }
        bottomSheetDialog?.show()


    }


    open   fun payForGoods(xPrice:Float,orderNo:String){
        isPayGoods  = true
        bottomSheetDialog = BottomSheetDialog(context, R.style.Theme_ChartDialogManager)
        bottomSheetDialog?.let { dialog ->
            val view = LayoutInflater.from(context).inflate(R.layout.dialog_pay, null)
            dialog.setContentView(view)

            val tvprice = view.findViewById<TextView>(R.id.tvPrice)
            tvprice.text = SpannableUtils.setSpanMoney(xPrice)
            val ivClose = view.findViewById<ImageView>(R.id.close_button)
            ivClose.setOnClickListener {
                dialog.dismiss()
            }
            val tvZhifubao = view.findViewById<TextView>(R.id.tv_gouxuan_zhifubao)
            val tvWeixin = view.findViewById<TextView>(R.id.tv_gouxuan_weixin)
            tvWeixin.isSelected = true
            val tvDuihuanma = view.findViewById<TextView>(R.id.tv_gouxuan_duihuanma)
            val llWeixin = view.findViewById<LinearLayout>(R.id.llWeixin)
            val llZhifu = view.findViewById<LinearLayout>(R.id.llZhifu)
            val tvZhifu = view.findViewById<TextView>(R.id.tvZhifu)
            llZhifu.setOnClickListener {
                tvZhifubao.isSelected = true
                tvDuihuanma.isSelected = false
                tvWeixin.isSelected = false
                tvZhifu.text = "确认支付"
            }
            llWeixin.setOnClickListener {
                tvZhifubao.isSelected = false
                tvDuihuanma.isSelected = false
                tvWeixin.isSelected = true
                tvZhifu.text = "确认支付"
            }
            val llDuihuan = view.findViewById<LinearLayout>(R.id.llDuihuan)
            llDuihuan.setOnClickListener {
                tvWeixin.isSelected = false
                tvZhifubao.isSelected = false
                tvDuihuanma.isSelected = true
                tvZhifu.text = "去兑换"
            }

            tvZhifu.setOnClickListener {
                //支付
                if (tvZhifubao.isSelected) {
                    //支付宝
                    mViewModel.payWatch(orderNo, "ALIPAY_APP")
                } else if (tvWeixin.isSelected) {
                    //微信
                    mViewModel.payWatch(orderNo, "WEIXIN_APP")
                } else {

                }

                liveObserver()
            }
        }
        bottomSheetDialog?.show()


    }

    fun liveObserver(){
        baseActivity.runOnUiThread {
            mViewModel.payObservable.observe(baseActivity) {
                it.data?.let {
                    val orderInfo: String? = it.alipayOrderInfo // 支付宝订单信息
                    val wxmodel: WeixinPayBean? = it.wxmodel // 微信订单信息
                    if (wxmodel != null) {
                        startWechatPay(wxmodel)
                    } else if (orderInfo != null) {
                        LogUtils.i("start Alipay")
                        val orderInfo: String = it.alipayOrderInfo!! // 订单信息
                        val payRunnable = Runnable {
                            val alipay = PayTask(baseActivity)
                            val result = alipay.payV2(orderInfo, true)
                            val msg = Message()
                            msg.what = SDK_PAY_FLAG
                            msg.obj = result
                            mHandler.sendMessage(msg)
                        }
                        // 必须异步调用
                        val payThread = Thread(payRunnable)
                        payThread.start()
                    }
                    bottomSheetDialog?.dismiss()
                }
            }
        }

    }

    /**
     * 微信支付
     */
    fun startWechatPay(wxModel: WeixinPayBean) {
        LogUtils.i("startWechatPay")
        val appId = wxModel.appId
        val partnerId = wxModel.partnerid
        val prepayId = wxModel.prepayId
        val packageValue = wxModel.packageName
        val nonceStr = wxModel.noncestr
        val timeStamp = wxModel.timestamp
        val sign = wxModel.sign

        val api = WXAPIFactory.createWXAPI(context, BuildConfig.appid)
        api.registerApp(appId)

        //以下这些都应该从服务器去获取
        val payRequest = PayReq()
        payRequest.appId = appId//你的微信appid
        payRequest.partnerId = partnerId//微信支付分配的商户号
        payRequest.prepayId = prepayId//微信返回的支付交易会话ID
        payRequest.packageValue = packageValue//固定值
        payRequest.nonceStr = nonceStr//随机字符串
        payRequest.timeStamp = timeStamp//时间戳
        payRequest.sign = sign//签名
        //传入一个标识，以便区分回调
        payRequest.extData = "AICancelPay"
        //在支付之前，如果应用没有注册到微信，应该先调用IWXMsg.registerApp将应用注册到微信
        //发起请求，调起微信前去支付
        api.sendReq(payRequest);
    }

    private val mHandler: Handler = object : Handler(Looper.getMainLooper()) {
        override fun handleMessage(msg: Message) {
            when (msg.what) {
                SDK_PAY_FLAG -> {
                    val payResult = PayBaseResult(msg.obj as Map<String?, String?>)

                    /**
                     * 对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    val resultInfo: String = payResult.getResult() // 同步返回需要验证的信息
                    val resultStatus: String = payResult.getResultStatus()
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
//                        Toast.makeText(this@PreventCancertAct,"支付成功"+payResult,Toast.LENGTH_SHORT).show()
//                        com.alipay.sdk.pay.demo.PayDemoActivity.showAlert(
//                            this@PayDemoActivity,
//                            getString(R.string.pay_success) + payResult
//                        )
                    /*    bundle.clear()
                        bundle.putString("orderNo", orderNo)
                        bundle.putString("orderType", "1")
                        RouteManager.goAct(ARouterUrl.PAY_SUCCESS, bundle)*/

                        if(isPayGoods){

                        }else{
                            Toast.makeText(
                                context,
                                "支付成功",
                                Toast.LENGTH_SHORT
                            )
                                .show()

                            EventBus.getDefault().post(ReChangeEvent())
                        }


                    } else {
                        if(isPayGoods){

                        }else{
                            Toast.makeText(
                                context,
                                "支付失败,请联系客服",
                                Toast.LENGTH_SHORT
                            )
                                .show()
                        }


                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
//                        com.alipay.sdk.pay.demo.PayDemoActivity.showAlert(
//                            this@PayDemoActivity,
//                            getString(R.string.pay_failed) + payResult
//                        )
                    }
                }

                WEIXIN_PAY_FLAG -> {
                    val event = msg.obj as WxPayEvent
                    when (event.code) {
                        BaseResp.ErrCode.ERR_OK -> {
                           /* bundle.clear()
                            bundle.putString("orderNo", orderNo)
                            bundle.putString("orderType", "1")
                            RouteManager.goAct(ARouterUrl.PAY_SUCCESS, bundle)*/
                            if(isPayGoods){

                            }else{
                                EventBus.getDefault().post(ReChangeEvent())
                                Toast.makeText(
                                    context,
                                    "支付成功",
                                    Toast.LENGTH_SHORT
                                )
                                    .show()
                            }

                        }

                        BaseResp.ErrCode.ERR_USER_CANCEL -> {

                        }

                        else -> {
                            if(isPayGoods){

                            }else{
                                Toast.makeText(
                                    context,
                                    "支付失败,请联系客服",
                                    Toast.LENGTH_SHORT
                                ).show()
                            }

                        }
                    }
                }
            }
        }
    }

}