package com.abbidot.tracker.vm

import android.content.Context
import android.os.CountDownTimer
import android.text.TextUtils
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.abbidot.baselibrary.constant.ConState
import com.abbidot.baselibrary.constant.EventName
import com.abbidot.baselibrary.eventbus.XEventBus
import com.abbidot.baselibrary.util.LogUtil
import com.abbidot.tracker.R
import com.abbidot.tracker.base.BaseActivity
import com.abbidot.tracker.bean.DeviceBean
import com.abbidot.tracker.database.MyDatabase
import com.abbidot.tracker.util.Util
import com.abbidot.tracker.util.bluetooth.SRBleUtil
import com.clj.fastble.BleManager
import com.clj.fastble.callback.BleScanCallback
import com.clj.fastble.data.BleDevice
import com.clj.fastble.data.BleScanState
import com.clj.fastble.scan.BleScanRuleConfig
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

/**
 *Created  by  on 2022/5/26/026.
 * @link
 * @description:自动连接设备
 */
class ConnectionDeviceViewModel : ViewModel() {

    private var mCountDownTimer: CountDownTimer? = null

    fun autoConnectBleDevice(context: Context) {
        //判断蓝牙是否打开
        if (!SRBleUtil.instance.isBleEnable(context)) {
            LogUtil.e("automaticConnection,蓝牙没打开")
            return
        }
        if (BleManager.getInstance().scanSate == BleScanState.STATE_SCANNING) {
            LogUtil.e("automaticConnection,已经在扫描蓝牙,开始扫描失败")
            return
        }
        viewModelScope.launch(Dispatchers.IO) {
            val localDevices = MyDatabase.deviceDao()
                .findAll(MyDatabase.DEVICE_TABLE) as MutableList<DeviceBean>
            LogUtil.e("查找本地ble设备有${localDevices.size}个")
            if (localDevices.size == 0) {
                return@launch
            }
            val scanTrackBle = mutableListOf<BleDevice>()
            val scanRuleConfig = BleScanRuleConfig.Builder().build()
            BleManager.getInstance().initScanRule(scanRuleConfig)
            BleManager.getInstance().scan(object : BleScanCallback() {
                override fun onScanStarted(success: Boolean) {
                    SRBleUtil.instance.isScanInterrupt = false
                    LogUtil.e("开始扫描...$success")
                }

                override fun onScanning(bleDevice: BleDevice?) {
                    LogUtil.d("onScanning....$bleDevice")
                    bleDevice?.apply {
                        if (null != name && name.contains(SRBleUtil.instance.trackDeviceBleStartName)) {
                            scanTrackBle.add(this)
                        }
                    }
                }

                override fun onScanFinished(scanResultList: MutableList<BleDevice>?) {
                    val interrupt = SRBleUtil.instance.isScanInterrupt
                    LogUtil.e("automaticConnection--扫描完成..中断扫描$interrupt，${scanResultList?.size}")
                    if (!interrupt) {
                        compareDevice(scanTrackBle, localDevices)
                    }
                }
            })
        }
    }

    /**
     * 从扫描到的设备中查找已添加的设备，并连接设备
     */
    private fun compareDevice(
        scanResultList: MutableList<BleDevice>, localDevices: MutableList<DeviceBean>
    ) {
        if (scanResultList.size > 0) {
            var connected = false
            viewModelScope.launch(Dispatchers.IO) {
                //创建新的变量，防止别的蓝牙扫描(蓝牙找设备功能)改变scanResultList变量，导致异常
                val scanBleList = mutableListOf<BleDevice>()
                scanBleList.addAll(scanResultList)
                for (device in localDevices) {
                    for (bleDevice in scanBleList) {
                        if (!TextUtils.isEmpty(bleDevice.name)) {
                            if (device.macId == bleDevice.mac) {
                                SRBleUtil.instance.connect(bleDevice)
                                connected = true
                                break
                            }
                        }
                    }
                }
                if (!connected) {
                    LogUtil.e("没有蓝牙设备可连")
                    SRBleUtil.instance.isBleConnecting = false
//                    XEventBus.post(EventName.ActionConDeviceState, ConState.DEVICE_NOT_FOUND)
                }
            }
        } else {
            LogUtil.e("蓝牙设备为0")
            SRBleUtil.instance.isBleConnecting = false
//            XEventBus.post(EventName.ActionConDeviceState, ConState.DEVICE_NOT_FOUND)
        }
    }

    /**
     * 连接中倒计时20s变为未连接状态
     */
//    fun connectingFailCountDown() {
//        mCountDownTimer = object : CountDownTimer(20 * 1000, 1000) {
//            override fun onTick(time: Long) {
//            }
//
//            override fun onFinish() {
//                LogUtil.e("连接中倒计时20s变为未连接状态")
//                XEventBus.post(EventName.ActionConDeviceState, ConState.CONNECTION_FAIL)
//            }
//        }.start()
//    }

    /**
     * 连接成功后取消倒计时
     */
    private fun cancelFailCountDown() {
        mCountDownTimer?.cancel()
    }

