package com.rdiot.yx485.ui.bind.model

import androidx.databinding.ObservableField
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.king.zxing.util.LogUtils
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch

/**
 * 绑定ViewModel
 * @author mR2hao
 * @date 2022/12/1
 */
class BindViewModel : ViewModel() {
    /** 房间名 */
    var roomName: ObservableField<String> = ObservableField("")

    /** 面板编号 */
    var panelNum: ObservableField<String> = ObservableField("") //807D3AE5E5D4

    /** Wifi名字 */
    var wifiSsid: ObservableField<String> = ObservableField("")

    /** Wifi密码 */
    var wifiPwd: ObservableField<String> = ObservableField("")

    /** 绑定分控标志 */
    var isBindSub: Boolean = false

    /** 定位名字（市） */
    var locationName: String? = null

    /** 设备类型id */
    var deviceTypeId: ObservableField<String> = ObservableField("")

    /** 设备类型code */
    var code: String = ""

    /** 配网倒计时 */
    var countDownTime: MutableLiveData<Int> = MutableLiveData(-1)
    private var countDownJob: Job? = null

    companion object {
        const val COUNT_TIME = 120
    }

    fun testMode() {
        LogUtils.w("当前使用testMode")
        LogUtils.e("当前使用testMode")
        LogUtils.w("当前使用testMode")
        LogUtils.e("当前使用testMode")
        LogUtils.w("当前使用testMode")
        LogUtils.e("当前使用testMode")
        roomName = ObservableField("1")
        panelNum = ObservableField("C8F09EE84FB0")
        wifiSsid = ObservableField("RD-100YUN-2.4G")
        wifiPwd = ObservableField("22230920yun")

    }

    fun startCountDown() {
        countDownJob?.cancel()
        countDownTime.value = COUNT_TIME
        countDownJob = viewModelScope.launch {
            while (isActive && countDownTime.value!! > 0) {
                if (countDownTime.value!! <= 0) {
                    countDownJob?.cancel()
                    countDownJob = null
                }
                delay(1000)
                countDownTime.value = countDownTime.value!! - 1
            }
        }
    }

    fun stopCountDown() {
        countDownJob?.cancel()
        countDownJob = null
    }
}