package com.zj365.dc.vm

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.tamsiree.rxkit.RxTimeTool
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.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.async
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.json.JSONArray
import org.json.JSONObject
import java.lang.StringBuilder
import java.text.SimpleDateFormat

class HealthVm : BaseVm() {

    val infoLive by lazy { MutableLiveData<RespBody<ReportBean>>() }
    val allDataInfo by lazy { MutableLiveData<MutableMap<String, Any>>() }
    val settingLive by lazy{MutableLiveData<RespBody<SettingBean>>()}
    val mqtt by lazy{MutableLiveData<RespBody<MqTTBean>>()}

    val uploadInfo by lazy { MutableLiveData<String>() }
    val uploadSleep by lazy { MutableLiveData<RespBody<String>>() }
    val uploadStep by lazy { MutableLiveData<RespBody<String>>() }
    val uploadMultiple by lazy { MutableLiveData<RespBody<NotAccepted>>() }

    val allData by lazy { MutableLiveData<RespBody<MainBean>>() }

    val familyLive by lazy { MutableLiveData<RespBody<MutableList<FamilyBean>>>() }

    val xtInfo by lazy { MutableLiveData<RespBody<XTangInfoBean>>()  }

    val tipsLive by lazy { MutableLiveData<RespBody<MutableList<TipsBean>>>()  }

    val dkInfo by lazy{ MutableLiveData<RespBody<DkBean>>() }

    val rankLive by lazy{MutableLiveData<RespBody<RankBean>>()}

    val bannerLive by lazy { MutableLiveData<RespBody<List<BannerBean>>>()  }

    val warningMsgLive by lazy { MutableLiveData<RespBody<MessageBean>>() }

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

    val scinceLive by lazy{MutableLiveData<RespBody<MutableList<ScienceBean>>>()}


    /**
     * 设备类型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 uploadAllInfo(
        arrayXl: JSONArray,
        arrayXya: JSONArray,
        arrayXy: JSONArray,
        arrayTemp: JSONArray,
        arrayBreath: JSONArray
    ) {
        viewModelScope.launch {
            withContext(Dispatchers.IO) {
                var sb = StringBuilder()
                var rate = async { uploadRate(arrayXl) }  //心率
                var dbp = async { uploadDbp(arrayXya) } //血压
                var so = async { uploadSo(arrayXy) } //血氧
                var temp = async { uploadTemp(arrayTemp) } //体温
                var resp = async { uploadResp(arrayBreath) } // 呼吸率
                if (rate.await() == 1) {
                    sb.append("心率上传错误")
                }
                if (dbp.await() == 1) {
                    sb.append("血压上传错误")
                }
                if (so.await() == 1) {
                    sb.append("血氧上传错误")
                }
                if (temp.await() == 1) {
                    sb.append("体温上传错误")
                }
                if (resp.await() == 1) {
                    sb.append("呼吸率上传错误")
                }
                uploadInfo.postValue(sb.toString())
            }
        }
    }

    /**
     * 获取所有信息
     */
    fun getAllInfo(id:String,isSHowDialog:Boolean) {
        startHttp(isSHowDialog) {
            var json=JSONObject()
            json.put("id",id)
            var body = apiInterface().getMainInfo(retrofits.getRequestBody(json.toString()))
            body.getCodeStatus(allData,nowData)
        }
    }

/*    *//**
     * 首页轮播图
     *
     * @param id 机构ID
     *//*
    fun getBanners(id: String?){
        startHttp(false) {
            var value=apiInterface().getBanners(id)
            value.getCodeStatus(bannerLive,nowData)
        }
    }*/

    /**
     * 首页小贴士
     */
    fun getTips(){
        startHttp(false) {
            var body = apiInterface().getTips()
            body.getCodeStatus(tipsLive,nowData)
        }
    }

    /**
     * 获取步数数据
     */
    fun getDkInfo(isShowLoading: Boolean = true, userId: String) {
        startHttp(isShowLoading) {
            var body=  apiInterface().getDkInfo(userId)
            body.getCodeStatus(dkInfo,nowData)
        }
    }

