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

import android.content.Intent
import android.text.TextUtils
import android.view.View
import android.widget.NumberPicker
import androidx.activity.viewModels
import com.abbidot.baselibrary.constant.ConState
import com.abbidot.baselibrary.constant.EventName
import com.abbidot.baselibrary.eventbus.XEventBus
import com.abbidot.tracker.R
import com.abbidot.tracker.base.BaseActivity
import com.abbidot.tracker.bean.BleTrackDeviceBean
import com.abbidot.tracker.bean.DataBean
import com.abbidot.tracker.constant.ConstantInt
import com.abbidot.tracker.constant.ConstantString
import com.abbidot.tracker.constant.GetResultCallback
import com.abbidot.tracker.databinding.ActivityAddNewTracker3Binding
import com.abbidot.tracker.util.Util
import com.abbidot.tracker.util.ViewUtil
import com.abbidot.tracker.util.bluetooth.SRBleUtil
import com.abbidot.tracker.vm.ConnectionDeviceViewModel
import com.abbidot.tracker.vm.TrackerSetViewModel

class AddNewTracker3Activity :
    BaseActivity<ActivityAddNewTracker3Binding>(ActivityAddNewTracker3Binding::inflate),
    NumberPicker.OnValueChangeListener {

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

    private var isFirstBind = false
    private var mDeviceOutId = ""
    private var mDeviceId = ""
    private var mScanDeviceList: ArrayList<DataBean>? = null
    private var mConBleMac = ""

    override fun getTopBar() = mViewBinding.ilAddNewTracker3TopBar.titleTopBar

    override fun initData() {
        super.initData()
        setTopBarTitle(R.string.txt_add_new_tracker)
        setLeftBackImage(R.drawable.icon_white_back_svg)
        mRightImageButton = addRightImageButton(R.drawable.icon_refresh)

        intent.extras?.apply {
            isFirstBind = getBoolean(ConstantString.isFirstBind, false)
            mDeviceOutId = getString(ConstantString.DeviceOutId, "")
            mScanDeviceList = Util.getParcelableArrayListAdaptive(
                intent, ConstantString.DeviceInfo, DataBean::class.java
            )
        }

        if (null == mScanDeviceList) finish()

        mViewBinding.apply {

            mScanDeviceList?.let {
                if (it.size == 1) {
                    mDeviceOutId = it[0].name
                    tvAddNewTracker3DeviceOutId.visibility = View.VISIBLE
                    rlAddNewTracker3DeviceLayout.visibility = View.GONE
                    tvAddNewTracker3DeviceOutId.text = mDeviceOutId
                } else if (it.size > 1) {
                    mDeviceOutId = it[0].name
                    val deviceOutIds = mutableListOf<String>()
                    for (d in it) {
                        deviceOutIds.add(d.name)
                    }
                    tvAddNewTracker3DeviceOutId.visibility = View.GONE
                    rlAddNewTracker3DeviceLayout.visibility = View.VISIBLE
                    npAddNewTracker3DeviceList.let { np ->
                        ViewUtil.instance.setNumberPickerAttributes(
                            mContext,
                            np,
                            0,
                            it.size - 1,
                            0,
                            26,
                            valueChangeListener = this@AddNewTracker3Activity,
                            removeUpDownLine = true,
                            loopSelector = false
                        )
                        np.displayedValues = deviceOutIds.toTypedArray()
                    }
                }
            }

            setOnClickListenerViews(btnPairTrackerNo, btnPairTrackerYes, mRightImageButton)
        }
    }

    override fun liveDataObserve() {
        //接收蓝牙连接状态
        XEventBus.observe(this, EventName.ConnectDeviceState) { ble: BleTrackDeviceBean ->
            setButtonEnabled(mViewBinding.btnPairTrackerYes, ConstantInt.Type1)
            if (ble.conState == ConState.CONNECTED) {
                mConBleMac = ble.mac
                val intent = Intent(mContext, AddPairedSuccessActivity::class.java)
                intent.putExtra(ConstantString.DeviceOutId, mDeviceOutId)
                intent.putExtra(ConstantString.isFirstBind, isFirstBind)
                intent.putExtra(ConstantString.DeviceId, mDeviceId)
                intent.putExtra(ConstantString.Mac, ble.mac)
                startActivity(intent)
            }
        }
        //搜索蓝牙的设备状态
        XEventBus.observe(this, EventName.ActionConDeviceState) { conState: Int ->
            if (conState == ConState.DEVICE_NOT_FOUND) {
                setButtonEnabled(mViewBinding.btnPairTrackerYes, ConstantInt.Type1)
                showToast(R.string.txt_ble_connect_fail)
            }
        }

        XEventBus.observe(this, EventName.RefreshDevice) {
            finish()
        }

        mTrackerSetViewModel.mAddBindDeviceLiveData.observe(this) {
            setButtonEnabled(mViewBinding.btnPairTrackerYes, ConstantInt.Type1)
            dealRequestResult(it, object : GetResultCallback {
                override fun onResult(any: Any) {
                    it.getOrNull()?.apply {
                        mDeviceId = deviceId
                        setButtonEnabled(mViewBinding.btnPairTrackerYes, ConstantInt.Type0)
                        //连接蓝牙，方便发送激活指令
                        mConnectionDeviceViewModel.connectDeviceToDeviceOutId(
                            this@AddNewTracker3Activity, mDeviceOutId
                        )
                    }
                }
            })
        }
    }

    override fun onValueChange(picker: NumberPicker?, oldVal: Int, newVal: Int) {
        mScanDeviceList?.let {
            mDeviceOutId = it[newVal].name
        }
    }

    override fun leftBackOnClick() {
        disconnectBle()
        super.leftBackOnClick()
    }

    /**
     * 防止没支付后退页面。扫描不到设备情况
     */
    private fun disconnectBle() {
        if (!TextUtils.isEmpty(mConBleMac)) {
            SRBleUtil.instance.disconnectToMac(mConBleMac)
        }
    }

    override fun onClick(v: View?) {
        mViewBinding.apply {
            when (v!!) {
                btnPairTrackerNo -> {
                    val intent = Intent(mContext, AddNewTracker4Activity::class.java)
                    intent.putExtra(ConstantString.isFirstBind, isFirstBind)
                    startActivity(intent)
                }

                btnPairTrackerYes -> {
                    disconnectBle()
                    setButtonEnabled(mViewBinding.btnPairTrackerYes, ConstantInt.Type0)
                    mTrackerSetViewModel.bindDevice(
                        this@AddNewTracker3Activity, mDeviceOutId
                    )
                }

                mRightImageButton -> {
                    disconnectBle()
                    val intent = Intent(mContext, AddNewTracker2Activity::class.java)
                    intent.putExtra(ConstantString.isFirstBind, isFirstBind)
                    startActivityFinish(intent)
                }
            }
        }
    }


}