package com.zj365.health.act

import android.annotation.SuppressLint
import android.os.Handler
import android.os.Looper
import android.os.Message
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import com.alibaba.android.arouter.facade.annotation.Route
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.act.BaseVmAct
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.BloodFilipOpenSuccessEvent
import com.xty.common.event.MyInfoEvent
import com.xty.common.event.NSuanOpenEvent
import com.xty.common.event.OpenOrRenewEvent
import com.xty.common.event.WxPayEvent
import com.xty.common.event.XTangUploadEvent
import com.xty.common.setImage
import com.xty.common.util.CommonToastUtils
import com.zj365.health.R
import com.zj365.health.databinding.ActXtangOpenOrRenewBinding
import com.zj365.health.model.PayResult
import com.zj365.health.vm.XTangVm
import com.xty.network.model.OpenOrRenewBean
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

/**
 * 血糖开通或续费
 */
@Route(path = ARouterUrl.OPEN_OR_RENEW)
class OpenOrRenewAct : BaseVmAct<XTangVm>() {

    private val binding by lazy { ActXtangOpenOrRenewBinding.inflate(layoutInflater) }
    override fun setLayout(): View = binding.root

    private var stringExtra: String = ""

    private var bottomSheetDialog: BottomSheetDialog? = null

    private var payPrice = 0f
    private var userId = ""
    private var pageType = 0//1,血糖，2，尿酸，3，血脂
    private var subject = 0//3，血糖续费开通，4，尿酸续费开通，5，血脂续费开通
    private val SDK_PAY_FLAG = 1
    private val WEIXIN_PAY_FLAG = 2

    @SuppressLint("SimpleDateFormat")
    override fun initData() {
        super.initData()
        stringExtra = intent.getStringExtra("expireTime").toString()
        if (stringExtra == "null") {
            stringExtra = ""
        }
        userId = intent.getStringExtra("userId").toString()
        pageType = intent.getIntExtra("pageType", 0)
        when (pageType) {
            1 -> {
                subject = 3
            }

            2 -> {
                subject = 4
            }

            3 -> {
                subject = 5
            }
        }
    }

    override fun initView() {
        super.initView()
        statusBar(binding.title.mView)
        //1,血糖，2，尿酸，3，血脂
        when (pageType) {
            1 -> {
                if (!TextUtils.isEmpty(stringExtra)) {
                    binding.title.mTvTitle.text = "血糖续费"
                } else {
                    binding.title.mTvTitle.text = "血糖开通"
                }
            }

            2 -> {
                if (!TextUtils.isEmpty(stringExtra)) {
                    binding.title.mTvTitle.text = "尿酸续费"
                } else {
                    binding.title.mTvTitle.text = "尿酸开通"
                }
            }

            3 -> {
                if (!TextUtils.isEmpty(stringExtra)) {
                    binding.title.mTvTitle.text = "血脂续费"
                } else {
                    binding.title.mTvTitle.text = "血脂开通"
                }
            }
        }
        if (!TextUtils.isEmpty(stringExtra)) {
            binding.tvSubmit.text = "立即购买"
        } else {
            binding.tvSubmit.text = "立即开通"
        }
        binding.title.mIvBack.apply {
            setOnClickListener {
                finish()
            }
        }

        //点击弹出支付方式弹窗
        binding.tvSubmit.setOnClickListener {
            if (!TextUtils.isEmpty(stringExtra)) {
                bottomSheetDialog?.show()
            } else {
                mViewModel.firstOpen(userId, pageType)
            }
        }

        //获取血糖、尿酸、血脂价格图片
        mViewModel.getPriceRequest(pageType)
    }

