package com.abbidot.tracker.deprecated.ui.activity.profile.recharge.cn

import android.os.Handler
import android.os.HandlerThread
import android.os.Message
import android.text.TextUtils
import android.view.View
import androidx.activity.viewModels
import androidx.core.content.ContextCompat
import androidx.lifecycle.lifecycleScope
import com.abbidot.baselibrary.constant.EventName
import com.abbidot.baselibrary.eventbus.XEventBus
import com.abbidot.baselibrary.util.LogUtil
import com.abbidot.baselibrary.util.Utils
import com.abbidot.tracker.R
import com.abbidot.tracker.alipay.PayResult
import com.abbidot.tracker.base.BaseActivity
import com.abbidot.tracker.bean.RechargeDeviceBean
import com.abbidot.tracker.bean.SetMealBean
import com.abbidot.tracker.constant.ConstantInt
import com.abbidot.tracker.constant.ConstantString
import com.abbidot.tracker.constant.GetResultCallback
import com.abbidot.tracker.databinding.ActivityRechargeOrderDetailCnBinding
import com.abbidot.tracker.deprecated.ui.activity.vm.PayCNViewModel
import com.abbidot.tracker.util.ThirdPartyUtil
import com.abbidot.tracker.util.Util
import com.abbidot.tracker.util.ViewUtil
import com.alipay.sdk.app.PayTask
import com.qmuiteam.qmui.widget.dialog.QMUIBottomSheet
import com.tencent.mm.opensdk.modelpay.PayReq
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch


/**
 * 国内充值订单详情
 */
