package com.zj365.health.vm

import android.annotation.SuppressLint
import android.text.TextUtils
import androidx.lifecycle.MutableLiveData
import com.xty.base.vm.BaseVm
import com.xty.common.util.CommonUtils
import com.xty.network.model.*
import okhttp3.MultipartBody
import org.json.JSONArray
import org.json.JSONObject
import java.io.File
import java.text.ParseException
import java.text.SimpleDateFormat

class DataManageVm : BaseVm() {
    val getDataListOb by lazy { MutableLiveData<RespBody<PaingBean<HealthDataBean>>>() }
    val getMedicalDataListOb by lazy { MutableLiveData<RespBody<PaingBean<MedicalDataBean>>>() }
    val addDataOb by lazy { MutableLiveData<RespBody<Any>>() }
    val editOb by lazy { MutableLiveData<RespBody<Any>>() }
    val deleteOb by lazy { MutableLiveData<RespBody<Any>>() }
    val editMedicalOb by lazy { MutableLiveData<RespBody<Any>>() }
    val imageLive1 by lazy { MutableLiveData<RespBody<MutableList<String>>>() }
    val getTendencyReturnData by lazy { MutableLiveData<RespBody<DataManageTendencyBean>>() }
    val getRecentyHealthReturnData by lazy { MutableLiveData<RespBody<RecentlyHealthBean>>() }
    val getBloodLipidReturnData by lazy { MutableLiveData<RespBody<BloodLipidDataBean>>() }

    fun getChatData(
        userId: String,
        dataType: String
    ) {
        val json = JSONObject()
        json.put("userId", userId)
        json.put("deviceType", dataType)
        startHttp {
            val recentlyHealth =
                apiInterface().getChatData(retrofits.getRequestBody(json.toString()))
            recentlyHealth.getCodeStatus(getRecentyHealthReturnData, nowData)
        }
    }
    fun edittMedical(
        id: Int?,
        path1: List<String>,
        path2: List<String>,
        remark: String,
        name: String = "",
        time: String = "",
        orgName: String = ""
    ) {

        val json = JSONObject()
        json.put("id", id)
        json.put("remark", remark)
        json.put("name", name)
        json.put("time", time)
        json.put("orgName", orgName)
        if (path1.isNotEmpty()) {
            val jsonArray = JSONArray()
            for (s in path1) {
                val examinationList = JSONObject()
                examinationList.put("imageUrl", s)
                jsonArray.put(examinationList)
            }
            json.put("examinationList", jsonArray)
        }
        if (path2.isNotEmpty()) {
            val jsonArray = JSONArray()
            for (s in path2) {
                val examinationList = JSONObject()
                examinationList.put("imageUrl", s)
                jsonArray.put(examinationList)
            }
            json.put("medicationList", jsonArray)
        }

        startHttp {
            val body = apiInterface().editHealthFileData(retrofits.getRequestBody(json.toString()))
            body.getCodeStatus(editMedicalOb, nowData)
        }
    }

    fun edittUseMedical(
        id: Int?,
        path1: List<String>,
        path2: List<String>,
        remark: String,
        name: String = "",
        orgName: String = "",
        startTime: String = "",
        endTime: String = "",
        medicalName: String = ""
    ) {

        val json = JSONObject()
        json.put("id", id)
        json.put("remark", remark)
        json.put("name", name)
        json.put("startTime", startTime)
        json.put("endTime", endTime)
        json.put("medicineName", medicalName)
        json.put("orgName", orgName)
        if (path1.isNotEmpty()) {
            val jsonArray = JSONArray()
            for (s in path1) {
                val examinationList = JSONObject()
                examinationList.put("imageUrl", s)
                jsonArray.put(examinationList)
            }
            json.put("examinationList", jsonArray)
        }
        if (path2.isNotEmpty()) {
            val jsonArray = JSONArray()
            for (s in path2) {
                val examinationList = JSONObject()
                examinationList.put("imageUrl", s)
                jsonArray.put(examinationList)
            }
            json.put("medicationList", jsonArray)
        }

        startHttp {
            val body = apiInterface().editHealthFileData(retrofits.getRequestBody(json.toString()))
            body.getCodeStatus(editMedicalOb, nowData)
        }
    }

