package com.zj365.health.act.skin

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 android.widget.Toast
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.WxPayEvent
import com.xty.common.setImage
import com.xty.common.util.SpannableUtils
import com.xty.network.model.PayGoodsBean
import com.xty.network.model.WeixinPayBean
import com.zj365.health.R
import com.zj365.health.databinding.ActAiSkinMeasurementBinding
import com.zj365.health.model.PayResult
import com.zj365.health.vm.SkinMeasurementVm
import com.zj365.health.weight.CancerDialog
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

@Route(path = ARouterUrl.AI_SKIN_MEASUREMENT_ACTIVITY)
class SkinMeasurementMainAct : BaseVmAct<SkinMeasurementVm>()  {

    val binding by lazy { ActAiSkinMeasurementBinding.inflate(layoutInflater)}

    var type = 0 //0 AI 测肤 1 AI 糖医

    var isShowTip = false

    var bottomSheetDialog: BottomSheetDialog? = null

     var payGoodsBean: PayGoodsBean? = null


    override fun liveObserver() {
        mViewModel.payGoodsObservable.observe(this){
            if (it.data == null){
                return@observe
            }
            payGoodsBean = it.data
            binding.ivBg.setImage(this,it.data.advUrl)
            initBottomDialog()
        }

        mViewModel.payObservable.observe(this){
            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(this)
                        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()
                }

            }
        }
    }

    override fun setLayout() = binding.root

    override fun initView() {
        super.initView()
        statusBar(binding.title.mView)
        type = intent.getIntExtra("type",0)
        if(type == 0){
            binding.title.mTvTitle.text ="AI测肤"
            binding.title.mTvRight.text ="测试记录"
            binding.title.mTvRight.setTextColor(resources.getColor(R.color.col_02c))
            binding.title.mTvRight.visibility = View.VISIBLE
        }else{
            binding.title.mTvTitle.text ="AI糖医"
            binding.title.mTvRight.text ="订单记录"
            binding.title.mTvRight.setTextColor(resources.getColor(R.color.col_02c))
            binding.title.mTvRight.visibility = View.VISIBLE
            mViewModel.getAIGoods()
        }

        binding.title.mTvRight.setOnClickListener {
            if(type == 0){

            }else{
                bundle.clear()
                bundle.putInt("type",1)
                RouteManager.goAct(ARouterUrl.ORDER_LIST,bundle)
            }

        }

        binding.title.mIvBack.setOnClickListener {
            finish()
        }

        binding.tvSubmit.setOnClickListener {


            bottomSheetDialog?.show()
        }

        initBottomDialog()

    }

    fun initBottomDialog() {
        payGoodsBean?.let { bean ->
            if (bottomSheetDialog == null) {
                bottomSheetDialog = BottomSheetDialog(this,R.style.Theme_ChartDialogManager)
                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 = SpannableUtils.setSpanMoney(bean.price!!)
                    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.visibility = View.GONE
                    llDuihuan.setOnClickListener {
                        tvWeixin.isSelected = false
                        tvZhifubao.isSelected = false
                        tvDuihuanma.isSelected = true
                        tvZhifu.text = "去兑换"
                    }

                    tvZhifu.setOnClickListener {
                        //支付
                        if (tvZhifubao.isSelected) {
                            //支付宝
                            mViewModel.payAISugarMedicineOrder(bean.id.toString(), false)
                        } else {
                            //微信
                            mViewModel.payAISugarMedicineOrder(bean.id.toString(), true)
                        }
                        dialog.dismiss()
                    }
                }
            }
        }


    }

    private val SDK_PAY_FLAG = 1
    private val WEIXIN_PAY_FLAG = 2

    /**
     * 微信支付
     */
    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(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);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun getWxPayResult(event: WxPayEvent) {
        val msg = mHandler.obtainMessage()
        msg.what = WEIXIN_PAY_FLAG
        msg.obj = event
        mHandler.sendMessage(msg)
    }

    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.getResult() // 同步返回需要验证的信息
                    val resultStatus: String = payResult.getResultStatus()
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {

                        payGoodsBean?.let {
                            if(type == 1){
                                AiIcingPaySuccessDialog(mViewModel.payObservable.value?.data?.orderNo!!).show(supportFragmentManager,"AiIcingPaySuccessDialog")

                            }else{
                                bundle.clear()
                                bundle.putString("orderNo", mViewModel.payObservable.value?.data?.orderNo)
                                bundle.putString("orderType", it.goodsType.toString())
                                RouteManager.goAct(ARouterUrl.PAY_SUCCESS, bundle)
                            }


                        }

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

                    }
                }
                WEIXIN_PAY_FLAG -> {
                    val event = msg.obj as WxPayEvent
                    when (event.code) {
                        BaseResp.ErrCode.ERR_OK -> {
                            payGoodsBean?.let {
                                if(type == 1){
                                    AiIcingPaySuccessDialog(mViewModel.payObservable.value?.data?.orderNo!!).show(supportFragmentManager,"AiIcingPaySuccessDialog")

                                }else{
                                    bundle.clear()
                                    bundle.putString("orderNo", mViewModel.payObservable.value?.data?.orderNo)
                                    bundle.putString("orderType", it.goodsType.toString())
                                    RouteManager.goAct(ARouterUrl.PAY_SUCCESS, bundle)
                                }

                            }

                        }

                        BaseResp.ErrCode.ERR_USER_CANCEL -> {

                        }

                        else -> {
                            Toast.makeText(
                                this@SkinMeasurementMainAct,
                                "支付失败,请联系客服",
                                Toast.LENGTH_SHORT
                            ).show()
                        }
                    }
                }
            }
        }
    }


}