package com.abbidot.tracker.vm

import android.app.Service
import android.media.AudioAttributes
import android.media.AudioManager
import android.media.SoundPool
import android.os.CountDownTimer
import android.text.TextUtils
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.abbidot.baselibrary.util.LogUtil
import com.abbidot.tracker.R
import com.abbidot.tracker.base.BaseActivity
import com.abbidot.tracker.util.bluetooth.SRBleUtil
import com.abbidot.tracker.widget.MyBluetoothAnimView
import com.abbidot.tracker.widget.MySignalView
import com.abbidot.tracker.widget.SignalRadarView
import com.clj.fastble.BleManager
import com.clj.fastble.callback.BleRssiCallback
import com.clj.fastble.callback.BleScanCallback
import com.clj.fastble.data.BleDevice
import com.clj.fastble.exception.BleException
import com.clj.fastble.scan.BleScanRuleConfig
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch


/**
 *Created  by .yzq on 2023/9/20/020.
 * @link
 * @description:
 */
class FindBleDeviceViewModel : ViewModel() {

    //音量管理器
    private lateinit var mAudioManager: AudioManager

    //记录手机原来的音量，便于还原
    private var mPhoneOriginalVolume = 0
    var mMaxVolume = 0

    //设置播放的当前时间
    private var mSetPlayTimeMillis = 0L

    private var mSoundPool: SoundPool? = null
    private var mSoundID = 0
    private var mStreamID = 0

    //播放的速度
    private var mSetPlaySpeed = 0.5f

    private var isStopReadRssi = false

    private var mCountDownTimer: CountDownTimer? = null