    fun edittHospitalMedical(
        id: Int?,
        path1: List<String>,
        path2: List<String>,
        remark: String,
        startTime: String = "",
        endTime: String = "",
        hospitalName: String = "",
        hospitalHint: String = ""
    ) {

        val json = JSONObject()
        json.put("id", id)
        json.put("remark", remark)
        json.put("startTime", startTime)
        json.put("endTime", endTime)
        json.put("hospital", hospitalName)
        json.put("hospitalExplain", hospitalHint)

        if (path1.isNotEmpty()) {
            val jsonArray = JSONArray()
            for (s in path1) {
                val examinationList = JSONObject()
                examinationList.put("imageUrl", s)
                jsonArray.put(examinationList)
            }
            json.put("hospitalList", jsonArray)
        }
        if (path2.isNotEmpty()) {
            val jsonArray = JSONArray()
            for (s in path2) {
                val examinationList = JSONObject()
                examinationList.put("imageUrl", s)
                jsonArray.put(examinationList)
            }
            json.put("hospitalList", jsonArray)
        }

        startHttp {
            val body = apiInterface().editHealthFileData(retrofits.getRequestBody(json.toString()))
            body.getCodeStatus(editMedicalOb, nowData)
        }
    }

    fun deleteMedical(list: MutableList<MedicalDataBean>) {
        val builder = java.lang.StringBuilder()
        for (s in list) {
            builder.append(s.id)
            val index = list.indexOf(s)
            if (index != 0 || index != list.size - 1) {
                builder.append(",")
            }
        }
        startHttp {
            val json = JSONObject()
            json.put("ids", builder.toString())
            val response = apiInterface().deleteHealthData(builder.toString())
            response.getCodeStatus(addDataOb, nowData)
        }
    }

    /**
     * 删除图片
     */
    fun deleteMedicalFile(paths: List<String>) {
        var ids = ""
        paths.forEach {
            ids = "$ids$it,"
        }
        startHttp {
            val body = apiInterface().deleteHealthCheckFiles(ids)
            body.getCodeStatus(deleteOb, nowData)
        }
    }

    fun submitHospital(
        path1: List<String>,
        path2: List<String>,
        remark: String,
        hospitalHint: String,
        startTime: String,
        endTime: String,
        hospitalName: String,
        type: String,
        userId: String?
    ) {
        val json = JSONObject()
        json.put("remark", remark)
        json.put("userId", userId)
        json.put("dataType", type)
        json.put("startTime", "$startTime 00:00:00")
        json.put("endTime", "$endTime 00:00:00")
        json.put("hospitalExplain", hospitalHint)
        json.put("hospital", hospitalName)
        val upType =
            if (TextUtils.equals(CommonUtils.getMyUserId(), userId) || userId.isNullOrEmpty()) {
                "1"
            } else {
                "5"
            }
        json.put("upType", upType)

        if (path1.isNotEmpty()) {
            val jsonArray = JSONArray()
            for (s in path1) {
                val examinationList = JSONObject()
                examinationList.put("imageUrl", s)
                jsonArray.put(examinationList)
            }
            json.put("hospitalList", jsonArray)
        }
        if (path2.isNotEmpty()) {
            val jsonArray = JSONArray()
            for (s in path2) {
                val examinationList = JSONObject()
                examinationList.put("imageUrl", s)
                jsonArray.put(examinationList)
            }
            json.put("hospitalList", jsonArray)
        }

        startHttp {
            val body = apiInterface().addHealthFileData(retrofits.getRequestBody(json.toString()))
            body.getCodeStatus(addDataOb, nowData)
        }
    }

    fun submitUseMedical(
        path1: List<String>,
        path2: List<String>,
        remark: String,
        medicalName: String,
        startTime: String,
        endTime: String,
        type: String,
        userId: String?
    ) {
        val json = JSONObject()
        json.put("remark", remark)
        json.put("userId", userId)
        json.put("dataType", type)
        json.put("startTime", "$startTime 00:00:00")
        json.put("endTime", "$endTime 00:00:00")
        json.put("medicineName", medicalName)
        val upType =
            if (TextUtils.equals(CommonUtils.getMyUserId(), userId) || userId.isNullOrEmpty()) {
                "1"
            } else {
                "5"
            }
        json.put("upType", upType)

        if (path1.isNotEmpty()) {
            val jsonArray = JSONArray()
            for (s in path1) {
                val examinationList = JSONObject()
                examinationList.put("imageUrl", s)
                jsonArray.put(examinationList)
            }
            json.put("examinationList", jsonArray)
        }
        if (path2.isNotEmpty()) {
            val jsonArray = JSONArray()
            for (s in path2) {
                val examinationList = JSONObject()
                examinationList.put("imageUrl", s)
                jsonArray.put(examinationList)
            }
            json.put("medicationList", jsonArray)
        }

        startHttp {
            val body = apiInterface().addHealthFileData(retrofits.getRequestBody(json.toString()))
            body.getCodeStatus(addDataOb, nowData)
        }
    }

