package com.abbidot.tracker.ui.activity.subscribe

import android.content.Intent
import android.text.TextUtils
import android.view.Gravity
import android.view.View
import androidx.activity.viewModels
import androidx.core.content.ContextCompat
import coil.load
import com.abbidot.baselibrary.constant.ConState
import com.abbidot.baselibrary.constant.EventName
import com.abbidot.baselibrary.constant.MMKVKey
import com.abbidot.baselibrary.eventbus.XEventBus
import com.abbidot.baselibrary.util.LogUtil
import com.abbidot.baselibrary.util.MMKVUtil
import com.abbidot.baselibrary.util.Utils
import com.abbidot.tracker.R
import com.abbidot.tracker.base.BaseActivity
import com.abbidot.tracker.bean.BleTrackDeviceBean
import com.abbidot.tracker.bean.PayResultBean
import com.abbidot.tracker.bean.PetBean
import com.abbidot.tracker.bean.ReceiveDeviceData
import com.abbidot.tracker.constant.ConstantInt
import com.abbidot.tracker.constant.ConstantString
import com.abbidot.tracker.constant.GetResultCallback
import com.abbidot.tracker.databinding.ActivityPaymentSuccessBinding
import com.abbidot.tracker.deprecated.ui.activity.vm.AddTrackerDeviceViewModel
import com.abbidot.tracker.ui.activity.device.wifi.AddWifiPowerZone1Activity
import com.abbidot.tracker.util.Util
import com.abbidot.tracker.util.ViewUtil
import com.abbidot.tracker.util.bluetooth.SRBleCmdUtil
import com.abbidot.tracker.util.bluetooth.SRBleUtil
import com.abbidot.tracker.vm.ConnectionDeviceViewModel
import com.abbidot.tracker.vm.PetInfoViewModel
import com.abbidot.tracker.vm.PetRelationViewModel
import com.abbidot.tracker.vm.UserProfileViewModel
import com.clj.fastble.BleManager