    /**
     * 获取排名信息
     */
    fun getRank(type:Int, isShowLoading: Boolean = false){
        startHttp(isShowLoading) {
            var respnse= apiInterface().getRankList("$type")
            respnse.getCodeStatus(rankLive,nowData)
        }
    }
    fun get24HourReportInfo(id: String = "", isShowLoading: Boolean = true){
        startHttp(isShowLoading) {
            var json = JSONObject()
            json.put("id", id)
            var response = apiInterface().get24HourReportInfo(retrofits.getRequestBody(json.toString()))
            response.getCodeStatus(infoLive, nowData)
        }
    }

    private fun getTime(times:String):String{
        var times =times.toLong() * 1000
      return RxTimeTool.milliseconds2String(times, SimpleDateFormat(" yyyy-MM-dd HH:mm"))
    }



    //心率上传
    private suspend fun uploadRate(array: JSONArray): Int {
        var rb = retrofits.getRequestBody(array.toString())
        var body = apiInterface().uploadRate(rb)
        return body.code
    }

    //血压上传
    private suspend fun uploadDbp(array: JSONArray): Int {
        var rb = retrofits.getRequestBody(array.toString())
        var body = apiInterface().uploadDbp(rb)
        return body.code
    }

    //血氧上传
    private suspend fun uploadSo(array: JSONArray): Int {
        var rb = retrofits.getRequestBody(array.toString())
        var body = apiInterface().uploadSo(rb)
        return body.code
    }

    //体温上传
    private suspend fun uploadTemp(array: JSONArray): Int {
        var rb = retrofits.getRequestBody(array.toString())
        var body = apiInterface().uploadTemp(rb)
        return body.code
    }

    //呼吸率上传
    private suspend fun uploadResp(array: JSONArray): Int {
        var rb = retrofits.getRequestBody(array.toString())
        var body = apiInterface().uploadResp(rb)
        return body.code
    }

    /**
     * 睡眠上传旧
     */
    fun uploadSleepOld(array: JSONArray) {
        startHttp(false) {
            var rb = retrofits.getRequestBody(array.toString())
            var body = apiInterface().uploadSleepOld(rb)
            body.getCodeStatus(uploadSleep, nowData)
        }
    }
    /**
     * 睡眠上传
     */
    fun uploadSleep(array: JSONArray) {
        startHttp(false) {
            var rb = retrofits.getRequestBody(array.toString())
            var body = apiInterface().uploadSleep(rb)
            body.getCodeStatus(uploadSleep, nowData)
        }
    }
    /**
     * 步数上传
     */
    fun uploadStep(array: JSONArray) {
        startHttp(false) {
            var rb = retrofits.getRequestBody(array.toString())
            var body = apiInterface().uploadStep(rb)
            body.getCodeStatus(uploadStep, nowData)
        }
    }

    /**
     * 获取血糖信息
     *
     */
    fun getXtInfo(userId: String, isShowLoading: Boolean = true){
        startHttp (isShowLoading) {
            var json = JSONObject()
            json.put("userId", userId)
            var value = apiInterface().getXtInfo(retrofits.getRequestBody(json.toString()))
            value.getCodeStatus(xtInfo, nowData)
        }
    }


    /**
     * 个人设置接口
     */
    fun getMySetting(){
        startHttp (false){
            var body=apiInterface().getMySetting()

            body.getCodeStatus(settingLive,nowData)
        }
    }
    fun uploadAllInfo(array: JSONArray){
        startHttp(false) {
            var body=apiInterface().uploadAllInfo(retrofits.getRequestBody(array.toString()))
            body.getCodeStatus(uploadMultiple,nowData)
        }
    }