class RechargeOrderDetailCNActivity : BaseActivity<ActivityRechargeOrderDetailCnBinding>(
    ActivityRechargeOrderDetailCnBinding::inflate
) {

    private val mPayCNViewModel: PayCNViewModel by viewModels()

    //设备
    private var mRechargeDeviceBean: RechargeDeviceBean? = null

    //套餐
    private var mSetMealBean: SetMealBean? = null
    private var mQMUIBottomSheet: QMUIBottomSheet? = null

    private val alipaySDKPayFlag = 1

    //支付方式
    private var mPayWay = 0

    //支付宝支付子线程
    private lateinit var mHandlerThread: HandlerThread
    private lateinit var mHandler: Handler

    override fun getTopBar() = mViewBinding.rechargeOrderDetailCnBar.titleTopBar

    override fun initData() {
        super.initData()
        setTopBarTitle(R.string.txt_pay_order_title)

        mRechargeDeviceBean = Util.getParcelableAdaptive(
            intent,
            ConstantString.RechargeDevice,
            RechargeDeviceBean::class.java
        )
        mSetMealBean =
            Util.getParcelableAdaptive(intent, ConstantString.SetMeal, SetMealBean::class.java)

        mViewBinding.apply {
            ViewUtil.instance.setShapeRadius(rechargeOrderDetailCnDevice.root, 6)
            ViewUtil.instance.setShapeRadius(rechargeOrderDetailCnAmount.root, 6)
            rechargeOrderDetailCnPayWay.let {
                it.text = getString(R.string.txt_select_payment_method)
                it.detailTextView.visibility = View.VISIBLE
                it.detailTextView.background =
                    ContextCompat.getDrawable(mContext!!, R.drawable.pic_wechatpay)

                setOnClickListenerViews(startPayMoneyBtnCn, it)
            }
        }

        //底部弹出菜单
        val languageList = mutableListOf(R.drawable.pic_wechatpay, R.drawable.pic_alipay)
        val bottomListSheetBuilder =
            ViewUtil.instance.showBottomSheetList(mContext!!, { dialog, _, position, _ ->
                dialog.dismiss()
                mPayWay = position
                mViewBinding.rechargeOrderDetailCnPayWay.detailTextView.background =
                    ContextCompat.getDrawable(mContext, languageList[position])
            })
        for (i in 0 until languageList.size) {
            bottomListSheetBuilder.addItem(languageList[i], "", "")
        }
        mQMUIBottomSheet = bottomListSheetBuilder.build()

        setRechargeDeviceData()
        setSetMeal()

        initAlipayThread()
    }

    /**
     * 初始化支付宝支付线程
     */
    private fun initAlipayThread() {
        mHandlerThread = HandlerThread("mHandlerThread")
        mHandlerThread.start()
        //支付宝支付结果回调
        mHandler = Handler(mHandlerThread.looper) {
            when (it.what) {
                alipaySDKPayFlag -> {
                    @Suppress("UNCHECKED_CAST") val payResult =
                        PayResult(it.obj as Map<String, String>)
                    //同步返回需要验证的信息
                    LogUtil.e("支付宝支付结果回调", payResult.toString())
                    mPayCNViewModel.alipayResultCallback(
                        this, payResult.resultStatus, mSetMealBean!!.accountFee
                    )
                }
            }
            true
        }
    }

    override fun liveDataObserve() {
        mPayCNViewModel.mGetWxPayOrderLiveData.observe(this) {
            dealRequestResult(it, object : GetResultCallback {
                override fun onResult(any: Any) {
                    val data = it.getOrNull()
                    data?.apply {
                        val request = PayReq()
                        request.appId = appid
                        request.partnerId = partnerid
                        request.prepayId = prepayid
                        request.packageValue = packageStr
                        request.nonceStr = noncestr
                        request.timeStamp = timestamp
                        request.sign = sign
                        ThirdPartyUtil.mApi.sendReq(request)
                    }
                }
            })
        }

        mPayCNViewModel.mGetAlipayOrderLiveData.observe(this) {
            dealRequestResult(it, object : GetResultCallback {
                override fun onResult(any: Any) {
                    val data = it.getOrNull()
                    data?.let {
                        //支付宝支付必须异步调用
                        lifecycleScope.launch(Dispatchers.IO) {
                            val alipay = PayTask(mActivity)
                            //订单信息
                            val result = alipay.payV2(data.orderString, true)
                            val msg = Message()
                            msg.what = alipaySDKPayFlag
                            msg.obj = result
                            mHandler.sendMessage(msg)
                        }
                    }
                }
            })
        }

        //支付成功返回
        XEventBus.observe(this, EventName.PayBack) {
            finish()
        }
    }

    private fun setRechargeDeviceData() {
        mRechargeDeviceBean?.apply {
            mViewBinding.rechargeOrderDetailCnDevice.let {
                it.itemCardDeviceName.text = this.deviceOutId
                it.itemCardDayNumber.text = this.surplusDays.toString()
                val overdueDate = this.overdueDate
                val asOfString = if (TextUtils.isEmpty(overdueDate)) {
                    ""
                } else {
                    String.format(getString(R.string.txt_card_list_end), overdueDate)
                }
                it.itemCardAsOf.text = asOfString

                this.pet?.apply {
                    it.itemCardPetHead.appHeadImage.visibility = View.VISIBLE
                    it.itemCardPetName.visibility = View.VISIBLE
                    it.itemCardPetName.text = pet!!.petName
                    ViewUtil.instance.imageLoadUrl(it.itemCardPetHead.appHeadImage, pet!!.imgurl)
                }
            }
        }
    }

    private fun setSetMeal() {
        mSetMealBean?.apply {
            val str = getString(R.string.txt_month_until) + "\t$accountFee"
            mViewBinding.tvNeedPayMoneyCn.text = str
            mViewBinding.rechargeOrderDetailCnAmount.let {
                if (hotType ==  ConstantInt.Type1) {
                    it.rechargeAmountNormalHotImage.visibility = View.VISIBLE
                } else {
                    it.rechargeAmountNormalHotImage.visibility = View.GONE
                }
                it.rechargeAmountTwoMoney.text = accountFee.toString()

                it.txtRechargeAmountName.text = name

                val perMonth = if (period > 1) {
                    String.format(getString(R.string.pet_managet_age), period)
                } else {
                    String.format(getString(R.string.pet_managet_age_1), period)
                }
                it.rechargeAmountTwoTime.text = perMonth

//                val subscriptionPlan =
//                    String.format(getString(R.string.txt_pay_amount_detail1), subscriptionFee)
                it.txtSubscriptionPlanContent.text = "数量：x1"

                val averageMonth = Utils.formatDecimal(accountFee / (12 * period), 2)
                val monthString = String.format(getString(R.string.txt_perMonth), averageMonth)
                it.rechargeAmountTwoDescription.text = monthString
            }
        }
    }

    /**
     * 去支付
     */
    private fun goPay() {
        when (mPayWay) {
            0 -> mPayCNViewModel.getWxPayOrder(this, mSetMealBean!!, mRechargeDeviceBean!!.deviceId)

            1 -> mPayCNViewModel.getAlipayOrder(
                this, mSetMealBean!!, mRechargeDeviceBean!!.deviceId
            )

        }
    }

    override fun onClick(v: View?) {
        when (v!!) {
            mViewBinding.startPayMoneyBtnCn -> goPay()
            mViewBinding.rechargeOrderDetailCnPayWay -> mQMUIBottomSheet?.show()
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        //线程退出释放
        mHandlerThread.quit()
    }
}