    /**
     * 根据mac连接设备
     */
    fun connectDeviceToMac(activity: BaseActivity<*>, mac: String, showLoading: Boolean = true) {
        if (TextUtils.isEmpty(mac)) {
            return
        }
        if (BleManager.getInstance().isConnected(mac)) {
            LogUtil.e("设备已经连接")
            return
        }
        if (SRBleUtil.instance.isBleConnecting) {
            LogUtil.e("已经有设备在连接中...")
            XEventBus.post(EventName.ActionConDeviceState, ConState.CONNECTING_MAC)
            return
        }
        Util.checkBluetoothPermissionsEnabled(activity, {
            SRBleUtil.instance.cancelBleScan("connectDeviceToMac,已经在扫描蓝牙，取消上次扫描")
            if (showLoading) activity.showLoading(showLoading, R.string.txt_connecting, false)
            viewModelScope.launch(Dispatchers.IO) {
                //防止和自动连接设备，扫描完成后回调冲突
                if (SRBleUtil.instance.isScanInterrupt) {
                    delay(1000)
                }
                //只扫描指定的mac设备
                val scanRuleConfig = BleScanRuleConfig.Builder().setDeviceMac(mac).build()
                BleManager.getInstance().initScanRule(scanRuleConfig)
                BleManager.getInstance().scan(object : BleScanCallback() {
                    override fun onScanStarted(success: Boolean) {
                        LogUtil.e("开始扫描${mac}设备...")
                        SRBleUtil.instance.isScanInterrupt = false
                        XEventBus.post(EventName.ActionConDeviceState, ConState.CONNECTING_MAC)
                    }

                    override fun onScanning(bleDevice: BleDevice?) {
                        LogUtil.d("onScanning....$bleDevice")
                        bleDevice?.apply {
                            if (bleDevice.mac == mac) BleManager.getInstance().cancelScan()
                        }
                    }

                    override fun onScanFinished(scanResultList: MutableList<BleDevice>?) {
                        val interrupt = SRBleUtil.instance.isScanInterrupt
                        if (interrupt) {
                            LogUtil.e("connectDeviceToMac--扫描完成..中断扫描")
                        } else {
                            activity.showLoading(false)
                            scanResultList?.let {
                                val size = scanResultList.size
                                LogUtil.e("扫描${mac}设备完成...$size")
                                if (size > 0) {
                                    SRBleUtil.instance.connect(scanResultList[0])
                                } else {
                                    XEventBus.post(
                                        EventName.ActionConDeviceState, ConState.DEVICE_NOT_FOUND
                                    )
                                }
                            }
                        }
                    }
                })
            }
        })
    }

    /**
     * 根据外显id连接设备
     */
    fun connectDeviceToDeviceOutId(
        activity: BaseActivity<*>, deviceOutId: String, showLoading: Boolean = true
    ) {
        if (TextUtils.isEmpty(deviceOutId)) {
            return
        }
        var isHaveScan = false
        Util.checkBluetoothPermissionsEnabled(activity, {
            SRBleUtil.instance.cancelBleScan("connectDeviceToDeviceOutId,已经在扫描蓝牙，取消上次扫描")
            activity.showLoading(showLoading, R.string.txt_search_device, false)
            viewModelScope.launch(Dispatchers.IO) {
                //防止和自动连接设备，扫描完成后回调冲突
                if (SRBleUtil.instance.isScanInterrupt) {
                    delay(1000)
                }
                val scanRuleConfig = BleScanRuleConfig.Builder().setScanTimeOut(10 * 1000).build()
                BleManager.getInstance().initScanRule(scanRuleConfig)
                BleManager.getInstance().scan(object : BleScanCallback() {
                    override fun onScanStarted(success: Boolean) {
                        LogUtil.e("开始扫描${deviceOutId}外显id设备...")
                        SRBleUtil.instance.isScanInterrupt = false
                        XEventBus.post(EventName.ActionConDeviceState, ConState.CONNECTING)
                    }

                    override fun onScanning(bleDevice: BleDevice?) {
                        LogUtil.d("onScanning....$bleDevice")
                        bleDevice?.apply {
                            if (null != name && name.contains(SRBleUtil.instance.trackDeviceBleStartName)) {
                                val start = 45
                                val end = start + 6
                                val subArray = scanRecord.sliceArray(start until end)
                                val scanDeviceOutId = subArray.decodeToString()
                                if (scanDeviceOutId == deviceOutId) {
                                    isHaveScan = true
                                    BleManager.getInstance().cancelScan()
                                    SRBleUtil.instance.connect(this)
                                }
                            }
                        }
                    }

                    override fun onScanFinished(scanResultList: MutableList<BleDevice>?) {
                        val interrupt = SRBleUtil.instance.isScanInterrupt
                        if (interrupt) {
                            LogUtil.e("connectDeviceToDeviceOutId--扫描完成..中断扫描")
                        } else {
                            LogUtil.e("扫描${deviceOutId}外显id设备 结束")
                            if (isHaveScan) {
                                activity.showLoading(showLoading, R.string.txt_connecting, false)
                            } else {
                                activity.showLoading(false)
                                XEventBus.post(
                                    EventName.ActionConDeviceState, ConState.DEVICE_NOT_FOUND
                                )
                            }
                        }
                    }
                })
            }
        })
    }

    /**
     * 断开连接
     */
    fun disconnect(bleDevice: BleDevice?) {
        bleDevice?.let {
            BleManager.getInstance().disconnect(it)
        }
    }

    override fun onCleared() {
        super.onCleared()
        LogUtil.e("ConnectionDeviceViewModel,onCleared")
        SRBleUtil.instance.isBleConnecting = false
        SRBleUtil.instance.cancelBleScan("onCleared,退出当前页面，取消扫描蓝牙")
        cancelFailCountDown()
    }
}