package com.zj365.dc.vm

import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Typeface
import android.text.TextUtils
import androidx.core.content.ContextCompat
import androidx.lifecycle.MutableLiveData
import com.tamsiree.rxkit.RxTimeTool
import com.xty.base.utils.OrganStatusCalcUtil
import com.xty.base.vm.BaseVm
import com.xty.common.Const
import com.xty.common.Dateutils
import com.xty.common.MMkvHelper
import com.xty.common.TimeUtils
import com.xty.common.util.CommonUtils
import com.xty.common.util.DeviceFunctionUtils
import com.xty.network.model.DeviceFunctionBean
import com.xty.network.model.FamilyBean
import com.xty.network.model.HealthMonitoringListBean
import com.xty.network.model.MainBean
import com.xty.network.model.MessageBean
import com.xty.network.model.MqTTBean
import com.xty.network.model.NotAccepted
import com.xty.network.model.RankBean
import com.xty.network.model.ReportBean
import com.xty.network.model.RespBody
import com.xty.network.model.SettingBean
import com.xty.network.model.TipsBean
import com.xty.network.model.WeatherBean
import com.xty.network.model.XTangInfoBean
import com.zj365.dc.R
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.async
import kotlinx.coroutines.withContext
import org.json.JSONArray
import org.json.JSONObject
import java.text.SimpleDateFormat

class DynamicManagementVm : BaseVm() {

    val allData by lazy { MutableLiveData<RespBody<MainBean>>() }
    val xtInfo by lazy { MutableLiveData<RespBody<XTangInfoBean>>() }
    val infoLive by lazy { MutableLiveData<RespBody<ReportBean>>() }

    //    val dkInfo by lazy{ MutableLiveData<RespBody<DkBean>>() }
//    val bannerLive by lazy { MutableLiveData<RespBody<List<BannerBean>>>()  }
    val warningMsgLive by lazy { MutableLiveData<RespBody<MessageBean>>() }
    val settingLive by lazy { MutableLiveData<RespBody<SettingBean>>() }
    val familyLive by lazy { MutableLiveData<RespBody<MutableList<FamilyBean>>>() }
    val tipsLive by lazy { MutableLiveData<RespBody<MutableList<TipsBean>>>() }
    val rankLive by lazy { MutableLiveData<RespBody<RankBean>>() }
    val uploadStep by lazy { MutableLiveData<RespBody<String>>() }
    val allDataInfo by lazy { MutableLiveData<MutableMap<String, Any>>() }
    val uploadSleep by lazy { MutableLiveData<RespBody<String>>() }
    val mqtt by lazy { MutableLiveData<RespBody<MqTTBean>>() }
    val uploadMultiple by lazy { MutableLiveData<RespBody<NotAccepted>>() }

    val weatherLiveDate by lazy { MutableLiveData<RespBody<WeatherBean>>() }

    val functionLiveData by lazy { MutableLiveData<RespBody<MutableList<DeviceFunctionBean>>>() }

    /**
     * 获取所有信息
     */
    fun getAllInfo(id: String, isShowDialog: Boolean,isTimer:Boolean = false) {
        startHttp(isShowDialog) {
            withContext(Dispatchers.IO){
                if(isTimer){
                    val json = JSONObject()
                    json.put("id", id)
                    val body = apiInterface().getMainInfo(retrofits.getRequestBody(json.toString()))
                    body.getCodeStatus(allData, nowData)
                }else{
                    val list = async { getDeviceFunctionLists(id) }.await()

                    if (list){
                        val allInfo =    async {
                            val json = JSONObject()
                            json.put("id", id)
                            val body = apiInterface().getMainInfo(retrofits.getRequestBody(json.toString()))
                            body.getCodeStatus(allData, nowData)
                        }
                    }
                }

            }

        }
    }

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

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

    fun get24HourReportInfo(id: String = "", isShowLoading: Boolean = true) {
        startHttp(isShowLoading) {
            val json = JSONObject()
            json.put("id", id)
            val response =
                apiInterface().get24HourReportInfo(retrofits.getRequestBody(json.toString()))
            response.getCodeStatus(infoLive, nowData)
        }
    }

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

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

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

