package com.zj365.dc.vm

import android.app.Activity
import android.content.Context
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.xty.base.vm.BaseVm
import com.xty.common.Const
import com.xty.common.MMkvHelper
import com.xty.common.util.CommonUtils
import com.xty.network.model.BannerBean
import com.xty.network.model.BindDeviceListBean
import com.xty.network.model.InviteCustodyBean
import com.xty.network.model.RespBody
import com.xty.network.model.SettingBean
import com.xty.network.model.UnReadMessageBean
import com.xty.network.model.Update
import com.xty.network.model.UserEquipmentInformationizationBean
import com.zj365.dc.BuildConfig
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.async
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.json.JSONObject

class MainVm : BaseVm() {

    val updateLive by lazy { MutableLiveData<RespBody<Update>>() }
    val readLive by lazy { MutableLiveData<RespBody<Any>>() }
    val getImUserSig by lazy { MutableLiveData<RespBody<String>>() }
    val countLive by lazy { MutableLiveData<RespBody<UnReadMessageBean>>() }
    val getUserEquipmentInformationization by lazy { MutableLiveData<RespBody<UserEquipmentInformationizationBean>>() }

    val saveSuccess by lazy { MutableLiveData<RespBody<Any>>() }
    val boundDevices  by lazy{MutableLiveData<RespBody<MutableList<BindDeviceListBean>>>()}

    val bannerLive by lazy { MutableLiveData<MutableMap<Int,MutableList<BannerBean>>>()  }

    val isDemonstrateData by  lazy {  MutableLiveData<RespBody<String>>() }

    val findInfoLiveData by lazy { MutableLiveData<RespBody<InviteCustodyBean>>() }

    val confirmInviteLiveData by lazy { MutableLiveData<RespBody<Any>>() }

    val settingLive by lazy { MutableLiveData<RespBody<SettingBean>>() }


    /**
     * 设备类型1，血压计，2，血糖仪.3体脂秤
     */
    fun getBindList(type:Int){
        startHttp {
            var json=JSONObject()
            json.put("deviceType",type)
            var response =apiInterface().getBindDevList(retrofits.getRequestBody(json.toString()))
            response.getCodeStatus(boundDevices,nowData)
        }
    }
    fun saveWeight(weight:Double,resistance:Double,sn:String){
        startHttp {
            val json = JSONObject()
            json.put("userId", CommonUtils.getMyUserId())
            json.put("weight", weight)
            json.put("resistance", resistance)
            json.put("sn", sn)
            var response = apiInterface().savePbfRecord(retrofits.getRequestBody(json.toString()))
            response.getCodeStatus(saveSuccess, nowData)
        }
    }
    fun getVersionNew() {
        startHttp {
            var response = apiInterface().getVersionNew(BuildConfig.VERSION_CODE)
            response.getCodeStatus(updateLive, nowData)
        }
    }

    fun readMsg(id: String) {
        startHttp {
            var json = JSONObject()
            json.put("notifyId", id)
            json.put("notifyStatus", 1)
            json.put("notifyHandStatus", 2)

            var respnse = apiInterface().readMsg(retrofits.getRequestBody(json.toString()))
            respnse.getCodeStatus(readLive, nowData)
        }


    }

    fun getImUserSig(identifier: String) {
        startHttp {
            val imUserSig = apiInterface().getImUserSig(identifier)
            imUserSig.body()?.getCodeStatus(getImUserSig, nowData, paramsData = identifier)
        }
    }

    //获取未读系统消息
    fun getNotReadCount() {
        startHttp(false) {
            var respnse = apiInterface().getNotReadCount()
            respnse.getCodeStatus(countLive, nowData)
        }
    }

    //请求用户设备信息
    fun getUserEquipmentInformationizationRequest(userId: String) {
        startHttp(false) {
            var json = JSONObject()
            json.put("id", userId)
            val response = apiInterface().getUserEquipmentInformationization(retrofits.getRequestBody(json.toString()))
            response.getCodeStatus(getUserEquipmentInformationization, nowData)
        }
    }

    fun getBanners(id: String?,location:Int){
        startHttp(false) {

            withContext(Dispatchers.IO){
                val userId = if (MMkvHelper.getLong(Const.USER_ID).toString() == "0") {
                    ""
                } else {
                    MMkvHelper.getLong(Const.USER_ID).toString()
                }
                var nowLine = async{apiInterface().getBanners(userId,location)}
                var showInfo = nowLine.await()
                // var value=apiInterface().getBanners(retrofits.getRequestBody(json.toString()))
                var dataMap = setMapValue(bannerLive.value,showInfo.data,location)
                if (dataMap != null){
                    bannerLive.postValue(dataMap)
                }
                // value.getCodeStatus(bannerLive,nowData)
            }

        }
    }

    fun  getIsDemonstate(){
        startHttp(false) {

            withContext(Dispatchers.IO){
                val userId = if (MMkvHelper.getLong(Const.USER_ID).toString() == "0") {
                    ""
                } else {
                    MMkvHelper.getLong(Const.USER_ID).toString()
                }
                var json = JSONObject()
                json.put("id", userId)
                val response = apiInterface().getIsDemonstrate(retrofits.getRequestBody(json.toString()))
                // value.getCodeStatus(bannerLive,nowData)
                response.getCodeStatus(isDemonstrateData,nowData)
            }

        }
    }

    fun searchInviteInfo(){
        startHttp(false) {
            var json = JSONObject()
            val response = apiInterface().findConfirmInfo(retrofits.getRequestBody(json.toString()))
            response.getCodeStatus(findInfoLiveData, nowData)
        }
    }

     fun confirmInvite(id:String, status:String){
         startHttp(false) {
             var json = JSONObject()
             json.put("id",id)
             json.put("status",status)
             val response = apiInterface().confirmInvited(retrofits.getRequestBody(json.toString()))
             response.getCodeStatus(confirmInviteLiveData,nowData)
         }

    }

    fun <T> setMapValue(map: MutableMap<Int, MutableList<T>>?, list: MutableList<T>?, type: Int): MutableMap<Int, MutableList<T>>? {
        if (list == null) {
            return null
        } else {  //当得到的值不是空的时候
            var mapNew = mutableMapOf<Int, MutableList<T>>()
            if (map == null) {
                mapNew[type] = list
                return mapNew
            } else {
                map[type] = list
                return map
            }
        }
    }

    /**
     * 个人设置接口
     */
    fun getMySetting() {
        startHttp {
            val body = apiInterface().getMySetting()
            body.getCodeStatus(settingLive, nowData)
        }
    }
}