package com.xhly.manageapp.ui.main.viewmodel

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.asFlow
import com.xhly.corelib.Const
import com.xhly.corelib.eventbus.UIEvent
import com.xhly.corelib.network.RetrofitService
import com.xhly.manageapp.ManageApplication
import com.xhly.manageapp.bean.app.AppModel
import com.xhly.manageapp.bean.app.ListAppBean
import com.xhly.manageapp.bean.log.UpdateBean
import com.xhly.manageapp.bean.WallpaperBean
import com.xhly.manageapp.bean.app.AppInstallBean
import com.xhly.manageapp.bean.log.PadInfoBean
import com.xhly.manageapp.bean.log.PadLocationBean
import com.xhly.manageapp.bean.school.SchoolDeviceSetBean
import com.xhly.manageapp.bean.strategy.AppTimeManageBean
import com.xhly.manageapp.bean.strategy.StrategyBean
import com.xhly.manageapp.network.app.AppService
import com.xhly.manageapp.network.log.LogService
import com.xhly.manageapp.network.strategy.StrategyService
import com.xhly.manageapp.viewmodel.BaseViewModel
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow

class MainViewModel : BaseViewModel() {
    private val appService by lazy { RetrofitService.create<AppService>() }
    private val strategyService by lazy { RetrofitService.create<StrategyService>() }
    private var logService = RetrofitService.create<LogService>()

/*    private val listData = MutableLiveData<ArrayList<AppModel>>()
    val listAppData: LiveData<ArrayList<AppModel>> = listData
    private val forceData = MutableLiveData<ArrayList<AppModel>>()
    val forceListAppData: LiveData<ArrayList<AppModel>> = forceData
    private val strategy = MutableLiveData<StrategyBean>()
    val strategyData: LiveData<StrategyBean> = strategy
    private val appStrategy = MutableLiveData<ArrayList<AppTimeManageBean>>()
    val appStrategyData: LiveData<ArrayList<AppTimeManageBean>> = appStrategy
    private val padInfo = MutableLiveData<Boolean>()
    val padInfoData: LiveData<Boolean> = padInfo
    private val updateInfo = MutableLiveData<Boolean>()
    val updateInfoData: LiveData<Boolean> = updateInfo
    private val loginOut = MutableLiveData<Boolean>()
    val loginOutData: LiveData<Boolean> = loginOut
    private val schoolSet = MutableLiveData<SchoolDeviceSetBean>()
    val schoolSetData: LiveData<SchoolDeviceSetBean> = schoolSet

    private val netWhiteList = MutableLiveData<ArrayList<String>>()
    val netWhiteListData: LiveData<ArrayList<String>> = netWhiteList*/

    private val wallpaper = MutableLiveData<WallpaperBean>()
    val wallpaperData: LiveData<WallpaperBean> = wallpaper


    private val listData =MutableStateFlow<ArrayList<AppModel>?>(null)
    val listAppData: Flow<ArrayList<AppModel>?> = listData.asStateFlow()

    private val forceData =MutableStateFlow<ArrayList<AppModel>?>(null)
    val forceListAppData: Flow<ArrayList<AppModel>?> = forceData.asStateFlow()

    private val strategy = MutableStateFlow<StrategyBean?>(null)
    val strategyData: Flow<StrategyBean?> = strategy.asStateFlow()

    private val appStrategy = MutableStateFlow<ArrayList<AppTimeManageBean>?>(null)
    val appStrategyData: Flow<ArrayList<AppTimeManageBean>?> = appStrategy.asStateFlow()

    private val padInfo = MutableStateFlow<Boolean?>(null)
    val padInfoData: Flow<Boolean?> = padInfo.asStateFlow()

    private val updateInfo =MutableStateFlow<Boolean?>(null)
    val updateInfoData: Flow<Boolean?> = updateInfo.asStateFlow()

    private val loginOut =MutableStateFlow<Boolean?>(null)
    val loginOutData:  Flow<Boolean?> = loginOut.asStateFlow()

    private val schoolSet = MutableStateFlow<SchoolDeviceSetBean?>(null)
    val schoolSetData: Flow<SchoolDeviceSetBean?> = schoolSet.asStateFlow()


    private val netWhiteList = MutableStateFlow<ArrayList<String>?>(null)
    val netWhiteListData: Flow<ArrayList<String>?> = netWhiteList.asStateFlow()



    fun getAppList() {
        launchUI {
            val postListApp = appService.postListApp(ListAppBean())
            if (postListApp.code == 0) {
                if (postListApp.obj != null && postListApp.obj.isNotEmpty()) {
                    listData.value = postListApp.obj
                } else {
                    listData.value = arrayListOf()
                }
            } else {
                if (!postListApp.msg.isNullOrEmpty()) {
                    netMessage.value = postListApp.msg
                }
            }
            //获得必装应用
            val result = appService.postForceApp()
            if (result.code == 0 && result.obj != null && result.obj.isNotEmpty()) {
                forceData.value = result.obj
            }
        }
    }

