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

import android.animation.AnimatorSet
import android.content.Intent
import android.text.TextUtils
import android.view.View
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.baselibrary.list.BaseRecyclerAdapter
import com.abbidot.baselibrary.util.LogUtil
import com.abbidot.tracker.R
import com.abbidot.tracker.adapter.ScanDeviceAdapter
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.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.ViewUtil
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 com.clj.fastble.callback.BleScanCallback
import com.clj.fastble.data.BleDevice
import com.clj.fastble.scan.BleScanRuleConfig
import com.clj.fastble.utils.HexUtil
import com.qmuiteam.qmui.util.QMUIDisplayHelper

class AddNewTracker3Activity :
    BaseActivity<ActivityAddNewTracker3Binding>(ActivityAddNewTracker3Binding::inflate) {

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

    private var isFirstBind = false
    private var mDeviceId = ""
    private var mDeviceOutId = ""
    private var mConBleMac = ""
    private var mType = ConstantInt.Type1

    private lateinit var mScanDeviceAdapter: ScanDeviceAdapter

    private var mAnimatorSet: AnimatorSet? = null

    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)

        intent.extras?.apply {
            isFirstBind = getBoolean(ConstantString.isFirstBind, false)
        }

        mScanDeviceAdapter = ScanDeviceAdapter(mContext, mutableListOf()).apply {
            setOnItemClickListener(object : BaseRecyclerAdapter.OnItemClickListener {
                override fun onItemClick(itemView: View?, pos: Int) {
                    mViewBinding.ivAddNewTracker3RefreshBtn.isEnabled = false
                    if (isConnect) return
                    SRBleUtil.instance.cancelBleScan("AddNewTracker2Activity,开始连接蓝牙,取消蓝牙扫描")
                    disconnectBle()
                    getData().let {
                        isConnect = true
                        it[pos].conState = ConState.CONNECTING
                        notifyItemRangeChanged(0, it.size)
                        mDeviceOutId = it[pos].deviceOutId
                        mConBleMac = it[pos].macId
                        mType = it[pos].type
                        mTrackerSetViewModel.bindDevice(
                            this@AddNewTracker3Activity, mDeviceOutId
                        )
                    }
                }
            })
        }
        mViewBinding.apply {
            ViewUtil.instance.setRecyclerViewVerticalLinearLayout(
                mContext,
                rvAddNewTracker3DeviceList,
                mScanDeviceAdapter,
                top = QMUIDisplayHelper.dpToPx(16)
            )

            setOnClickListenerViews(ivAddNewTracker3RefreshBtn)
        }
        startScanBle()
    }

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

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

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

                override fun onInterceptCode() {
                    super.onInterceptCode()
                    mViewBinding.ivAddNewTracker3RefreshBtn.isEnabled = true
                    setNoConnectState()
                }

                override fun onRequestError(exceptionCode: String?) {
                    super.onRequestError(exceptionCode)
                    setNoConnectState()
                    mViewBinding.ivAddNewTracker3RefreshBtn.isEnabled = true
                }
            })
        }
    }

    private fun setNoConnectState() {
        mScanDeviceAdapter.apply {
            getData().let {
                if (it.size > 0) {
                    isConnect = false
                    for (device in it) {
                        if (device.conState == ConState.CONNECTING) device.conState =
                            ConState.DISCONNECTED
                    }
                    notifyItemRangeChanged(0, it.size)
                }
            }
        }
    }

    private fun startScanBle() {
        SRBleUtil.instance.cancelBleScan("AddNewTracker2Activity,已经在扫描蓝牙,取消蓝牙扫描")

        mScanDeviceAdapter.getData().let { list ->
            mScanDeviceAdapter.notifyItemRangeRemoved(0, list.size)
            list.clear()
            mViewBinding.rvAddNewTracker3DeviceList.visibility = View.GONE
        }
        mViewBinding.ivAddNewTracker3RefreshBtn.let {
            it.isEnabled = false

            if (null == mAnimatorSet) {
                mAnimatorSet = ViewUtil.instance.viewRotationAnimator(it, true)
            } else {
                mAnimatorSet!!.start()
            }
        }
        // 扫描超时时间，可选
        val scanRuleConfig = BleScanRuleConfig.Builder().setScanTimeOut(15 * 1000).build()
        BleManager.getInstance().initScanRule(scanRuleConfig)
        BleManager.getInstance().scan(object : BleScanCallback() {
            override fun onScanStarted(success: Boolean) {
                LogUtil.e("开始扫描...$success")
            }

            override fun onScanning(bleDevice: BleDevice?) {
                LogUtil.d("onScanning....$bleDevice")
                bleDevice?.apply {
                    if (null != name && name.contains(SRBleUtil.instance.trackDeviceBleStartName)) {
                        val subArray = getManufacturerInfo(scanRecord)
                        LogUtil.e("截取后的外显id广播=${HexUtil.formatHexString(subArray, true)}")
                        var typeName = ""
                        subArray?.let {
                            typeName = it.decodeToString()
                        }
                        DeviceBean().let {
                            it.type = getDeviceType(typeName)
                            it.deviceOutId =
                                name.substring(SRBleUtil.instance.trackDeviceBleStartName.length)
                                    .trim()
                            it.macId = mac
                            it.deviceName = name
                            mScanDeviceAdapter.getData().let { list ->
                                ViewUtil.instance.viewShow(mViewBinding.rvAddNewTracker3DeviceList)
                                list.add(it)
                                mScanDeviceAdapter.notifyItemRangeInserted(list.size - 1, 1)
                            }
                        }
                    } else if (null != name && name.contains("Pet_")) {
                        DeviceBean().let {
                            it.type = getDeviceType("typeName")
                            it.deviceOutId = scanRecord.sliceArray(45..45 + 6).decodeToString()
                            it.macId = mac
                            it.deviceName = name
                            mScanDeviceAdapter.getData().let { list ->
                                list.add(it)
                                mScanDeviceAdapter.notifyItemRangeInserted(list.size - 1, 1)
                            }
                        }
                    }
                }
            }

            override fun onScanFinished(scanResultList: MutableList<BleDevice>?) {
                LogUtil.e("automaticConnection--扫描完成...${scanResultList?.size}")
                scanFinished()
            }
        })
    }

    /**
     * 获取查找设备类型
     */
    private fun getManufacturerInfo(scanRecord: ByteArray): ByteArray? {
        var index = 0
        while (index < scanRecord.size) {
            val length = scanRecord[index].toInt() and 0xFF
            if (length == 0) break
            val typeIndex = index + 1
            val dataStart = index + 2
            val dataLength = length - 1
            val dataEndExclusive = dataStart + dataLength
            if (typeIndex >= scanRecord.size || dataEndExclusive > scanRecord.size) {
                return null
            }
            val type = scanRecord[typeIndex].toInt() and 0xFF
            if (type == 0xFF) {
                val data = scanRecord.copyOfRange(dataStart, dataEndExclusive)
                if (data.size < 2) return null
//                val companyId = (data[0].toInt() and 0xFF) or ((data[1].toInt() and 0xFF) shl 8)
                val payload = data.copyOfRange(2, data.size)
                return payload
            }
            index += (length + 1)
        }
        return null
    }

    /**
     * 获取设备类型
     */
    private fun getDeviceType(typeName: String): Int {
        return when (typeName) {
            "G40" -> ConstantInt.Type2
            else -> ConstantInt.Type1
        }
    }

    private fun scanFinished() {
        mAnimatorSet?.cancel()
        mViewBinding.ivAddNewTracker3RefreshBtn.isEnabled = true
        if (isFrontRunning && mScanDeviceAdapter.getData().size == 0) {
            ViewUtil.instance.showDialog(
                mContext,
                R.string.txt_no_search_device,
                object : BaseDialog.OnDialogOkListener {
                    override fun onOkClick(dialog: BaseDialog<*>) {
                        dialog.dismiss()
                        startScanBle()
                    }
                },
                okTextResId = R.string.txt_ok,
                cancelTextResId = R.string.txt_cancel,
                cancelListener = object : BaseDialog.OnDialogCancelListener {
                    override fun onCancelClick(dialog: BaseDialog<*>) {
                        dialog.dismiss()
                        finish()
                    }
                })
        }
    }


    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!!) {
                ivAddNewTracker3RefreshBtn -> {
                    disconnectBle()
                    startScanBle()
                }
            }
        }
    }
}