    /**
     * 提交饮食数据
     */
    fun submitYShiData(
        userId: String,
        path1: List<RevampImgBean>,
        createTime: String,
        mealType: Int,
        time: String,
        mealExplain: String,
        type: String
    ) {
        val json = JSONObject()
        json.put("mealType", mealType)
        json.put("createTime", createTime)
        json.put("userId", userId)
        json.put("dataType", type)
        if (isValidDate(time)) {
            json.put("time", time)
        } else {
            json.put("time", "${time}:00")
        }
        json.put("mealExplain", mealExplain)
        if (path1.isNotEmpty()) {
            val jsonArray = JSONArray()
            for (s in path1) {
                val examinationList = JSONObject()
                examinationList.put("imageUrl", s.imageUrl)
                jsonArray.put(examinationList)
            }
            json.put("mealList", jsonArray)
        }
        val upType =
            if (TextUtils.equals(CommonUtils.getMyUserId(), userId) || userId.isNullOrEmpty()) {
                "1"
            } else {
                "5"
            }
        json.put("upType", upType)

        startHttp {
            val body = apiInterface().addHealthFileData(retrofits.getRequestBody(json.toString()))
            body.getCodeStatus(addDataOb, nowData)
        }
    }

    /**
     * 修改饮食数据
     */
    fun edittYShiData(
        userId: String,
        id: Int?,
        path1: List<RevampImgBean>,
        createTime: String,
        mealType: Int,
        time: String,
        mealExplain: String,
        type: String,
    ) {
        val json = JSONObject()
        json.put("id", id)
        json.put("mealType", mealType)
        json.put("createTime", createTime)
        json.put("userId", userId)
        json.put("dataType", type)
        if (isValidDate(time)) {
            json.put("time", time)
        } else {
            json.put("time", "${time}:00")
        }
        json.put("mealExplain", mealExplain)
        if (path1.isNotEmpty()) {
            val jsonArray = JSONArray()
            for (s in path1) {
                val examinationList = JSONObject()
                examinationList.put("imageUrl", s.imageUrl)
                if (s.id!! > 0) {
                    examinationList.put("id", s.id)
                }
                jsonArray.put(examinationList)
            }
            json.put("mealList", jsonArray)
        }

        startHttp {
            val body = apiInterface().editHealthFileData(retrofits.getRequestBody(json.toString()))
            body.getCodeStatus(editMedicalOb, nowData)
        }
    }

    /**
     * 校验时间格式
     */
    @SuppressLint("SimpleDateFormat")
    private fun isValidDate(str: String): Boolean {
        var convertSuccess = true
        // 指定日期格式为四位年/两位月份/两位日期，注意yyyy/MM/dd区分大小写；
        val format = SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
        try {
            // 设置lenient为false. 否则SimpleDateFormat会比较宽松地验证日期，比如2007/02/29会被接受，并转换成2007/03/01
            format.isLenient = false
            format.parse(str)
        } catch (e: ParseException) {
            // e.printStackTrace();
            // 如果throw java.text.ParseException或者NullPointerException，就说明格式不对
            convertSuccess = false
        }
        return convertSuccess
    }

    fun yshiDelete(list: MutableList<MedicalDataBean>) {
        val builder = StringBuilder()
        for (s in list) {
            builder.append(s.id)
            val index = list.indexOf(s)
            if (index != 0 || index != list.size - 1) {
                builder.append(",")
            }
        }
        startHttp {
            val json = JSONObject()
            json.put("ids", builder.toString())
            val response = apiInterface().deleteHealthData(builder.toString())
            response.getCodeStatus(addDataOb, nowData)
        }
    }

    fun submitMedical(
        path1: List<String>,
        path2: List<String>,
        type: String,
        name: String,
        time: String,
        orgName: String,
        remark: String = "",
        userId: String?
    ) {
        val json = JSONObject()
        json.put("remark", remark)
        json.put("userId", userId)
        json.put("dataType", type)
        json.put("name", name)
        json.put("orgName", orgName)
        json.put("time", time)
        val upType =
            if (TextUtils.equals(CommonUtils.getMyUserId(), userId) || userId.isNullOrEmpty()) {
                "1"
            } else {
                "5"
            }
        json.put("upType", upType)

        if (path1.isNotEmpty()) {
            val jsonArray = JSONArray()
            for (s in path1) {
                val examinationList = JSONObject()
                examinationList.put("imageUrl", s)
                jsonArray.put(examinationList)
            }
            json.put("examinationList", jsonArray)
        }
        if (path2.isNotEmpty()) {
            val jsonArray = JSONArray()
            for (s in path2) {
                val examinationList = JSONObject()
                examinationList.put("imageUrl", s)
                jsonArray.put(examinationList)
            }
            json.put("medicationList", jsonArray)
        }

        startHttp {
            val body = apiInterface().addHealthFileData(retrofits.getRequestBody(json.toString()))
            body.getCodeStatus(addDataOb, nowData)
        }
    }