    @SuppressLint("SetTextI18n", "InflateParams")
    fun initBottomDialog() {
        if (bottomSheetDialog == null) {
            bottomSheetDialog = BottomSheetDialog(this)
            bottomSheetDialog?.let { dialog ->
                val view = LayoutInflater.from(this).inflate(R.layout.dialog_pay, null)
                dialog.setContentView(view)

                val tvprice = view.findViewById<TextView>(R.id.tvPrice)
                tvprice.text = "￥${payPrice}"
                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.renewOpenRequest(userId, subject, "ALIPAY_APP", "")
                    } else if (tvWeixin.isSelected) {
                        //微信
                        mViewModel.renewOpenRequest(userId, subject, "WEIXIN_APP", "")
                    } else {
                        //兑换码
                        if (stringExtra.isEmpty()) {
                            //1,血糖，2，尿酸，3，血脂
                            when (pageType) {
                                1 -> {//血糖
                                    bundle.clear()
                                    bundle.putBoolean("isOpen", false)
                                    bundle.putString("id", userId)
                                    RouteManager.goAct(ARouterUrl.XT_OPEN, bundle)
                                }

                                2 -> {//尿酸
                                    bundle.clear()
                                    bundle.putString("id", userId)
                                    bundle.putBoolean("isOpen", false)
                                    RouteManager.goAct(ARouterUrl.NS_OPEN, bundle)
                                }

                                3 -> {
                                    bundle.clear()
                                    bundle.putString("id", userId)
                                    bundle.putBoolean("isOpen", false)
                                    RouteManager.goAct(ARouterUrl.XT_OPEN, bundle)
                                }
                                else ->{}
                            }
                        } else {
                            when (pageType) {
                                1 -> {//血糖
                                    bundle.clear()
                                    bundle.putBoolean("isOpen", true)
                                    bundle.putString("id", userId)
                                    RouteManager.goAct(ARouterUrl.XT_OPEN, bundle)
                                }

                                2 -> {//尿酸
                                    bundle.clear()
                                    bundle.putString("id", userId)
                                    bundle.putBoolean("isOpen", true)
                                    bundle.putString("time",stringExtra)
                                    RouteManager.goAct(ARouterUrl.NS_OPEN, bundle)
                                }

                                3 -> {
                                    bundle.clear()
                                    bundle.putString("id", userId)
                                    bundle.putBoolean("isOpen", false)
                                    RouteManager.goAct(ARouterUrl.XT_OPEN, bundle)
                                }
                                else ->{}
                            }
                        }
                    }
                    dialog.dismiss()
                }
            }
        }
    }

    override fun liveObserver() {
        //获取血糖、尿酸、血脂价格返回方法
        mViewModel.getPriceData.observe(this) {
            if (it.code == 0) {
                val data = it.data
                val imgUrl = if (stringExtra.isEmpty()) {
                    data.firstImageUrl
                } else {
                    data.imageUrl
                }
                binding.ivRenewPicture.setImage(this, imgUrl)

                payPrice = data.price
                initBottomDialog()
            } else {
                CommonToastUtils.showToast("获取开通血糖价格失败！")
            }
        }

        //支付返回方法
        mViewModel.renewOpenData.observe(this) {
            if (it.code == 0) {
                if (it.data != null) {
                    when (it.data.channelName) {
                        "ALIPAY_APP" -> {//支付宝
                            val alipayOrderInfo = it.data.alipayOrderInfo
                            LogUtils.i("start Alipay")
                            val payRunnable = Runnable {
                                val alipay = PayTask(this)
                                val result = alipay.payV2(alipayOrderInfo, true)
                                val msg = Message()
                                msg.what = SDK_PAY_FLAG
                                msg.obj = result
                                mHandler.sendMessage(msg)
                            }
                            // 必须异步调用
                            val payThread = Thread(payRunnable)
                            payThread.start()
                        }

                        "WEIXIN_APP" -> {//微信
                            val wxmodel = it.data.wxmodel
                            startWechatPay(wxmodel)
                        }
                    }
                }
            } else {
                CommonToastUtils.showToast("支付失败：${it.msg}")
            }
        }

        //首次开通返回方法
        mViewModel.firstOpenData.observe(this) {
            if (it.code == 0) {
                //1,血糖，2，尿酸，3，血脂
                when (pageType) {
                    1 -> {
                        EventBus.getDefault().post(XTangUploadEvent())
                    }

                    2 -> {
                        bundle.clear()
                        bundle.putString("id",userId)
                        bundle.putBoolean("firstOpen", true)
                        bundle.putString("time",stringExtra)
                        RouteManager.goAct(ARouterUrl.NS_MESSAGE_PERFECT,bundle)
                    }

                    3 ->{
                        EventBus.getDefault().post(BloodFilipOpenSuccessEvent())
                    }
                }
                EventBus.getDefault().post(MyInfoEvent())
                finish()
            } else {
                CommonToastUtils.showToast("开通失败：${it.msg}")
            }
        }
    }

    /**
     * 微信支付
     */
    private fun startWechatPay(wxModel: OpenOrRenewBean.Wxmodel) {
        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(this, 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 = PayResult(msg.obj as Map<String?, String?>)

                    /**
                     * 对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    val resultInfo: String = payResult.result // 同步返回需要验证的信息
                    val resultStatus: String = payResult.resultStatus
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                        //1,血糖，2，尿酸，3，血脂
                        when (pageType) {
                            1 -> {//血糖
                                EventBus.getDefault().post(XTangUploadEvent())
                            }

                            2 -> {//尿酸
                                EventBus.getDefault().post(NSuanOpenEvent())
                            }

                            3 ->{
                                EventBus.getDefault().post(XTangUploadEvent())
                            }

                            else -> {}
                        }
                        EventBus.getDefault().post(MyInfoEvent())
                        finish()
                    } else {
                        CommonToastUtils.showToast("支付失败,请联系客服")
                    }
                }

                WEIXIN_PAY_FLAG -> {
                    val event = msg.obj as WxPayEvent
                    when (event.code) {
                        BaseResp.ErrCode.ERR_OK -> {
                            //1,血糖，2，尿酸，3，血脂
                            when (pageType) {
                                1 -> {//血糖
                                    EventBus.getDefault().post(XTangUploadEvent())
                                }

                                2 -> {//尿酸
                                    EventBus.getDefault().post(NSuanOpenEvent())
                                }
                                3 ->{
                                    EventBus.getDefault().post(XTangUploadEvent())

                                }

                                else -> {}
                            }
                            EventBus.getDefault().post(MyInfoEvent())
                            finish()
                        }

                        BaseResp.ErrCode.ERR_USER_CANCEL -> {

                        }

                        else -> {
                            CommonToastUtils.showToast("支付失败,请联系客服")
                        }
                    }
                }
            }
        }
    }

    /**
     * 微信支付返回
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun getWxPayResult(event: WxPayEvent) {
        val msg = mHandler.obtainMessage()
        msg.what = WEIXIN_PAY_FLAG
        msg.obj = event
        mHandler.sendMessage(msg)
    }

    /**
     * 开通/续费成功
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun xtOpenSuccess(event: OpenOrRenewEvent) {
        finish()
    }
}