    fun startScanFind(
        activity: BaseActivity<*>,
        mac: String,
        signalView: MySignalView,
        radoView: SignalRadarView,
        bluetoothView: MyBluetoothAnimView,
        showLoading: Boolean = false
    ) {
        if (TextUtils.isEmpty(mac)) {
            return
        }
        if (!SRBleUtil.instance.isBleEnable(activity)) {
            activity.showToast(R.string.txt_ble_enable)
            return
        }
        SRBleUtil.instance.cancelBleScan("FindBleDeviceViewModel--->已经在扫描蓝牙，取消上次扫描")
        if (showLoading) activity.showLoading(true)

        //扫描超时时间，可选，默认10秒，若小于0，则时间无限，一直扫猫，但可以用BLeManger.getInstance().cancelScan()来中止扫描
        val scanTimeOut = 0L
        //扫描到设备的时间，多久没扫描到设备
        var currentScanTimeMillis = 0L
        var speed = 0.5f

        viewModelScope.launch(Dispatchers.IO) {

            mAudioManager = activity.getSystemService(Service.AUDIO_SERVICE) as AudioManager
            mPhoneOriginalVolume = getVolume()
            mMaxVolume = mAudioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC)
            setVolume(0)

            createSoundPoolIfNeeded(activity)

            if (BleManager.getInstance().isConnected(mac)) {
                LogUtil.e("是已连接的设备，直接获取信号")
                mCountDownTimer?.cancel()
                activity.runOnUiThread {
                    countDownReadConnectRssi {
                        SRBleUtil.instance.readConnectRssi(mac, object : BleRssiCallback() {
                            override fun onRssiFailure(exception: BleException?) {
                                LogUtil.e("FindBleDeviceViewModel--->获取连接设备信号失败...")
                            }

                            override fun onRssiSuccess(rssi: Int) {
                                LogUtil.e("FindBleDeviceViewModel--->获取连接设备信号onRssiSuccess$rssi...$isStopReadRssi")
                                if (isStopReadRssi) {
                                    mCountDownTimer?.cancel()
                                    return
                                }
                                speed = getPlaySpeed(rssi)
                                val value = getSignalValue(rssi)
                                signalView.setValue(value)
                                bluetoothView.setValue(value)
                                radoView.setValue(value)
                                playAudio(speed)
                            }

                        })
                    }
                }
                return@launch
            }
            //只扫描指定的mac设备
            val scanRuleConfig =
                BleScanRuleConfig.Builder().setDeviceMac(mac).setScanTimeOut(scanTimeOut).build()
            BleManager.getInstance().initScanRule(scanRuleConfig)
            BleManager.getInstance().scan(object : BleScanCallback() {
                override fun onScanStarted(success: Boolean) {
                    LogUtil.e("FindBleDeviceViewModel--->开始扫描${mac}设备...")
                }

                override fun onScanning(bleDevice: BleDevice?) {
                    bleDevice?.let {
                        LogUtil.e("FindBleDeviceViewModel--->onScanning...${it.mac},${it.rssi}")
                    }
                }

                override fun onLeScan(bleDevice: BleDevice?) {
                    bleDevice?.let {
                        if (it.mac == mac) {
                            currentScanTimeMillis = System.currentTimeMillis()
                            LogUtil.e("FindBleDeviceViewModel--->onLeScan...${it.mac},${it.rssi}")
                            speed = getPlaySpeed(it.rssi)
                            val value = getSignalValue(it.rssi)
                            signalView.setValue(value)
                            bluetoothView.setValue(value)
                            radoView.setValue(value)
                        }
                        //10s没扫描到设备
                        if (System.currentTimeMillis() - currentScanTimeMillis > 10 * 1000) {
                            LogUtil.e("FindBleDeviceViewModel--->10s没扫描到设备")
                            speed = getPlaySpeed(-200)
                            val value = getSignalValue(-200)
                            signalView.setValue(value)
                            bluetoothView.setValue(value)
                            radoView.setValue(value)
                            currentScanTimeMillis = System.currentTimeMillis()
                        }
                        playAudio(speed)
                    }
                }

                override fun onScanFinished(scanResultList: MutableList<BleDevice>?) {
                }
            })
        }
    }

    /**
     * 每隔2s执行一次请求
     */
    private fun countDownReadConnectRssi(readConnectRssi: () -> Unit) {
        mCountDownTimer = object : CountDownTimer(2 * 1000, 1000) {
            override fun onTick(time: Long) {
            }

            override fun onFinish() {
                readConnectRssi()
                countDownReadConnectRssi(readConnectRssi)
            }
        }.start()
    }

    fun setVolume(volume: Int) {
        //显示设置音量大小的操作条 flag=AudioManager.FLAG_SHOW_UI显示设置音量的ui
        mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, volume, 0)
    }

    /**
     * 获取系统当前的音量
     */
    fun getVolume(): Int {
        return mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC)
    }

    /**
     * 创建SoundPool ，注意 api 等级
     */
    private fun createSoundPoolIfNeeded(activity: BaseActivity<*>) {
        if (mSoundPool == null) {
            val audioAttributes = AudioAttributes.Builder().setUsage(AudioAttributes.USAGE_MEDIA)
                .setContentType(AudioAttributes.CONTENT_TYPE_MUSIC).build();

            mSoundPool =
                SoundPool.Builder().setMaxStreams(5).setAudioAttributes(audioAttributes).build()

            // 设置加载完成监听
            mSoundPool?.setOnLoadCompleteListener { _, _, status ->
                LogUtil.e("音频文件加载完成,status=$status")
            }
            val fd = activity.assets.openFd("find_device.mp3")
            mSoundID = mSoundPool?.load(fd, 1)!!
        } else {
            if (mStreamID != 0) mSoundPool?.resume(mStreamID)
        }
    }

    /**
     * 播放声音
     */
    private fun playAudio(speed: Float) {
        val currentTimeMillis = System.currentTimeMillis()
        //1秒更新下播放速度
        if (currentTimeMillis - mSetPlayTimeMillis > 1000) {
            mSoundPool?.apply {
                if (mStreamID == 0) {
                    mSetPlaySpeed = speed
                    mStreamID = play(
                        mSoundID, mMaxVolume.toFloat(), mMaxVolume.toFloat(), 1, -1, speed
                    )
                } else {
                    if (mSetPlaySpeed != speed) {
                        setRate(mStreamID, speed)
                        mSetPlaySpeed = speed
                    }
                }
            }
            mSetPlayTimeMillis = currentTimeMillis
        }
    }

    /**
     * 获取要设置播放速度大小
     * 信号强 0dBm~-50dBm  信号中 -50dBm~-70dBm 信号弱 -70dBm~dBm
     *低功耗蓝牙分四级
     * 4:  0~-60
     * 3: -60~-70
     * 2: -70~-80
     * 1:  -80~
     */
    private fun getPlaySpeed(rssi: Int): Float {
        return when (getSignalValue(rssi)) {
            4 -> {
                2.0f
            }

            3 -> {
                1.5f
            }

            2 -> {
                1.0f
            }

            1 -> {
                0.75f
            }

            else -> {
                0.5f
            }
        }
    }

    private fun getSignalValue(rssi: Int): Int {
        return if (rssi >= -50) {
            4
        } else if (rssi >= -70) {
            3
        } else if (rssi >= -90) {
            2
        } else if (rssi >= -100) {
            1
        } else {
            0
        }
    }

    /**
     * 停止查找设备
     */
    fun stopFindDevice() {
        SRBleUtil.instance.cancelBleScan("停止查找设备取消扫描蓝牙")
        isStopReadRssi = true
        mCountDownTimer?.cancel()
        //还原手机原来的音量
        setVolume(mPhoneOriginalVolume)
    }

    fun stopPlay() {
        mSoundPool?.pause(mStreamID)
    }

    override fun onCleared() {
        super.onCleared()
        LogUtil.e("FindBleDeviceViewModel onCleared")
        stopFindDevice()
        mSoundPool?.apply {
            if (mStreamID > 0) stop(mStreamID)
            release()
        }
    }
}