    /**
     * 上传图片
     */
    fun uploadImagesFiles(path: List<String>) {
        if (path.isEmpty()) {
            return
        }
        val list = mutableListOf<MultipartBody.Part>()
        for (s in path) {
            if (s.contains("http")) {
                continue
            }
            val f = File(s)
            val rb =
                MultipartBody.Part.createFormData("files", f.name, retrofits.getMultiPartFileRb(f))
            list.add(rb)
        }
        if (list.isEmpty()) {
            return
        }
        startHttp {
            val body = apiInterface().uploadImagesFile(list)
            body.getCodeStatus(imageLive1, nowData)
        }
    }

    fun uploadImagesMedicalFile(path: List<String>) {
        if (path.isEmpty()) {
            return
        }
        val list = mutableListOf<MultipartBody.Part>()
        for (s in path) {
            if (s.contains("http")) {
                continue
            }
            val f = File(s)
            val rb =
                MultipartBody.Part.createFormData("files", f.name, retrofits.getMultiPartFileRb(f))
            list.add(rb)
        }
        if (list.isEmpty()) {
            return
        }
        startHttp {
            val body = apiInterface().uploadImagesFile(list)
            body.getCodeStatus(imageLive1, nowData)
        }
    }

    fun getMedicalDataList(page: Int) {
        val myUserId = CommonUtils.getMyUserId()
        startHttp {
            val json = JSONObject()
            json.put("pageNum", page)
            json.put("pageSize", 20)
            json.put("userId", myUserId)
            val response =
                apiInterface().getHealthFileData(retrofits.getRequestBody(json.toString()))
            response.getCodeStatus(getMedicalDataListOb, nowData)
        }
    }

    /**
     * 饮食记录列表
     */
    fun getYShiDataList(
        userId: String,
        page: Int,
        dataType: String,
        year: String,
        month: String,
        isUpload: Boolean
    ) {
        startHttp {
            val json = JSONObject()
            if (isUpload) {
                json.put("orderSort", 1)
            } else {
                json.put("orderSort", 2)
            }
            if (!TextUtils.isEmpty(year)) {
                json.put("year", year)
            }
            if (!TextUtils.isEmpty(month)) {
                json.put("month", month)
            }
            json.put("dataType", dataType)
            json.put("pageNum", page)
            json.put("pageSize", 20)
            json.put("userId", userId)
            val response =
                apiInterface().getHealthFileData(retrofits.getRequestBody(json.toString()))
            response.getCodeStatus(getMedicalDataListOb, nowData)
        }
    }

    /**
     * 删除数据
     */
    fun delete(list: MutableList<HealthDataBean>) {
        val builder = java.lang.StringBuilder()
        for (s in list) {
            builder.append(s.id)
            val index = list.indexOf(s)
            if (index != 0 || index != list.size - 1) {
                builder.append(",")
            }
        }
        startHttp {
            val json = JSONObject()
            json.put("ids", builder.toString())
            val response = apiInterface().deleteHealthData(builder.toString())
            response.getCodeStatus(deleteOb, nowData)
        }
    }

    /**
     * 数据添加
     */
    fun addData(
        userId: String?,
        dataType: String?,
        time: String?,
        dataValue: String?,//可以传体重值
        tcStr: String,
        tgStr: String,
        hdlStr: String,
        ldlStr: String,
        height: String//身高
    ) {
        startHttp {
            val json = JSONObject()
            json.put("time", "$time:00")
            json.put("dataType", dataType)
            json.put("dataValue", dataValue)
            json.put("height", height)
            json.put("tc", tcStr)
            json.put("tg", tgStr)
            json.put("hdl", hdlStr)
            json.put("ldl", ldlStr)
            json.put("userId", userId)
            val upType =
                if (TextUtils.equals(CommonUtils.getMyUserId(), userId) || userId.isNullOrEmpty()) {
                    "1"
                } else {
                    "5"
                }
            json.put("upType", upType)
            val response = apiInterface().addHealthData(retrofits.getRequestBody(json.toString()))
            response.getCodeStatus(addDataOb, nowData)
        }
    }

