package com.rdiot.yx485.device.model

import android.text.TextUtils
import androidx.databinding.ObservableField
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.king.zxing.util.LogUtils
import com.rdiot.yx485.base.BaseViewModel
import com.rdiot.yx485.bean.DeviceOnlineState
import com.rdiot.yx485.bean.DeviceRoomListBean
import com.rdiot.yx485.bean.DeviceTreeBean
import com.rdiot.yx485.bean.DeviceTreeBean.DataBean
import com.rdiot.yx485.bean.EditDeviceReplyBean
import com.rdiot.yx485.bean.EditDeviceReplyBean.DataBean.DeviceBean
import com.rdiot.yx485.http.Url
import com.rdiot.yx485.http.Url.DEVICES
import com.rdiot.yx485.http.Url.ONLINE
import com.rdiot.yx485.http.Url.ROOMS
import com.rdiot.yx485.http.entity.BaseReplyBean
import com.rdiot.yx485.util.LocalCache
import com.zcolin.frame.http.ZHttp
import com.zcolin.frame.http.response.ZResponse
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
import okhttp3.Response

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

    var deviceName: ObservableField<String> = ObservableField("")

    var homeId: ObservableField<String> = ObservableField("")

    var roomId: ObservableField<String> = ObservableField("")

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

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

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

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

    var deviceCode: ObservableField<String> = ObservableField("")
    var subDeviceCode: ObservableField<String> = ObservableField("")

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

    /** 配网倒计时 */
    var countDownTime: MutableLiveData<Int> = MutableLiveData(-1)

    var addState: MutableLiveData<Boolean> = MutableLiveData(false)

    private var countDownJob: Job? = null

    companion object {
        var COUNT_TIME = 20
    }

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

    fun addDeviceToRoom() {
        val params = LinkedHashMap<String?, String?>()
        params.put("name", deviceName.get())
        params.put("device_code", deviceCode.get())
        params.put("type_id", deviceTypeId.get())
        params.put("is_master", isMaster.toString())
        if (!isMaster) {
            params.put("sub_code", subDeviceCode.get())
        }
        params.put("home_id", homeId.get())
        params.put("room_id", roomId.get())
        LogUtils.d(params.toString())
        ZHttp.postWithHeader(DEVICES, getHeaders(), params, object : ZResponse<BaseReplyBean?>() {
            override fun onSuccess(
                response: Response?,
                resObj: BaseReplyBean?
            ) {
                resObj?.let {
                    addState.value = it.isSuccess
                    if (it.isSuccess) {
                        stopCountDown()
                        return
                    }

                    mErrorMessage.value = it.message
                }
            }

            override fun onError(code: Int, error: String?) {
                super.onError(code, error)
                mErrorMessage.value = error
            }
        })
    }

    private var mDeviceList = MutableLiveData<List<DeviceBean>?>()
    val deviceList: LiveData<List<DeviceBean>?>
        get() = mDeviceList

    fun loadDeviceList(isMaster: Boolean? = null) {
        val params = LinkedHashMap<String?, String?>()
        isMaster?.let {
            params.put("is_master", it.toString())
        }
        params.put("home_id", LocalCache.getDefaultHomeId())
        params.put("q", "page")
        LogUtils.d(params.toString())
        ZHttp.getWithHeader<EditDeviceReplyBean?>(
            DEVICES, getHeaders(), params,
            object : ZResponse<EditDeviceReplyBean?>() {
                override fun onSuccess(response: Response?, resObj: EditDeviceReplyBean?) {
                    resObj?.data?.list?.let {
                        mDeviceList.value = it
                    }
                }

                override fun onError(code: Int, error: String?) {
                    super.onError(code, error)
                    mErrorMessage.value = error
                }
            })
    }

    /**
     * 删除
     */
    fun deleteDevice(id: String) {
        val url = Url.DEVICEDELETES + id
        ZHttp.deteleWithHeader<BaseReplyBean?>(
            url,
            getHeaders(),
            object : ZResponse<BaseReplyBean?>() {
                override fun onSuccess(response: Response?, resObj: BaseReplyBean?) {
                    resObj?.let {
                        if (it.isSuccess) {
                            loadDeviceList()
                            return
                        }

                        mErrorMessage.value = it.message
                    }
                }

                override fun onError(code: Int, error: String?) {
                    super.onError(code, error)
                    mErrorMessage.value = error
                }
            })
    }

    private var mRoomList = MutableLiveData<List<DeviceRoomListBean.RoomBean>?>()
    val roomList: LiveData<List<DeviceRoomListBean.RoomBean>?>
        get() = mRoomList

    fun loadRoomList() {
        val params = LinkedHashMap<String?, String?>()
        params.put("home_id", LocalCache.getDefaultHomeId())
        params.put("q", "list")
        LogUtils.d(params.toString())
        ZHttp.getWithHeader<DeviceRoomListBean?>(
            ROOMS, getHeaders(), params,
            object : ZResponse<DeviceRoomListBean?>() {
                override fun onSuccess(response: Response?, resObj: DeviceRoomListBean?) {
                    resObj?.data?.let {
                        mRoomList.value = it
                    }
                }

                override fun onError(code: Int, error: String?) {
                    super.onError(code, error)
                    mErrorMessage.value = error
                }
            })
    }

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

    private var mDeviceTypeList = MutableLiveData<List<DataBean>?>()
    val deviceTypeList: LiveData<List<DataBean>?>
        get() = mDeviceTypeList

    fun loadDeviceTypeList() {
        ZHttp.getWithHeader<DeviceTreeBean?>(
            Url.DEVICETYPELIST,
            getHeaders(),
            object : ZResponse<DeviceTreeBean?>() {
                override fun onSuccess(response: Response?, resObj: DeviceTreeBean?) {
                    resObj?.let {
                        mDeviceTypeList.value = it.data
                    }
                }

                override fun onError(code: Int, error: String?) {
                    super.onError(code, error)
                    mErrorMessage.value = error
                }
            })
    }

    private val _onlineState = MutableLiveData<Boolean>()
    val onlineState: LiveData<Boolean> = _onlineState

    fun checkOnlineState() {
        val id = deviceCode.get()
        LogUtils.d("checkOnlineState:" + id)
        id ?: return
        if (TextUtils.isEmpty(id)) {
            return
        }

        val url = ONLINE.replace("{id}", id)
        ZHttp.getWithHeader<DeviceOnlineState?>(
            url,
            getHeaders(),
            object : ZResponse<DeviceOnlineState?>() {
                override fun onSuccess(response: Response?, resObj: DeviceOnlineState?) {
                    LogUtils.d(resObj.toString())
                    resObj?.let {
                        _onlineState.value = it.data.status == 1
                    }
                }

                override fun onError(code: Int, error: String?) {
                    super.onError(code, error)
                    mErrorMessage.value = error
                }
            })
    }
}