package com.zj365.health.vm

import android.text.TextUtils
import androidx.lifecycle.MutableLiveData
import com.xty.base.vm.BaseVm
import com.xty.common.Const
import com.xty.network.model.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import org.json.JSONArray
import org.json.JSONObject

class XTangVm : BaseVm() {

    val upload by lazy { MutableLiveData<RespBody<String>>() }
    val open by lazy { MutableLiveData<RespBody<XTangOpenBean>>() }
    val xtInfo by lazy { MutableLiveData<RespBody<XTangInfoBean>>() }
    val xtInfoDetail by lazy { MutableLiveData<RespBody<XtNewBean>>() }
    val bloodSugarInfo by lazy { MutableLiveData<RespBody<XTangInfoBean>>() }
    val bloodSugarDetail by lazy { MutableLiveData<RespBody<MutableList<XTangInfoDetailBean>>>() }
    val xtHistory by lazy { MutableLiveData<RespBody<MutableList<XTangHistoryBean>>>() }
    val xtSection by lazy { MutableLiveData<RespBody<MutableList<XTangSectionBean>>>() }
    val xtSectionList by lazy { MutableLiveData<RespBody<PaingBean<BloodSugarNewbean>>>() }
    val getPriceData by lazy { MutableLiveData<RespBody<PriceBean>>() }
    val renewOpenData by lazy { MutableLiveData<RespBody<OpenOrRenewBean>>() }
    val firstOpenData by lazy { MutableLiveData<RespBody<FirstOpenBean>>() }
    val deleteBloodCalibrationData by lazy { MutableLiveData<RespBody<Any>>() }

    /**
     * 获取血糖、尿酸、血脂价格图片
     */
    fun getPriceRequest(type: Int) {
        startHttp {
            val price = apiInterface().getPrice(type)
            price.getCodeStatus(getPriceData, nowData)
        }
    }

    /**
     * 血糖上传
     */
    fun xtUpload(params: JSONArray) {
        startHttp {
            val value = apiInterface().xtUpload(retrofits.getRequestBody(params.toString()))
            value.getCodeStatus(upload, nowData)
        }
    }

    /**
     * 血糖开通/血糖续费
     * @param actCode 激活码
     */
    fun xtOpen(userId: String, actCode: String) {
        startHttp {
            val json = JSONObject()
            json.put("userId", userId)
            json.put("tumourCode", actCode)
            val value = apiInterface().xtOpen(retrofits.getRequestBody(json.toString()))
            value.getCodeStatus(open, nowData)
        }
    }

    /**
     * （血糖/尿酸）首次开通
     */
    fun firstOpen(userId: String, pageType:Int) {
        startHttp {
            val json = JSONObject()
            json.put("id", userId)
            //1,血糖，2，尿酸，3，血脂
            when(pageType) {
                1 -> {
                    val xueTangFirstOpen = apiInterface().xueTangFirstOpen(retrofits.getRequestBody(json.toString()))
                    xueTangFirstOpen.getCodeStatus(firstOpenData, nowData)
                }
                2 -> {
                    val niaoSuanFirstOpen = apiInterface().niaoSuanFirstOpen(retrofits.getRequestBody(json.toString()))
                    niaoSuanFirstOpen.getCodeStatus(firstOpenData, nowData)
                }

                3->{
                    val bloodFilipFirstOpen = apiInterface().openBloodLipidFirstOpen(retrofits.getRequestBody(json.toString()))
                    bloodFilipFirstOpen.getCodeStatus(firstOpenData,nowData)
                }
            }
        }
    }

    /**
     * 血糖尿酸血脂续费（新）
     */
    fun renewOpenRequest(
        userId: String,//用户ID
        subject: Int,//3，血糖续费开通，4，尿酸续费开通，5，血脂续费开通
        channelName: String,//支付方式（ALIPAY_APP：支付宝支付，WEIXIN_APP：微信支付，EXCHANGE_CODE：兑换码兑换
        exchangeCode: String//兑换码
    ) {
        startHttp {
            val json = JSONObject()
            json.put("id", userId)
            json.put("subject", subject)
            json.put("channelName", channelName)
            if (!TextUtils.isEmpty(exchangeCode)) {
                json.put("exchangeCode", exchangeCode)
            }
            val renewOpen = apiInterface().renewOpen(retrofits.getRequestBody(json.toString()))
            renewOpen.getCodeStatus(renewOpenData, nowData)
        }
    }