            body.getCodeStatus(settingLive, nowData)
        }
    }

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

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

    /**
     * 获取排名信息
     */
    fun getRank(type: Int, isShowLoading: Boolean = false) {
        startHttp(isShowLoading) {
            val respnse = apiInterface().getRankList("$type")
            respnse.getCodeStatus(rankLive, nowData)
        }
    }

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

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

    /**
     * 欢迎语
     */
    fun getWelcomeInfo(id: String) {
        if (id == null) {
            return
        }
        startHttp(false) {
            val body = apiInterface().getWelconmInfo(id)
            if (body.code == 0) {
                if (body.data != null) {
                    if (body.data.welcomeWords.isNotEmpty()) {
                        MMkvHelper.put(Const.WELCOME_DESC, body.data.welcomeWords)
                    } else {
                        MMkvHelper.remove(Const.WELCOME_DESC)
                    }
                    if (body.data.logUrl.isNotEmpty()) {
                        MMkvHelper.put(Const.WELCOME_IMG, body.data.logUrl)
                    } else {
                        MMkvHelper.remove(Const.WELCOME_IMG)
                    }
                    if (body.data.id.isNotEmpty()) {
                        MMkvHelper.put(Const.ORGAN_ID, body.data.id)
                    } else {
                        MMkvHelper.remove(Const.ORGAN_ID)
                    }
                    if (body.data.adImgUrl.isNotEmpty()) {
                        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) {
            val json = JSONObject()
            json.put("userId", CommonUtils.getMyUserId())

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

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

    //设置健康监测按钮列表数据
    @SuppressLint("SimpleDateFormat")
    fun setHealthMonitoringListData(
        context: Context,
        bean: MainBean,
        functionList:MutableList<DeviceFunctionBean>?
    ): MutableList<HealthMonitoringListBean> {
        val healthMonitoringList: MutableList<HealthMonitoringListBean> = mutableListOf()

        bean.apply {
            MMkvHelper.put(Const.X1_X2_Device, false)
            functionList?.forEach {
                if (DeviceFunctionUtils.hasFunction(it,"hr")){ //心率
                    val statusXL = if (hrData.hr == 0) {
                        0
                    } else if (hrData.hrMessage.contains("正常")) {
                        1
                    } else {
                        2
                    }
                    val contentXL = if (hrData.hr == 0) "--" else hrData.hr.toString()
                    val mTimeXL = milliseconds2String(hrData.hrTime)
                    healthMonitoringList.add(
                        HealthMonitoringListBean(
                            "心率",
                            statusXL,
                            mTimeXL,
                            contentXL,
                            R.mipmap.bg_xl,
                            R.mipmap.ic_xl,
                            0,
                            it.type,
                            calorie = hrData.count
                        )
                    )

                }else if (DeviceFunctionUtils.hasFunction(it,"so")){ //血氧
                    val statusXY = if (soData.so == 0) {
                        0
                    } else if (soData.soMessage.contains("正常")) {
                        1
                    } else {
                        2
                    }
                    val contentXY = if (soData.so == 0) "--" else soData.so.toString()
                    val mTimeXY = milliseconds2String(soData.soTime)
                    healthMonitoringList.add(
                        HealthMonitoringListBean(
                            "血氧",
                            statusXY,
                            mTimeXY,
                            contentXY,
                            R.mipmap.bg_oo,
                            R.mipmap.ic_oo,
                            1,
                            it.type,
                            calorie = soData.count
                        )
                    )
                }else if(DeviceFunctionUtils.hasFunction(it,"resp")){ //呼吸率
                    val statusHXL = if (respiratoryData.respiratory == 0) {
                        0
                    } else if (respiratoryData.respiratoryMessage.contains("正常")) {
                        1
                    } else {
                        2
                    }
                    val contentHXL =
                        if (respiratoryData.respiratory == 0) "--" else respiratoryData.respiratory.toString()
                    val mTimeHXL = milliseconds2String(respiratoryData.respiratoryTime)
                    healthMonitoringList.add(
                        HealthMonitoringListBean(
                            "呼吸率",
                            statusHXL,
                            mTimeHXL,
                            contentHXL,
                            R.mipmap.bg_breath,
                            R.mipmap.ic_h_breath,
                            2,
                            it.type,
                            calorie = respiratoryData.count
                        )
                    )
                }else if(DeviceFunctionUtils.hasFunction(it,"temp")){ //体温
                    val statusTW = if (tempData.tempInt == 0) {
                        0
                    } else if (tempData.tempMessage.contains("正常")) {
                        1
                    } else {
                        2
                    }
                    val contentTW =
                        if (tempData.tempInt == 0) "--" else "${tempData.tempInt}.${tempData.tempFloat}"
                    val mTimeTW = milliseconds2String(tempData.tempTime)
                    healthMonitoringList.add(
                        HealthMonitoringListBean(
                            "体温",
                            statusTW,
                            mTimeTW,
                            contentTW,
                            R.mipmap.bg_temp,
                            R.mipmap.ic_temp,
                            3,
                            it.type,
                            calorie = tempData.count
                        )
                    )
                }else if(DeviceFunctionUtils.hasFunction(it,"step")){ //步数
                    val contentBS =
                        if (stepData.step == 0) "--" else stepData.step.toString()
                    val mTimeBS = if (stepData.stepTime.isNullOrEmpty()) {
                        RxTimeTool.getCurrentDateTime("yyyy-MM-dd HH:mm")
                    } else (if (stepData.stepTime.contains("-")) {
                        stepData.stepTime.let {
                            it.substring(0, it.length - 3)
                        }
                    } else {
                        milliseconds2String(stepData.stepTime)
                    })
                    val calorieBS = caloriesData
                    healthMonitoringList.add(
                        HealthMonitoringListBean(
                            "步数",
                            0,
                            mTimeBS,
                            contentBS,
                            R.mipmap.bg_step,
                            R.mipmap.ic_steps,
                            4,
                            it.type,
                            calorie = calorieBS
                        )
                    )
                }else if(DeviceFunctionUtils.hasFunction(it,"sleep")){  //睡眠
                    val statusSM = 0
                    val contentSM = if (sleepData.sleep.toLong() <= 0) {
                        "-小时-分"
                    } else {
                        sleepData.sleep.toLong().let {
                            TimeUtils.secToSpan(
                                it,
                                18,
                                ContextCompat.getColor(
                                    context,
                                    R.color.col_464
                                ),
                                Typeface.BOLD,
                            ).toString()
                        }
                    }
                    val mTimeSM = if (sleepData.sleepTime == 0) {
                        RxTimeTool.getCurrentDateTime("yyyy-MM-dd HH:mm")
                    } else {
                        milliseconds2String(sleepData.sleepTime.toString())
                    }
                    healthMonitoringList.add(
                        HealthMonitoringListBean(
                            "睡眠",
                            statusSM,
                            mTimeSM,
                            contentSM,
                            R.mipmap.bg_h_sleep,
                            R.mipmap.ic_h_sleep,
                            5,
                            it.type,
                            calorie = sleepData.count
                        )
                    )
                }else if(DeviceFunctionUtils.hasFunction(it,"dbp")){ //血压
                    val statusXYa = if (dbpData.GDbp == 0 && dbpData.DDbp == 0) {
                        0
                    } else if (dbpData.DbpMessage.contains("正常")) {
                        1
                    } else {
                        2
                    }
                    val contentXYa = if (dbpData.GDbp == 0 && dbpData.DDbp == 0) {
                        "--"
                    } else {
                        "${dbpData.GDbp}/${dbpData.DDbp}"
                    }
                    val mTimeXYa = milliseconds2String(dbpData.DbpTime)
                    healthMonitoringList.add(
                        HealthMonitoringListBean(
                            "血压",
                            statusXYa,
                            mTimeXYa,
                            contentXYa,
                            R.mipmap.bg_xya,
                            R.mipmap.ic_xya,
                            6,
                            it.type,
                            calorie = dbpData.count
                        )
                    )
                }else if(DeviceFunctionUtils.hasFunction(it,"sugar")){ //血糖
                    var statusXT = 0
                    var contentXT = ""
                    var mTimeXT = ""
                    when (bloodSugarData.model) {//如果有errorMsg则为建模中
                        //0 未开通 1：建模中 2：建模完成
                        0 -> {
                            if (TextUtils.isEmpty(bloodSugarData.expireTime)) {
                                contentXT = "未开通"
                                mTimeXT = "免费体验100天"
                                statusXT = 3
                            } else {
                                contentXT = "续费"
                                mTimeXT = RxTimeTool.getCurrentDateTime("yyyy-MM-dd HH:mm")
                                statusXT = 0
                            }
                        }

                        1 -> {
                            statusXT = 1
                            contentXT = "建模中"
                            mTimeXT = if (bloodSugarData.time.isNullOrEmpty()) {
                                "${RxTimeTool.getCurrentDateTime("yyyy-MM-dd HH")}:00"
                            } else if (bloodSugarData.time.contains("-")) {
                                bloodSugarData.time
                            } else {
                                "${
                                    RxTimeTool.simpleDateFormat(
                                        "yyyy-MM-dd HH",
                                        RxTimeTool.string2Date(
                                            "yyyy-MM-dd HH:mm:ss",
                                            bloodSugarData.time
                                        )
                                    )
                                }:00"
                            }
                        }

                        2 -> {
                            statusXT =
                                if (bloodSugarData.bloodsugar.toFloat() == 0f) {
                                    0
                                } else if (OrganStatusCalcUtil.bloodSugarStatu(bloodSugarData.bloodsugar.toFloat()) == 0) {
                                    1
                                } else {
                                    2
                                }
                            contentXT = if (bloodSugarData.bloodsugar.toFloat() == 0f) {
                                "--"
                            } else {
                                bloodSugarData.bloodsugar
                            }
                            mTimeXT = if (bloodSugarData.time.isNullOrEmpty()) {
                                "${RxTimeTool.getCurrentDateTime("yyyy-MM-dd HH")}:00"
                            } else {
                                "${
                                    RxTimeTool.simpleDateFormat(
                                        "yyyy-MM-dd HH",
                                        RxTimeTool.string2Date(
                                            "yyyy-MM-dd HH:mm:ss",
                                            bloodSugarData.time
                                        )
                                    )
                                }:00"
                            }
                        }
                    }
                    healthMonitoringList.add(
                        HealthMonitoringListBean(
                            "血糖",
                            statusXT,
                            mTimeXT,
                            contentXT,
                            R.mipmap.bg_bloodsugar,
                            R.mipmap.ic_bloodsugar,
                            7,
                            it.type,
                            calorie = bloodSugarData.count
                        )
                    )
                }else if(DeviceFunctionUtils.hasFunction(it,"ecg")){ //心电
                    val statusXD = 0
                    val contentXD =
                        if (TextUtils.isEmpty(heartData.hrData) || heartData.hrData == "0") {
                            "--"
                        } else {
                            heartData.hrData
                        }
                    val mTimeXD = milliseconds2String(heartData.heartTimeV2)
                    healthMonitoringList.add(
                        HealthMonitoringListBean(
                            "心电",
                            statusXD,
                            mTimeXD,
                            contentXD,
                            R.mipmap.bg_ecg,
                            R.mipmap.ic_ecg,
                            8,
                            it.type,
                        )
                    )
                }else if(DeviceFunctionUtils.hasFunction(it,"uric")){  //尿酸
                    var statusNS = 0
                    var contentNS = ""
                    var mTimeNS = ""
                    when (uricAcidData.status) {
                        //0 未开通 1：建模中 2：建模完成
                        0 -> {
                            if (TextUtils.isEmpty(uricAcidData.expireTime)) {
                                contentNS = "未开通"
                                mTimeNS = "免费体验100天"
                                statusNS = 3
                            } else {
                                contentNS = "续费"
                                mTimeNS = RxTimeTool.getCurrentDateTime("yyyy-MM-dd HH:mm")
                                statusNS = 0
                            }
                        }

                        1 -> {
                            statusNS = 1
                            contentNS = "建模中"
                            mTimeNS = if (uricAcidData.time.isNullOrEmpty()) {
                                "${milliseconds2String(uricAcidData.time)}:00"
                            } else if (uricAcidData.time.contains("-")) {
                                uricAcidData.time
                            } else {
                                "${
                                    milliseconds2String(uricAcidData.time)
                                }:00"
                            }
                        }

                        2 -> {
                            statusNS =
                                if (uricAcidData.value == "0" || TextUtils.isEmpty(uricAcidData.value)) {
                                    0
                                } else if (uricAcidData.message.contains("正常")) {
                                    1
                                } else {
                                    2
                                }
                            contentNS =
                                if (!TextUtils.isEmpty(uricAcidData.value)) uricAcidData.value else "--"
                            mTimeNS = milliseconds2String(uricAcidData.time)
                        }
                    }
                    healthMonitoringList.add(
                        HealthMonitoringListBean(
                            "尿酸",
                            statusNS,
                            mTimeNS,
                            contentNS,
                            R.mipmap.bg_niaosuan,
                            R.mipmap.ic_niaosuan,
                            9,
                            it.type,
                            sex = user.sex.toString(),
                            calorie = uricAcidData.count
                        )
                    )
                }else if(DeviceFunctionUtils.hasFunction(it,"bloodFat")){ //血脂
                    //血脂
                    var statusXZ = 0
                    var contentXZ = ""
                    var mTimeXZ = ""
                    when (bloodFatData.status) {
                        //0 未开通 1：建模中 2：建模完成
                        0 -> {
                            if (TextUtils.isEmpty(bloodFatData.expireTime)) {
                                contentXZ = "未开通"
                                mTimeXZ = "免费体验100天"
                                statusXZ = 3
                            } else {
                                contentXZ = "续费"
                                mTimeXZ = RxTimeTool.getCurrentDateTime("yyyy-MM-dd HH:mm")
                                statusXZ = 0
                            }
                        }

                        1 -> {
                            statusXZ = 1
                            contentXZ = "建模中"
                            mTimeXZ = if (bloodFatData.time.isNullOrEmpty()) {
                                "${RxTimeTool.getCurrentDateTime("yyyy-MM-dd HH")}:00"
                            } else if (bloodFatData.time.contains("-")) {
                                bloodFatData.time
                            } else {
//                                "${
//                                    RxTimeTool.simpleDateFormat(
//                                        "yyyy-MM-dd HH",
//                                        RxTimeTool.string2Date(
//                                            "yyyy-MM-dd HH:mm:ss",
//                                            bloodFatData.time
//                                        )
//                                    )
//                                }:00"
                                milliseconds2String(bloodFatData.time)
                            }
                        }

                        2 -> {
                            statusXZ =
                                if (bloodFatData.value == "0" || TextUtils.isEmpty(bloodFatData.value)) {
                                    0
                                } else if (bloodFatData.message.contains("正常")) {
                                    1
                                } else {
                                    2
                                }
                            contentXZ =
                                if (!TextUtils.isEmpty(bloodFatData.value)) bloodFatData.value else "--"
                            mTimeXZ = milliseconds2String(bloodFatData.time)
                        }
                    }
                    healthMonitoringList.add(
                        HealthMonitoringListBean(
                            "血脂",
                            statusXZ,
                            mTimeXZ,
                            contentXZ,
                            R.mipmap.bg_fat,
                            R.mipmap.ic_fat,
                            10,
                            it.type
                        )
                    )
                }
            }
        }
        return healthMonitoringList
    }

    @SuppressLint("SimpleDateFormat")
    private fun milliseconds2String(strTime: String): String {
        return RxTimeTool.milliseconds2String(
            strTime.toLong() * 1000,
            SimpleDateFormat("yyyy-MM-dd HH:mm")
        )
    }

     fun getWeather(){
        startHttp {
            val json = JSONObject()
            json.put("longitude", MMkvHelper.getDouble(Const.LONGITUDE))
            json.put("latitude", MMkvHelper.getDouble(Const.LATITUDE))
            val body = apiInterface().getWeather(retrofits.getRequestBody(json.toString()))
            body.getCodeStatus(weatherLiveDate, nowData)
        }
    }

    suspend fun getDeviceFunctionLists(id:String):Boolean{
        val json = JSONObject()
        json.put("id", id)
        val body = apiInterface().getDeviceFunctionList(retrofits.getRequestBody(json.toString()))
        body.getCodeStatus(functionLiveData, nowData)
        return true
    }
}