    /**
     * 修改数据
     */
    fun editData(
        id: String?,
        dataType: String?,
        time: String?,
        dataValue: String?,
        tcStr: String,
        tgStr: String,
        hdlStr: String,
        ldlStr: String,
        height: String//身高
    ) {
        startHttp {
            val json = JSONObject()
            json.put("time", "$time:00")
            json.put("id", id)
            json.put("dataType", dataType)
            json.put("dataValue", dataValue)
            json.put("tc", tcStr)
            json.put("tg", tgStr)
            json.put("hdl", hdlStr)
            json.put("ldl", ldlStr)
            json.put("height", height)
            val response = apiInterface().editHealthData(retrofits.getRequestBody(json.toString()))
            response.getCodeStatus(editOb, nowData)
        }
    }

    /**
     * 数据列表网络请求
     */
    fun getDataList(
        userId: String,
        dataType: String?,
        orderSort: String?,
        page: Int,
        year: String,
        month: String,
        pageSize: Int = 20
    ) {
        startHttp {
            val json = JSONObject()
            json.put("pageNum", page)
            json.put("pageSize", pageSize)
            dataType?.let {
                json.put("dataType", it)
            }
            json.put("orderSort", orderSort)
            json.put("year", year)
            json.put("month", month)
            json.put("userId", userId)
            val response =
                apiInterface().getHealthDataList(retrofits.getRequestBody(json.toString()))
            response.getCodeStatus(getDataListOb, nowData)
        }
    }

    /**
     * 数据对比
     */
    fun interceptingDate(
        id: String,
        type: Int,
        dataType: String,
        dateTime: String,
        comDateTime: String,
    ) {
        var endDate = ""
        var date = dateTime
        var comTimeEnd = ""
        var comDateTimeStr = comDateTime
        if (type == 2) {
            val split = date.split("至")
            val end = split[0]
            val start = split[1]
            val splitCom = comDateTime.split("至")
            val comEnd = splitCom[0]
            val comStart = splitCom[1]
            date = end
            endDate = start
            comTimeEnd = comStart
            comDateTimeStr = comEnd
        }
        startHttp(true) {
            if(dataType == "5"){
                getLineChartDataByBloodLipid(
                    id,
                    type,
                    dataType,
                    date,
                    endDate,
                    comDateTimeStr,
                    comTimeEnd
                )
            }else{
                getLineChartData(
                    id,
                    type,
                    dataType,
                    date,
                    endDate,
                    comDateTimeStr,
                    comTimeEnd
                )
            }

        }
    }

    //数据管理请求
    private suspend fun getLineChartData(
        id: String,
        type: Int,
        dataType: String,
        date: String,
        endDate: String,
        compareDate: String,
        compareEndDate: String
    ) {
        val json = JSONObject()
        json.put("id", id)
        json.put("type", type)
        json.put("date", date)
        json.put("dataType", dataType)
        json.put("compareDate", compareDate)
        json.put("compareEndDate", compareEndDate)
        json.put("endDate", endDate)
        val xtFindNew =
            apiInterface().getTendencyData(retrofits.getRequestBody(json.toString()))
        xtFindNew.getCodeStatus(getTendencyReturnData, nowData)
    }

    //数据管理请求
    private suspend fun getLineChartDataByBloodLipid(
        id: String,
        type: Int,
        dataType: String,
        date: String,
        endDate: String,
        compareDate: String,
        compareEndDate: String
    ) {
        val json = JSONObject()
        json.put("id", id)
        json.put("type", type)
        json.put("date", date)
        json.put("dataType", dataType)
        json.put("compareDate", compareDate)
        json.put("compareEndDate", compareEndDate)
        json.put("endDate", endDate)
        val xtFindNew =
            apiInterface().getTendencyDataByBloodLipid(retrofits.getRequestBody(json.toString()))
        xtFindNew.getCodeStatus(getBloodLipidReturnData, nowData)
    }

    //请求最近趋势图健康数据
    fun getRecentlyHealthData(
        userId: String,
        dataType: String
    ) {
        val json = JSONObject()
        json.put("userId", userId)
        json.put("dataType", dataType)
        startHttp {
            val recentlyHealth =
                apiInterface().getRecentlyHealth(retrofits.getRequestBody(json.toString()))
            recentlyHealth.getCodeStatus(getRecentyHealthReturnData, nowData)
        }
    }
}