    /*    fun getForceAppList(){
            launchUI {
                val result= appService.postForceApp()
                if (result.code==0&&result.obj!=null&&result.obj.isNotEmpty()){
                    forceData.value=result.obj
                }
            }
        }*/

    fun updateStrategy() {
        launchUI {
            val postDetailPad = strategyService.postDetailPad()
            if (postDetailPad.code == 0) {
                if (postDetailPad.obj != null) {
                    strategy.value = postDetailPad.obj
                }
            } else {
                if (!postDetailPad.msg.isNullOrEmpty()) {
                    netMessage.value = postDetailPad.msg
                }
            }
        }
    }


    /**
     * 获得app时间使用策略
     */
    fun uploadAppStrategy() {
        launchUI {
            val postAppListPad = strategyService.postAppListPad()
            if (postAppListPad.code == 0) {
                if (postAppListPad.obj != null && postAppListPad.obj.size > 0) {
                    appStrategy.value = postAppListPad.obj
                } else {
                    appStrategy.value = arrayListOf()
                }
            } else {
                if (!postAppListPad.msg.isNullOrEmpty()) {
                    netMessage.value = postAppListPad.msg
                }
            }
        }
    }

    fun updatePadInfo(padInfoBean: PadInfoBean) {
        launchUI {
            val anyResponseData = logService.postPadDetailAdd(padInfoBean)
            if (anyResponseData.code == 0) {
                padInfo.value = true
            }
        }
    }

    /**
     * 添加安装的app的更新日志，每次安装应用后扫描并上传所有app
     */
    fun updateAppInstallInfo(list:List<AppInstallBean>) {
        launchUI {
            val result = appService.postAppInstallAdd(list)
        }
    }


    /**
     * 每天请求一次app更新接口，这个接口是用于提交管控自身的版本信息统计
     */
    fun updateMcApp(updateBean: UpdateBean) {
        launchUI {
            val postClientAdd = appService.postClientAdd(updateBean)
            if (postClientAdd.code == 0) {
                updateInfo.value = true
            }
        }
    }

    fun loginOut(userid: String, loginpwd: String) {
        launchUI {
            val map = HashMap<String, Any>()
            map["userid"] = userid
            map["loginpwd"] = loginpwd
            ManageApplication.getDeviceInfo()?.let {sn->
                map["sn"]=sn
            }
            val postLoginOut = loginService.postLoginOut(map)
            if (postLoginOut.code == 0) {
                loginOut.value = true
            } else {
                if (postLoginOut.msg != null) {
                    netMessage.value = postLoginOut.msg
                }
            }
        }
    }

    /**
     * 获得设备设置管理
     */
    fun postDevicesetDetail(schoolid: Long) {
        launchUI {
            val postListApp = appService.postListApp(ListAppBean())
            if (postListApp.code == 0) {
                if (postListApp.obj != null && postListApp.obj.isNotEmpty()) {
                    listData.value = postListApp.obj
                } else {
                    listData.value = arrayListOf()
                }
            } else {
                if (!postListApp.msg.isNullOrEmpty()) {
                    netMessage.value = postListApp.msg
                }
            }
            //获得必装应用
            val result1 = appService.postForceApp()
            if (result1.code == 0 && result1.obj != null && result1.obj.isNotEmpty()) {
                forceData.value = result1.obj
            }

            val map = HashMap<String, Any>()
            map["schoolid"] = schoolid
            val result = strategyService.postDevicesetDetail(map)
            if (result.code == 0) {
                schoolSet.value = result.obj
            } else {
                netMessage.value = result.msg
            }
        }
    }

    /**
     * 获得壁纸
     */
    fun postWallpaperPad() {
        launchUI {
            val postWallpaperPad = appService.postWallpaperPad()
            if (postWallpaperPad.code == 0) {
                wallpaper.value = postWallpaperPad.obj
            }
        }
    }

    /**
     * 获得网址白名单
     */
    fun postAppNetWhiteList() {
        launchUI {
            val postAppNetWhiteList = strategyService.postAppNetWhiteList()
            if (postAppNetWhiteList.code == 0) {
                val urlList = arrayListOf<String>()
                postAppNetWhiteList.obj.forEach {
                    if (it.contains(";")) {
                        it.split(";").forEach { str ->
                            urlList.add(str)
                        }
                    } else {
                        urlList.add(it)
                    }
                }
                netWhiteList.value = urlList
            }
        }
    }

    /**
     * 修改密码
     */
    fun postEditPwd(userid:Long, loginpwd:String, oldpwd:String){
        launchUI {
            val map=HashMap<String,Any>()
            map["userid"] = userid
            map["loginpwd"] =loginpwd
            map["oldpwd"] = oldpwd
            val postEditPwd = loginService.postEditPwd(map)
            if (postEditPwd.code==0){
                netMessage.value ="修改成功"
            //修改完密码不退出登录
            //UIEvent(Const.ACCOUNTLOGINOUT).post()
            }else{
                netMessage.value ="修改失败"
            }
        }
    }

    /**
     * 发送定位
     */

    fun  postPadLocation(location:PadLocationBean){
        launchUI {
            logService.postPadLocation(location)
        }
    }
}