package com.zj365.health.vm

import androidx.lifecycle.MutableLiveData
import com.xty.base.vm.BaseVm
import com.xty.common.util.CommonToastUtils
import com.xty.network.model.MedicBean
import com.xty.network.model.NotAccepted
import com.xty.network.model.RespBody
import com.xty.network.model.SettingBean
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.async
import kotlinx.coroutines.withContext
import org.json.JSONArray
import org.json.JSONObject

class MedicalHistoryVm : BaseVm() {

    val medicLive by lazy { MutableLiveData<RespBody<MutableList<MedicBean>>>() }
    val setBasic by lazy { MutableLiveData<NotAccepted>() }
    val allData by lazy { MutableLiveData<RespBody<SettingBean>>() }
    fun getUserInfo(id:String?) {
        startHttp {
            var body = apiInterface().getUseInfo(id)
            body.getCodeStatus(allData, nowData)
        }
    }

    fun getMedicHistory() {
        startHttp {
            val medicHistory = apiInterface().getMedicHistory()
            medicHistory.getCodeStatus(medicLive, nowData)
        }
    }

    fun submit(
        medicNames: String,
        medicIds: String,
        tumour: String,
        other: String,
        diseaseList: String,
        userId: String?
    ) {

        startHttp {
            withContext(Dispatchers.IO) {
                var upload = async { uploadInfo(medicNames, medicIds, tumour, other, diseaseList,userId) }
                val await = upload.await() //个人信息上传
                if (await.code != 0) {
                    CommonToastUtils.showToast(await.msg)
                } else {
                    setBasic.postValue(await.data)
                }
            }
        }
    }

    private suspend fun uploadInfo(
        medicNames: String,
        medicIds: String,
        tumour: String,
        other: String,
        diseaseList: String,
        userId:String?
    ): RespBody<NotAccepted> {
        var json = JSONObject()

        json.put("id",userId)
        json.put("historyId", medicIds)

        json.put("tumour", tumour)
        json.put("other", other)
        if (diseaseList.isNullOrEmpty()) {
            json.put("diseaseList", "")
        } else {
            var array = JSONArray(diseaseList) //去掉转移的斜杠
            json.put("diseaseList", array)
        }

        var rb = retrofits.getRequestBody(json.toString())
        var body = apiInterface().setUpdateUser(rb)
        return body
    }

}