    /**
     * 获取血糖信息
     * @param type 日：0 周：1 月：2 年：3
     */
    fun getXtInfo(userId: String) {
        startHttp {
            val json = JSONObject()
            json.put("userId", userId)
            val value = apiInterface().getXtInfo(retrofits.getRequestBody(json.toString()))
            value.getCodeStatus(xtInfo, nowData)
        }
    }

    /**
     * 获取血糖详情
     * @param type 日：0 周：1 月：2 年：3
     */
    fun getXtInfoDetail(userId: String, type: Int, time: String?, isDemonstrate: Boolean) {

        if (isDemonstrate) {
            startHttp {
                withContext(Dispatchers.IO) {
                    val json = JSONObject()
                    json.put("type", type)
                    json.put("signType", 6)//体征类型1，血压，2，心率，3，呼吸率，4，体温，5，血氧，6，血糖，7，睡眠,8,健康报告
                    val value =
                        apiInterface().findDemonstrateBloodsugar(retrofits.getRequestBody(json.toString()))
                    value.getCodeStatus(xtInfoDetail, nowData)
                }
            }
        } else {
            var endDate: String? = ""
            var date = time
            if (type == 2) {
                val split = date?.split("至")
                val start = split?.get(0)
                val end = split?.get(1)
                date = start
                endDate = end
            }
            startHttp {
                withContext(Dispatchers.IO) {
                    val json = JSONObject()
                    json.put("id", userId)
                    json.put("type", type)
                    json.put("date", date)
                    json.put("endDate", endDate)
                    val value =
                        apiInterface().getXtFindNew(retrofits.getRequestBody(json.toString()))
                    value.getCodeStatus(xtInfoDetail, nowData)
                }
            }
        }
    }

    /**
     * 获取糖化血红蛋白信息
     * @param type 日：0 周：1 月：2 年：3
     */
    fun getBloodSugarInfo(userId: String) {
        startHttp {
            val json = JSONObject()
            json.put("userId", userId)
            val value = apiInterface().getBloodSugarInfo(userId)
            value.getCodeStatus(bloodSugarInfo, nowData)
        }
    }

    /**
     * 获取糖化血红蛋白详情
     * @param type 日：0 周：1 月：2 年：3
     */
    fun getBloodSugarDetail(userId: String, type: Int, time: String?) {
        startHttp {
            val json = JSONObject()
            json.put("userId", userId)
            json.put("type", type)
            json.put("time", time)
            val value =
                apiInterface().getBloodSugarDetail(retrofits.getRequestBody(json.toString()))
            value.getCodeStatus(bloodSugarDetail, nowData)
        }
    }

    /**
     * 获取血糖上传记录
     */
    fun getXtHistory(userId: String) {
        startHttp {
            val json = JSONObject()
            json.put("userId", userId)
            val value = apiInterface().getXtHistory(retrofits.getRequestBody(json.toString()))
            value.getCodeStatus(xtHistory, nowData)
        }
    }

    /**
     * 血糖校准记录新
     * */
    fun getXtHistoryNew(id: Int, page: Int) {
        val json = JSONObject()
        json.put("id", id)
        json.put("pageNum", page)
        json.put("pageSize", Const.PAGE_SIZE)
        startHttp {
            val body =
                apiInterface().calibrationSugarHistoryNew(retrofits.getRequestBody(json.toString()))
            body.getCodeStatus(xtSectionList, nowData)
        }
    }

    fun getXtSection(userId: Long) {
        startHttp {
            val value = apiInterface().getXtSection(userId)
            value.getCodeStatus(xtSection, nowData)
        }
    }

    /**
     * 批量删除血糖校准记录
     */
    fun deleteBloodCalibrationRequest(list: MutableList<BloodSugarNewbean>){
        var ids = ""
        list.forEachIndexed { _, bloodSugarNewbean ->
            ids += "${bloodSugarNewbean.id},"
        }
        startHttp {
            val deleteBloodCalibration = apiInterface().deleteBloodCalibration(ids)
            deleteBloodCalibration.getCodeStatus(deleteBloodCalibrationData, nowData)
        }
    }
}