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.core.content.ContextCompat
import androidx.lifecycle.lifecycleScope
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.MMKVUtil
import com.abbidot.tracker.R
import com.abbidot.tracker.base.BaseActivity
import com.abbidot.tracker.base.BaseDialog
import com.abbidot.tracker.bean.BleTrackDeviceBean
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.ActivityDeleteTracker2Binding
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.ConnectionDeviceViewModel
import com.abbidot.tracker.vm.TrackerSetViewModel
import com.clj.fastble.BleManager
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

class DeleteTracker2Activity :
    BaseActivity<ActivityDeleteTracker2Binding>(ActivityDeleteTracker2Binding::inflate) {

    private val mConnectionDeviceViewModel: ConnectionDeviceViewModel by viewModels()
    private val mTrackerSetViewModel: TrackerSetViewModel by viewModels()

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

    override fun getTopBar() = mViewBinding.ilDeleteTracker2TopBar.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 {
            setButtonEnabled(btnDeleteDeleteTracker2)
            setOnClickListenerViews(
                btnCancelDeleteTracker2,
                btnDeleteDeleteTracker2,
                ilDeleteTracker2BluetoothTips.trbBleConnectState
            )

            mDeviceBean?.let { device ->
                val str = String.format(getString(R.string.txt_con_tracker_dec), device.deviceOutId)
                tvDeleteTracker2Dec.text = str

                connectBle()
            }
        }
    }

    private fun connectBle() {
        mDeviceBean?.let { device ->
            //是否连接了蓝牙
            if (BleManager.getInstance().isConnected(device.macId)) {
                setButtonEnabled(mViewBinding.btnDeleteDeleteTracker2, ConstantInt.Type1)
                mViewBinding.ilDeleteTracker2BluetoothTips.trbBleConnectState.let {
                    it.setBackgroundColor(
                        ContextCompat.getColor(mContext, R.color.cyan_color1)
                    )
                    it.text = getString(R.string.tracker_manage_set_ble_connect)
                }
            } else {
                mConnectionDeviceViewModel.connectDeviceToMac(
                    this@DeleteTracker2Activity, device.macId
                )
            }
        }
    }

    override fun liveDataObserve() {
        //接收蓝牙连接状态
        XEventBus.observe(this, EventName.ConnectDeviceState) { trackDevice: BleTrackDeviceBean ->
            showLoading(false)
            mDeviceBean?.apply {
                if (trackDevice.mac == macId) {
                    mViewBinding.ilDeleteTracker2BluetoothTips.trbBleConnectState.let { view ->
                        val bgColor = if (trackDevice.conState == ConState.CONNECTED) {
                            setButtonEnabled(
                                mViewBinding.btnDeleteDeleteTracker2, ConstantInt.Type1
                            )
                            view.text = getString(R.string.tracker_manage_set_ble_connect)
                            ContextCompat.getColor(mContext, R.color.cyan_color1)
                        } else {
                            setButtonEnabled(
                                mViewBinding.btnDeleteDeleteTracker2, ConstantInt.Type0
                            )
                            view.text = getString(R.string.tracker_manage_set_ble_unconnect)
                            ContextCompat.getColor(mContext, R.color.red_color4)
                        }
                        view.setBackgroundColor(bgColor)
//                        ViewUtil.instance.bleConState(
//                            this@DeleteTracker2Activity, trackDevice.conState, Gravity.CENTER
//                        )
                    }
                }
            }
        }

        //搜索蓝牙的设备状态
        XEventBus.observe(this, EventName.ActionConDeviceState) { conState: Int ->
            setButtonEnabled(mViewBinding.btnDeleteDeleteTracker2, 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.ilDeleteTracker2BluetoothTips.trbBleConnectState.let { view ->
                ViewUtil.instance.bleConActionState(this, view, conState)
            }
        }

        //接收蓝牙返回数据
        XEventBus.observe(this, EventName.DeviceReceiveData) { receiveData: ReceiveDeviceData ->
            mDeviceBean?.apply {
                if (macId == receiveData.mac) {
                    val data = receiveData.data
                    parseData(data)
                }
            }
        }

        //解绑设备/删除设备
        mTrackerSetViewModel.mUnbindDeviceLiveData.observe(this@DeleteTracker2Activity) {
            dealRequestResult(it, object : GetResultCallback {
                override fun onResult(any: Any) {
//                    showToast(R.string.txt_delete_success)
                    lifecycleScope.launch {
                        withContext(Dispatchers.IO) {
                            mDeviceBean?.let { device ->
                                SRBleUtil.instance.disconnectToMac(device.macId)
                                //删除设备成功后,把本地数据库中的设备也删除
                                MyDatabase.deviceDao().deleteByParams(
                                    ConstantString.DeviceId,
                                    device.deviceId,
                                    MyDatabase.DEVICE_TABLE
                                )
                                runOnUiThread {
                                    showDeleteDialog()
                                }
                            }
                        }
                    }
                }

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

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

    /**
     * 解析数据
     */
    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 == 0x19 && data1 == 1 && data2 == 0) {
                mDeviceBean?.apply {
                    mTrackerSetViewModel.unbindDevice(this@DeleteTracker2Activity, deviceId)
                }
            }
        }
    }

    private fun deleteTracker() {
        mDeviceBean?.apply {
            //是否连接了蓝牙
            if (BleManager.getInstance().isConnected(macId)) {
                SRBleUtil.instance.getConnectMacDevice(macId)?.let {
                    setButtonEnabled(mViewBinding.btnDeleteDeleteTracker2, ConstantInt.Type0)
                    setButtonEnabled(mViewBinding.btnCancelDeleteTracker2, ConstantInt.Type0)
                    SRBleUtil.instance.writeData(it.bleDevice, SRBleCmdUtil.instance.factoryReset())
                }
            } else {
                showToast(R.string.tracker_manage_set_ble_unconnect)
            }
        }
    }

    override fun onClick(v: View?) {
        mViewBinding.apply {
            when (v!!) {
                btnCancelDeleteTracker2 -> finish()
                btnDeleteDeleteTracker2 -> deleteTracker()
                ilDeleteTracker2BluetoothTips.trbBleConnectState -> mDeviceBean?.apply {
                    ViewUtil.instance.connectionBtn(
                        mContext,
                        ilDeleteTracker2BluetoothTips.trbBleConnectState.text.toString(),
                        macId
                    ) {
                        connectBle()
                    }
                }
            }
        }
    }
}