class PaymentSuccessActivity :
    BaseActivity<ActivityPaymentSuccessBinding>(ActivityPaymentSuccessBinding::inflate) {

    private val mAddTrackerViewModel: AddTrackerDeviceViewModel by viewModels()
    private val mConnectionDeviceViewModel: ConnectionDeviceViewModel by viewModels()
    private val mUserProfileViewModel: UserProfileViewModel by viewModels()
    private val mPetRelationViewModel: PetRelationViewModel by viewModels()
    private val mPetViewModel: PetInfoViewModel by viewModels()

    private var mPayResult: PayResultBean? = null
    private var mMac = ""
    private var mPetBean: PetBean? = null

    override fun getTopBar() = null

    override fun initData() {
        super.initData()
        intent.extras?.apply {
            mPayResult = Util.getParcelableAdaptive(
                intent, ConstantString.Amount, PayResultBean::class.java
            )
        }

        mViewBinding.apply {
            ivPaymentSuccessAnim.load(R.drawable.pwd_reset_successful_done)
            mPayResult?.let {
                LogUtil.e("充值类型rechargeType=${it.rechargeType}")

                tvPaymentSuccessDeviceId.text = it.deviceOutId
                tvPaymentSuccessExpiresOnDate.text = Utils.formatTime(
                    Utils.stringToTimestamp(
                        it.expirationTime, isUtc = true
                    ), Utils.DATE_FORMAT_PATTERN_CN4
                )
                val times = Utils.differYear(
                    System.currentTimeMillis(), Utils.stringToTimestamp(it.expirationTime)
                )
                ilPaymentSuccessCountDownLayout.tvAddSuccessDeviceExpiresDays.text = times[0]
                ilPaymentSuccessCountDownLayout.tvAddSuccessDeviceExpiresHours.text = times[1]
                ilPaymentSuccessCountDownLayout.tvAddSuccessDeviceExpiresMin.text = times[2]
            }
            setOnClickListenerViews(
                btnPaymentSuccessContinue, ilPaymentSuccessBluetoothTips.trbBleConnectState
            )

            mMac = MMKVUtil.getString(MMKVKey.FirstDeviceMac)
            if (TextUtils.isEmpty(mMac)) {
                btnPaymentSuccessContinue.setText(R.string.txt_done)
                tvPaymentSuccessActivateTip.visibility = View.INVISIBLE
                ilPaymentSuccessBluetoothTips.root.visibility = View.GONE
            } else {
                connectBle(mMac)
            }
        }
    }

    override fun liveDataObserve() {
        //接收蓝牙连接状态
        XEventBus.observe(this, EventName.ConnectDeviceState) { ble: BleTrackDeviceBean ->
            if (TextUtils.isEmpty(mMac)) return@observe
            mViewBinding.ilPaymentSuccessBluetoothTips.trbBleConnectState.let { view ->
                val bgColor = if (ble.conState == ConState.CONNECTED) {
                    setButtonEnabled(mViewBinding.btnPaymentSuccessContinue, ConstantInt.Type1)
                    view.text = getString(R.string.tracker_manage_set_ble_connect)
                    ContextCompat.getColor(mContext, R.color.cyan_color1)
                } else {
                    setButtonEnabled(mViewBinding.btnPaymentSuccessContinue, ConstantInt.Type0)
                    view.text = getString(R.string.tracker_manage_set_ble_unconnect)
                    ContextCompat.getColor(mContext, R.color.red_color4)
                }
                view.setBackgroundColor(bgColor)
                ViewUtil.instance.bleConStateToast(this, ble.conState, Gravity.CENTER)
            }
        }

        //搜索蓝牙的设备状态
        XEventBus.observe(this, EventName.ActionConDeviceState) { conState: Int ->
            if (TextUtils.isEmpty(mMac)) return@observe
            setButtonEnabled(mViewBinding.btnPaymentSuccessContinue, ConstantInt.Type0)
            if (conState == ConState.DEVICE_NOT_FOUND) {
//                ViewUtil.instance.showDialog(
//                    mContext,
//                    R.string.txt_no_search_device,
//                    object : BaseDialog.OnDialogOkListener {
//                        override fun onOkClick(dialog: BaseDialog<*>) {
//                            dialog.dismiss()
//                        }
//                    },
//                    okTextResId = R.string.txt_sure,
//                    cancelTextResId = R.string.txt_cancel
//                )
            }
            mViewBinding.ilPaymentSuccessBluetoothTips.trbBleConnectState.let { view ->
                ViewUtil.instance.bleConActionState(this, view, conState)
            }
        }

        //接收蓝牙返回数据
        XEventBus.observe(this, EventName.DeviceReceiveData) { receiveData: ReceiveDeviceData ->
            if (TextUtils.isEmpty(mMac)) return@observe
            mPayResult?.apply {
                if (mMac == receiveData.mac) {
                    val data = receiveData.data
//                    setButtonEnabled(mViewBinding.btnPaymentSuccessContinue, ConstantInt.Type1)
                    parseData(data)
                }
            }
        }


        mAddTrackerViewModel.mUpdatePayDeviceStateLiveData.observe(this) {
            dealRequestResult(it, object : GetResultCallback {
                override fun onResult(any: Any) {
                    MMKVUtil.putInt(MMKVKey.isBindDevice, ConstantInt.isBind)
                    XEventBus.post(EventName.RefreshDevice)
                    if (TextUtils.isEmpty(mMac)) {
                        XEventBus.post(EventName.PayBack)
                        finish()
                    } else SRBleUtil.instance.getConnectMacDevice(mMac)?.let { ble ->
                        SRBleUtil.instance.writeData(
                            ble.bleDevice, SRBleCmdUtil.instance.setWorkingStatus()
                        )
                    }
                }

                override fun onRequestError(exceptionCode: String?) {
                    LogUtil.e("支付成功后，更新绑定状态------->请求宠物数据错误onRequestError，再次请求")
                    if (exceptionCode == mNetworkRequestsFailLimit) {
                    } else {
                        mAddTrackerViewModel.updatePayDeviceState(
                            this@PaymentSuccessActivity, mPayResult!!.deviceId
                        )
                    }
                }
            })
        }
        //默认单位设置
        mUserProfileViewModel.mUpdateMeasureUnitLiveData.observe(this@PaymentSuccessActivity) {
            dealRequestResult(it, object : GetResultCallback {
                override fun onResult(any: Any) {
                    it.getOrNull()?.apply {
                        MMKVUtil.putInt(MMKVKey.MeasureUnit, ConstantInt.Type1)
                        PetBean().let { pet ->
                            pet.petName = "My Pet"
                            pet.deviceId = mPayResult!!.deviceId
                            pet.petType = ConstantInt.DogPetType
                            pet.gender = ConstantInt.WoMan
                            pet.macID = mMac
                            mPayResult?.let { p ->
                                pet.deviceType = p.deviceType
                            }
                            pet.birthdayDate = "2024-01-01"
                            pet.height = Utils.formatDecimal(Util.inToCm(20.0), 1).toFloat()
                            pet.weight = Utils.formatDecimal(Util.lbsToKg(25.0), 1).toFloat()
                            mPetBean = pet
                            mPetViewModel.addPet(this@PaymentSuccessActivity, pet)
                        }
                    }
                }
            })
        }
        //添加默认宠物
        mPetViewModel.mAddPetLiveData.observe(this@PaymentSuccessActivity) {
            dealRequestResult(it, object : GetResultCallback {
                override fun onResult(any: Any) {
                    it.getOrNull()?.let { pet ->
                        mPetBean?.let { petBean ->
                            petBean.petId = pet.petId
                            mPetRelationViewModel.bindPet(
                                this@PaymentSuccessActivity, petBean.deviceId, petBean.petId
                            )
                        }
                    }
                }
            })
        }
        //绑定默认宠物
        mPetRelationViewModel.mBindPetLiveData.observe(this@PaymentSuccessActivity) {
            dealRequestResult(it, object : GetResultCallback {
                override fun onResult(any: Any) {
                    XEventBus.post(EventName.RefreshPet)
                    showToast(R.string.txt_bind_success, isFinish = true)
                    mViewBinding.root.postDelayed({
                        MMKVUtil.putInt(MMKVKey.isBindPet, ConstantInt.isBind)
                        mPetBean?.apply {
                            val intent = Intent(mContext, AddWifiPowerZone1Activity::class.java)
                            intent.putExtra(ConstantString.Pet, this)
                            intent.putExtra(ConstantString.isFirstBind, true)
                            startActivity(intent)
                        }
                    }, 1500)
                }
            })
        }
    }

    /**
     * 解析数据
     */
    private fun parseData(data: ByteArray?) {
        if (null != data && data.isNotEmpty()) {
            val data0 = SRBleCmdUtil.instance.byteToInt(data[0])
            val data1 = SRBleCmdUtil.instance.byteToInt(data[1])
            val data2 = SRBleCmdUtil.instance.byteToInt(data[2])
            if (data0 == 0x1A && data1 == 1 && data2 == 0) {
                MMKVUtil.putString(MMKVKey.FirstDeviceMac, "")
                XEventBus.post(EventName.PayBack)
                mPayResult?.let {
                    if (it.rechargeType == ConstantInt.Type0 || it.rechargeType == ConstantInt.Type1) {
                        mUserProfileViewModel.updateMeasureUnit(ConstantInt.Type1)
//                        val intent = Intent(mContext, FirstSetPetTypeActivity::class.java)
//                        intent.putExtra(ConstantString.isFirstBind, true)
//                        startActivity(intent)
                    } else finish()
                }
            }
        }
    }

    private fun connectBle(mac: String) {
        //是否连接了蓝牙
        if (BleManager.getInstance().isConnected(mac)) {
            mViewBinding.ilPaymentSuccessBluetoothTips.trbBleConnectState.let {
                it.setBackgroundColor(
                    ContextCompat.getColor(mContext, R.color.cyan_color1)
                )
                it.text = getString(R.string.tracker_manage_set_ble_connect)
            }
        } else {
            setButtonEnabled(mViewBinding.btnPaymentSuccessContinue, ConstantInt.Type0)
            mConnectionDeviceViewModel.connectDeviceToMac(
                this@PaymentSuccessActivity, mac
            )
        }
    }

    /**
     * 手动连接/断开设备
     */
    private fun connectionBtn(btnString: String) {
        mPayResult?.apply {
            if (btnString == getString(R.string.tracker_manage_set_ble_unconnect)) {
                connectBle(mMac)
            } else if (btnString == getString(R.string.tracker_manage_set_ble_connect)) {
//                ViewUtil.instance.operateDialogTips(mContext, R.string.txt_disconnect_tips) {
//                    SRBleUtil.instance.disconnectToMac(mac)
//                }
            }
        }
    }

    private fun payContinue() {
        mPayResult?.apply {
            if (rechargeType == ConstantInt.Type0 || rechargeType == ConstantInt.Type1) {
                mViewBinding.btnPaymentSuccessContinue.isEnabled = false
                //刷新设备绑定
                mAddTrackerViewModel.updatePayDeviceState(this@PaymentSuccessActivity, deviceId)
            } else if (TextUtils.isEmpty(mMac)) {
                XEventBus.post(EventName.PayBack)
                finish()
            } else SRBleUtil.instance.getConnectMacDevice(mMac)?.let {
                setButtonEnabled(mViewBinding.btnPaymentSuccessContinue, ConstantInt.Type0)
                SRBleUtil.instance.writeData(it.bleDevice, SRBleCmdUtil.instance.setWorkingStatus())
            }
        }
    }

    override fun onClick(v: View?) {
        mViewBinding.apply {
            when (v!!) {
                ilPaymentSuccessBluetoothTips.trbBleConnectState -> connectionBtn(
                    ilPaymentSuccessBluetoothTips.trbBleConnectState.text.toString()
                )

                btnPaymentSuccessContinue -> payContinue()
            }
        }
    }
}