package com.abbidot.tracker.ui.activity.device

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 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.PetBean
import com.abbidot.tracker.bean.ReceiveDeviceData
import com.abbidot.tracker.bean.SubscriptionsOrderBean
import com.abbidot.tracker.constant.ConstantInt
import com.abbidot.tracker.constant.ConstantString
import com.abbidot.tracker.constant.GetResultCallback
import com.abbidot.tracker.databinding.ActivityAddPairedSuccessBinding
import com.abbidot.tracker.deprecated.ui.activity.vm.AddTrackerDeviceViewModel
import com.abbidot.tracker.ui.activity.device.wifi.AddWifiPowerZone1Activity
import com.abbidot.tracker.ui.activity.subscribe.SubscriptionPlanActivity
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 AddPairedSuccessActivity :
    BaseActivity<ActivityAddPairedSuccessBinding>(ActivityAddPairedSuccessBinding::inflate) {

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

    private lateinit var mSubscriptionsOrderBean: SubscriptionsOrderBean

    private var isFirstBind = false
    private var mDeviceOutId = ""
    private var mDeviceId = ""
    private var mMac = ""

    //设备类型
    private var mType = ConstantInt.Type1
    private var mPetBean: PetBean? = null

    //判断设备可用套餐状态
    private var mAvailableOrder = 0

    override fun getTopBar() = mViewBinding.ilAddPairedSuccessTopBar.titleTopBar

    override fun initData() {
        super.initData()
        setTopBarTitle("")

        intent.extras?.apply {
            isFirstBind = getBoolean(ConstantString.isFirstBind, false)
            mDeviceId = getString(ConstantString.DeviceId, "")
            mMac = getString(ConstantString.Mac, "")
            mType = getInt(ConstantString.Type, ConstantInt.Type1)
            mDeviceOutId = getString(ConstantString.DeviceOutId, "")
        }

        mSubscriptionsOrderBean = SubscriptionsOrderBean()

        mViewBinding.apply {
            tvPairSuccessDeviceOutId.text = mDeviceOutId
            ivPairSuccessDeviceImage.setImageResource(Util.getDeviceTypeImage(mType))
            setOnClickListenerViews(btnPairSuccessActivate)
        }
        setButtonEnabled(mViewBinding.btnPairSuccessActivate, ConstantInt.Type0)
        mAddTrackerViewModel.getDeviceOrderStatus(this@AddPairedSuccessActivity, mDeviceOutId)
    }

    override fun liveDataObserve() {
        mAddTrackerViewModel.apply {
            //获取设备套餐可用状态
            mDeviceOrderStatusLiveData.observe(this@AddPairedSuccessActivity) {
                dealRequestResult(it, object : GetResultCallback {
                    override fun onResult(any: Any) {
                        it.getOrNull()?.apply {

                            MMKVUtil.putString(MMKVKey.FirstDeviceId, mDeviceId)
                            MMKVUtil.putString(MMKVKey.FirstDeviceOutId, mDeviceOutId)
                            MMKVUtil.putString(MMKVKey.FirstDeviceMac, mMac)

                            mSubscriptionsOrderBean.let { o ->
                                o.deviceId = mDeviceId
                                o.userId = MMKVUtil.getString(MMKVKey.UserId)
                            }
                            mNetworkRequestsFailRetryCount = 0

                            mAvailableOrder = availableOrder
                            //判断设备是否有可用套餐
                            if (availableOrder == ConstantInt.Type1) {
                                bleNotify()
                                connectBle(mMac)
                            } else {
                                setButtonEnabled(
                                    mViewBinding.btnPairSuccessActivate, ConstantInt.Type1
                                )
                            }
                        }
                    }

                    override fun onRequestError(exceptionCode: String?) {
                        LogUtil.e("获取设备套餐可用状态---->请求错误onRequestError，再次请求")
                        if (exceptionCode == mNetworkRequestsFailLimit) {
                            finish()
                        } else {
                            mAddTrackerViewModel.getDeviceOrderStatus(
                                this@AddPairedSuccessActivity, mDeviceOutId
                            )
                        }
                    }
                })
            }

            //获取设备sim卡IccId
            mGetIccIdLiveData.observe(this@AddPairedSuccessActivity) {
                dealRequestResult(it, object : GetResultCallback {
                    override fun onResult(any: Any) {
                        it.getOrNull()?.apply {
                            mSubscriptionsOrderBean.deviceOutId = mDeviceOutId
                            mSubscriptionsOrderBean.iccid = iccid

                            val intent = Intent(mContext, SubscriptionPlanActivity::class.java)
                            intent.putExtra(ConstantString.LkSetMeal, mSubscriptionsOrderBean)
                            intent.putExtra(ConstantString.Type, mType)
                            intent.putExtra(ConstantString.isFirstBind, isFirstBind)
                            startActivityFinish(intent)
                        }
                    }

                    override fun onRequestError(exceptionCode: String?) {
                        super.onRequestError(exceptionCode)
                        setButtonEnabled(mViewBinding.btnPairSuccessActivate, ConstantInt.Type1)
                    }
                })
            }

            //更新设备绑定状态
            mUpdatePayDeviceStateLiveData.observe(this@AddPairedSuccessActivity) {
                dealRequestResult(it, object : GetResultCallback {
                    override fun onResult(any: Any) {
                        MMKVUtil.putInt(MMKVKey.isBindDevice, ConstantInt.isBind)
                        XEventBus.post(EventName.RefreshDevice)

                        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) {
                            setButtonEnabled(mViewBinding.btnPairSuccessActivate, ConstantInt.Type1)
                        } else {
                            mAddTrackerViewModel.updatePayDeviceState(
                                this@AddPairedSuccessActivity, mSubscriptionsOrderBean.deviceId
                            )
                        }
                    }
                })
            }

            //默认单位设置
            mUserProfileViewModel.mUpdateMeasureUnitLiveData.observe(this@AddPairedSuccessActivity) {
                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 = mDeviceId
                                pet.petType = ConstantInt.DogPetType
                                pet.gender = ConstantInt.WoMan
                                pet.macID = mMac
                                pet.deviceType = mType
                                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@AddPairedSuccessActivity, pet)
                            }
                        }
                    }

                    override fun onRequestError(exceptionCode: String?) {
                        super.onRequestError(exceptionCode)
                        setButtonEnabled(mViewBinding.btnPairSuccessActivate, ConstantInt.Type1)
                    }
                })
            }
            //添加默认宠物
            mPetViewModel.mAddPetLiveData.observe(this@AddPairedSuccessActivity) {
                dealRequestResult(it, object : GetResultCallback {
                    override fun onResult(any: Any) {
                        it.getOrNull()?.let { pet ->
                            mPetBean?.let { petBean ->
                                petBean.petId = pet.petId
                                mPetRelationViewModel.bindPet(
                                    this@AddPairedSuccessActivity, petBean.deviceId, petBean.petId
                                )
                            }
                        }
                    }

                    override fun onRequestError(exceptionCode: String?) {
                        super.onRequestError(exceptionCode)
                        setButtonEnabled(mViewBinding.btnPairSuccessActivate, ConstantInt.Type1)
                    }
                })
            }
            //绑定默认宠物
            mPetRelationViewModel.mBindPetLiveData.observe(this@AddPairedSuccessActivity) {
//                setButtonEnabled(mViewBinding.btnPairSuccessActivate, ConstantInt.Type1)
                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)
                            if (isFirstBind) {
                                mPetBean?.apply {
                                    val intent =
                                        Intent(mContext, AddWifiPowerZone1Activity::class.java)
                                    intent.putExtra(ConstantString.Pet, this)
                                    intent.putExtra(ConstantString.isFirstBind, isFirstBind)
                                    startActivity(intent)
                                }
                            }
                        }, 1500)
                    }