    fun uploadWatchTest(){
        var body = "[{\"heartValue\":74,\"hrvValue\":37,\"cvrrValue\":3,\"stepValue\":4042,\"sbpValue\":71,\"bodyFatFloatValue\":0,\"ooValue\":98,\"bodyFatIntValue\":0,\"tempIntValue\":35,\"tempFloatValue\":5,\"startTime\":1665676213,\"dbpValue\":108,\"respiratoryRateValue\":15,\"original\":\"{code=0, data=[{heartValue=74, hrvValue=37, cvrrValue=3, stepValue=4042, DBPValue=71, bodyFatFloatValue=0, OOValue=98, bodyFatIntValue=0, tempIntValue=35, tempFloatValue=5, startTime=1665676213000, SBPValue=108, respiratoryRateValue=15}], dataType=1289}\"}]"
        startHttp(false) {
            var body=apiInterface().uploadAllInfo(retrofits.getRequestBody(body))
        }
    }

    fun  getMqttInfo(){
        startHttp (false){
           var response= apiInterface().getMqttInfo()
            response.getCodeStatus(mqtt,nowData)
        }

    }

    /**
     * 获取家人
     */
    fun getMyFamilyList(){
        startHttp (false){
            var json=JSONObject()
            /* json.put("pageNum","1")
             json.put("pageSize",Const.PAGE_SIZE)*/
            var request=  apiInterface().getMyFamily(retrofits.getRequestBody(json.toString()))
            request.getCodeStatus(familyLive,nowData)
        }
    }


    /**
     * 欢迎语
     */
     fun getWelcomeInfo(id: String){
        if(id==null){
            return
        }
        startHttp(false) {

           var body= apiInterface().getWelconmInfo(id)
            if(body.code==0){
                if(body.data != null){
                    if (!body.data.welcomeWords.isNullOrEmpty()){
                        MMkvHelper.put(Const.WELCOME_DESC, body.data.welcomeWords)
                    }else{
                        MMkvHelper.remove(Const.WELCOME_DESC)
                    }
                    if (!body.data.logUrl.isNullOrEmpty()){
                        MMkvHelper.put(Const.WELCOME_IMG, body.data.logUrl)
                    }else{
                        MMkvHelper.remove(Const.WELCOME_IMG)
                    }
                    if (!body.data.id.isNullOrEmpty()){
                        MMkvHelper.put(Const.ORGAN_ID, body.data.id)
                    }else{
                        MMkvHelper.remove(Const.ORGAN_ID)
                    }
                    if (!body.data.adImgUrl.isNullOrEmpty()){
                        MMkvHelper.put(Const.WELCOME_BG, body.data.adImgUrl)
                    }else{
                        MMkvHelper.remove(Const.WELCOME_BG)
                    }
                }else{
                    if(MMkvHelper.contains(Const.WELCOME_DESC)){
                        MMkvHelper.remove(Const.WELCOME_DESC)
                    }
                    if(MMkvHelper.contains(Const.WELCOME_IMG)){
                        MMkvHelper.remove(Const.WELCOME_IMG)
                    }
                    if (MMkvHelper.contains(Const.ORGAN_ID)){
                        MMkvHelper.remove(Const.ORGAN_ID)
                    }
                    if (MMkvHelper.contains(Const.WELCOME_BG)){
                        MMkvHelper.remove(Const.WELCOME_BG)
                    }
                }
            }
        }
    }

    /**
     * 获取预警消息
     */
    fun getWarningMsg() {
        startHttp (false){
            var json = JSONObject()
            json.put("userId", CommonUtils.getMyUserId())

            var respnse = apiInterface().getWarningMsgList(retrofits.getRequestBody(json.toString()))
            respnse.getCodeStatus(warningMsgLive, nowData)
        }
    }

    /**
     *   预警消息改变已读状态
     */
    fun readMsg(id: String, notifyId: String){
        startHttp {
            var json=JSONObject()
            json.put("id", id)
            json.put("notifyId", notifyId)
            json.put("notifyStatus",1)
            json.put("notifyHandStatus",2)

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

    fun getScinceList(){
        startHttp {
            var body= apiInterface().getScinceList()
            body.getCodeStatus(scinceLive,nowData)
        }
    }
}