package com.xhly.manageapp.viewmodel

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import com.xhly.corelib.base.viewmodel.CommonBaseViewModel
import com.xhly.corelib.network.RetrofitService
import com.xhly.corelib.utils.LogShow
import com.xhly.corelib.utils.MD5Utils
import com.xhly.manageapp.bean.log.LogEventBean
import com.xhly.manageapp.bean.log.LogPushBean
import com.xhly.manageapp.bean.log.LogPushResultBean
import com.xhly.manageapp.bean.log.LogdOperateBean
import com.xhly.manageapp.bean.scheme.AutoAppBean
import com.xhly.manageapp.network.log.LogService
import com.xhly.manageapp.ui.login.netservice.LoginService
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow

open class BaseViewModel : CommonBaseViewModel() {
    protected val loginService: LoginService by lazy { RetrofitService.create<LoginService>() }
    private val logService: LogService = RetrofitService.create<LogService>()
    private val pwdResult = MutableLiveData<Boolean>()
    val pwdResultData: LiveData<Boolean> = pwdResult
    private val timeResult = MutableLiveData<Long>()
    val timeResultData: LiveData<Long> = timeResult
    private val controlResult = MutableLiveData<Boolean>()
    val controlResultData: LiveData<Boolean> = controlResult
    private val lockResult = MutableLiveData<Boolean>()
    val lockResultData: LiveData<Boolean> = lockResult
    private val resetResult = MutableLiveData<Boolean>()
    val resetlResultData: LiveData<Boolean> = resetResult

    /*    private val logResult=MutableLiveData<LogPushResultBean>()
        val logResultData:LiveData<LogPushResultBean> =logResult

    private val logEventResult = MutableLiveData<LogEventBean>()
    val logEventData: LiveData<LogEventBean> = logEventResult
        */
    private val logResult = MutableStateFlow<LogPushResultBean?>(null)
    val logResultData: Flow<LogPushResultBean?> = logResult.asStateFlow()

    private val logEventResult =MutableStateFlow<LogEventBean?>(null)
    val logEventData: Flow<LogEventBean?> = logEventResult.asStateFlow()


    private val autoAppResult = MutableStateFlow<AutoAppBean?>(null)
    val autoAppData: Flow<AutoAppBean?> = autoAppResult.asStateFlow()

    /**
     * 解除当前锁屏
     */
    fun postPwdDetail(code: String, sn: String) {
        launchUI {
            //先对比本地密码，一致则直接解锁，不然传给服务器
            if (code == MD5Utils.getDynamicPassword(sn)) {
                pwdResult.value = true
                postEditUnlock(sn)
            } else {
                val map = HashMap<String, Any>()
                map["password"] = code
                val result = loginService.postExitControl(map)
                pwdResult.value = result.code == 0
            }
        }
    }

    /**
     * 手动进入管理页面
     */
    fun postExitControl(code: String, sn: String) {
        launchUI {
            //先对比本地密码，一致则可以进入本地管理页面
            controlResult.value = code == MD5Utils.getDynamicPassword(sn)
            /*else{
                val map=HashMap<String,Any>()
                map["password"]=code
                val result= loginService.postExitControl(map)
                controlResult.value = result.code==0
            }*/
        }
    }

    /**
     * 发送事件日志
     */
    fun eventLog(operateBean: LogdOperateBean) {
        launchUI {
            val result = logService.postLogdoperateAdd(operateBean)
            if (result.code == 0) {
                val logEventBean = LogEventBean()
                logEventBean.enableFlag = true
                logEventBean.logEventType = operateBean.doEvent
                logEventResult.value = logEventBean
            }
        }
    }

    /**
     * 发送事件推送日志,再接口回调后再调用功能实现
     */
    fun postLogPushAdd(logPushBean: LogPushBean) {
        launchUI {
            val postLogPushAdd = logService.postLogPushAdd(logPushBean)
            if (postLogPushAdd.code == 0) {
                //为true则后续执行
                val logPushResultBean = LogPushResultBean()
                logPushResultBean.pushType = logPushBean.pushType
                logPushResultBean.enableFlag = true
                logResult.value = logPushResultBean
            }
        }
    }

    /**
     * 同步服务器的时间
     */
    fun postSyncTime() {
        launchUI {
            val startTime = System.currentTimeMillis()
            val postSyncTime = loginService.postSyncTime()
            if (postSyncTime.code == 0) {
                val endTime = System.currentTimeMillis()
                val obj = postSyncTime.obj
                timeResult.value = obj + (endTime - startTime) / 2
            } else {
                if (!postSyncTime.msg.isNullOrEmpty()) {
                    netMessage.value = postSyncTime.msg
                }
            }
        }
    }


    /**
     * 违规事件发送socket消息后，请求接口然后处理锁定
     * sn 设备号
     *  pushType  3锁定
     */
    fun postExitLocked(sn: String, pushType: Int = 3) {
        launchUI {
            val map = HashMap<String, Any>()
            map["sn"] = sn
            map["pushType"] = pushType
            val result = loginService.postExitLocked(map)
            if (result.code == 0) {
                lockResult.value = true
            } else {
                if (!result.msg.isNullOrEmpty()) {
                    netMessage.value = result.msg
                }
            }
        }
    }

    /**
     * 违规事件发送socket消息后，请求接口然后处理恢复出厂设置
     * sn 设备号
     * pushType  6恢复出厂设置
     */
    fun postExitReseted(sn: String, pushType: Int = 6) {
        launchUI {
            val map = HashMap<String, Any>()
            map["sn"] = sn
            map["pushType"] = pushType
            val result = loginService.postExitReseted(map)
            if (result.code == 0) {
                resetResult.value = true
            } else {
                if (!result.msg.isNullOrEmpty()) {
                    netMessage.value = result.msg
                }
            }
        }
    }

    /**
     * 设备--解除锁定(锁定后，本地输入密码校验通过后调用) 参数sn
     */
    fun postEditUnlock(sn: String) {
        launchUI {
            val map = HashMap<String, Any>()
            map["sn"] = sn
            var postExitLocked = loginService.postEditUnlock(map)
        }
    }

    /**
     * 开机设置-启动应用-平板用户（根据这个接口启动指定应用）
     */

    fun postAutoAppDetail(regionid: Long) {
        launchUI {
            try {
                val map = HashMap<String, Any>()
                map["regionid"] = regionid
                val result = loginService.postAutoAppDetail(map)
                if (result.code == 0) {
                    result.obj.netSucessFlag = true
                    autoAppResult.value = result.obj
                } else {
                    val autoAppBean = AutoAppBean()
                    autoAppBean.netSucessFlag = true
                    autoAppResult.value = AutoAppBean()
                }
            } catch (e: Exception) {
                autoAppResult.value = AutoAppBean()
                LogShow(e.toString())
            }
        }
    }
}