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

import android.content.Intent
import android.graphics.Typeface
import android.view.View
import androidx.activity.viewModels
import androidx.lifecycle.lifecycleScope
import com.abbidot.baselibrary.constant.EventName
import com.abbidot.baselibrary.constant.MMKVKey
import com.abbidot.baselibrary.eventbus.XEventBus
import com.abbidot.baselibrary.util.MMKVUtil
import com.abbidot.tracker.R
import com.abbidot.tracker.base.BaseActivity
import com.abbidot.tracker.base.BaseDialog
import com.abbidot.tracker.bean.DeviceBean
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.database.MyDatabase
import com.abbidot.tracker.databinding.ActivityDeleteTracker1Binding
import com.abbidot.tracker.dialog.CommonDialog1
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.TrackerSetViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

class DeleteTracker1Activity :
    BaseActivity<ActivityDeleteTracker1Binding>(ActivityDeleteTracker1Binding::inflate) {

    private val mTrackerSetViewModel: TrackerSetViewModel by viewModels()

    private var mDeviceBean: DeviceBean? = null
    private var isOnlyBindOneDevice = false

    override fun getTopBar() = mViewBinding.ilDeleteTracker1TopBar.titleTopBar

    override fun initData() {
        super.initData()
        setTopBarTitle("")
        setLeftBackImage(R.drawable.icon_white_back_svg)

        intent.extras?.apply {
            isOnlyBindOneDevice = getBoolean(ConstantString.isCheck, false)
            mDeviceBean = Util.getParcelableAdaptive(
                intent, ConstantString.DeviceInfo, DeviceBean::class.java
            )
        }

        mViewBinding.apply {
            setOnClickListenerViews(btnCancelDeleteTracker1, btnNextDeleteTracker1)
        }
    }

    override fun liveDataObserve() {
        //解绑设备/删除设备
        mTrackerSetViewModel.mUnbindDeviceLiveData.observe(this@DeleteTracker1Activity) {
            dealRequestResult(it, object : GetResultCallback {
                override fun onResult(any: Any) {
                    lifecycleScope.launch {
                        withContext(Dispatchers.IO) {
                            mDeviceBean?.let { device ->
                                //是否连接了蓝牙
                                if (SRBleUtil.instance.isMacConnect(device.macId)) {
                                    SRBleUtil.instance.getConnectMacDevice(device.macId)
                                        ?.let { ble ->
                                            SRBleUtil.instance.writeData(
                                                ble.bleDevice,
                                                SRBleCmdUtil.instance.setWorkingStatus(status = 2)
                                            )
                                        }
                                }
                                //删除设备成功后,把本地数据库中的设备也删除
                                MyDatabase.deviceDao().deleteByParams(
                                    ConstantString.DeviceId,
                                    device.deviceId,
                                    MyDatabase.DEVICE_TABLE
                                )
                                runOnUiThread {
                                    showDeleteDialog()
                                }
                            }
                        }
                    }
                }

                override fun onRequestError(exceptionCode: String?) {
                    super.onRequestError(exceptionCode)
                    setButtonEnabled(mViewBinding.btnNextDeleteTracker1, ConstantInt.Type1)
                }
            })
        }
        //接收蓝牙返回数据
        XEventBus.observe(this, EventName.DeviceReceiveData) { receiveData: ReceiveDeviceData ->
            mDeviceBean?.apply {
                if (macId == receiveData.mac) {
                    receiveData.data?.let {
                        val data0 = SRBleCmdUtil.instance.byteToInt(it[0])
                        if (data0 == 0x1A) {
                            SRBleUtil.instance.disconnectToMac(macId)
                        }
                    }
                }
            }
        }
    }

    private fun showDeleteDialog() {
        if (isOnlyBindOneDevice) {
            XEventBus.post(EventName.LogOut)
            MMKVUtil.putInt(MMKVKey.isBindDevice, ConstantInt.Type0)
            MMKVUtil.putInt(MMKVKey.isBindPet, ConstantInt.Type0)
        } else {
            XEventBus.post(EventName.DeleteDevice)
        }
        CommonDialog1(
            mContext,
            "",
            getString(R.string.txt_unbind_success),
            false,
            5f,
            Typeface.BOLD,
            R.color.data_black_color,
            false,
            okClickListener = object : BaseDialog.OnDialogOkListener {
                override fun onOkClick(dialog: BaseDialog<*>) {
                    if (isOnlyBindOneDevice) {
                        val intent = Intent(mContext, AddNewTracker1Activity::class.java)
                        intent.putExtra(ConstantString.isFirstBind, true)
                        startActivityFinish(intent)
                    } else {
                        finish()
                    }
                }
            }).show()
    }

    private fun sureDeleteDevice() {
        ViewUtil.instance.showDialog(
            mContext, getString(R.string.txt_unbind_tips), object : BaseDialog.OnDialogOkListener {
                override fun onOkClick(dialog: BaseDialog<*>) {
                    dialog.dismiss()
                    mDeviceBean?.apply {
                        setButtonEnabled(mViewBinding.btnNextDeleteTracker1, ConstantInt.Type0)
                        mTrackerSetViewModel.unbindDevice(this@DeleteTracker1Activity, deviceId)
                    }
                }
            }, okTextResId = R.string.txt_sure
        )
    }

    override fun onClick(v: View?) {
        if (isLimitClick()) return
        mViewBinding.apply {
            when (v!!) {
                btnCancelDeleteTracker1 -> finish()
                btnNextDeleteTracker1 -> {
                    sureDeleteDevice()
//                    Intent(mContext, DeleteTracker2Activity::class.java).let {
//                        it.putExtra(ConstantString.DeviceInfo, mDeviceBean)
//                        it.putExtra(ConstantString.isCheck, isOnlyBindOneDevice)
//                        startActivityFinish(it)
//                    }
                }
            }
        }
    }
}