//                    override fun onRequestError(exceptionCode: String?) {
//                        super.onRequestError(exceptionCode)
//                        setButtonEnabled(mViewBinding.btnPairSuccessActivate, ConstantInt.Type1)
//                    }
                })
            }
        }
    }

    private fun bleNotify() {
        //接收蓝牙连接状态
        XEventBus.observe(this, EventName.ConnectDeviceState) { ble: BleTrackDeviceBean ->
            if (TextUtils.isEmpty(mMac)) return@observe
            mViewBinding.ilPairSuccessBluetoothTips.trbBleConnectState.let { view ->
                val bgColor = if (ble.conState == ConState.CONNECTED) {
                    setButtonEnabled(mViewBinding.btnPairSuccessActivate, ConstantInt.Type1)
                    view.text = getString(R.string.tracker_manage_set_ble_connect)
                    ContextCompat.getColor(mContext, R.color.cyan_color1)
                } else {
                    setButtonEnabled(mViewBinding.btnPairSuccessActivate, 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.btnPairSuccessActivate, 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.ilPairSuccessBluetoothTips.trbBleConnectState.let { view ->
                ViewUtil.instance.bleConActionState(this, view, conState)
            }
        }

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

    /**
     * 解析数据
     */
    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) {
                mUserProfileViewModel.updateMeasureUnit(ConstantInt.Type1)
            }
        }
    }

    private fun connectBle(mac: String) {
        mViewBinding.ilPairSuccessBluetoothTips.root.visibility = View.VISIBLE
        //是否连接了蓝牙
        if (BleManager.getInstance().isConnected(mac)) {
            mViewBinding.ilPairSuccessBluetoothTips.trbBleConnectState.let {
                it.setBackgroundColor(
                    ContextCompat.getColor(mContext, R.color.cyan_color1)
                )
                it.text = getString(R.string.tracker_manage_set_ble_connect)
            }
            setButtonEnabled(mViewBinding.btnPairSuccessActivate, ConstantInt.Type1)
        } else {
            mConnectionDeviceViewModel.connectDeviceToMac(this@AddPairedSuccessActivity, mac)
        }
    }


    private fun addBindActivateDevice() {
        if (TextUtils.isEmpty(mDeviceOutId)) {
            showToast(R.string.txt_no_dfu)
            return
        }
        setButtonEnabled(mViewBinding.btnPairSuccessActivate, ConstantInt.Type0)
        if (mAvailableOrder == ConstantInt.Type1) {
            //刷新设备绑定
            mAddTrackerViewModel.updatePayDeviceState(this@AddPairedSuccessActivity, mDeviceId)
        } else {
            mAddTrackerViewModel.getIccId(this@AddPairedSuccessActivity, mDeviceOutId)
        }
    }

    override fun leftBackOnClick() {
        if (!TextUtils.isEmpty(mMac)) {
            SRBleUtil.instance.disconnectToMac(mMac)
        }
        super.leftBackOnClick()
    }

    override fun onClick(v: View?) {
        mViewBinding.apply {
            when (v!!) {
                btnPairSuccessActivate -> addBindActivateDevice()
            }
        }
    }
}