package com.zj365.dc.vm

import androidx.lifecycle.MutableLiveData
import com.xty.base.vm.BaseVm
import com.xty.common.TimeUtils
import com.xty.common.util.CommonToastUtils
import com.xty.network.model.ImageUploadBean
import com.xty.network.model.NotAccepted
import com.xty.network.model.PrevBean
import com.xty.network.model.RespBody
import com.zj365.dc.R
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.async
import kotlinx.coroutines.withContext
import okhttp3.MultipartBody
import org.json.JSONArray
import org.json.JSONObject
import java.io.File

class BasicInfoVm : BaseVm() {

    val setBasic by lazy {MutableLiveData<NotAccepted>()}
    val prevLive by lazy{MutableLiveData<RespBody<PrevBean>>()}
    val activeLive by lazy {MutableLiveData<NotAccepted>()}

    fun submit(path: String,name:String,sex:String, icCard:String,height:String,weight:String,area:String,urgent:String,urgentPhone:String,urgentRelation:String
    ,province:String,city:String,district:String,lat:String,lng:String,medicNames:String,medicIds:String,signPath:String,devNum:String,code:String,devMc:String,devName:String,diseaseList:String,birthDay:String,birthdayType:Int) {

//        if(icCard.length!=18){
//            ToastUtils.show("请输入正确的身份证号")
//            return
//        }
        if(height.isNullOrEmpty()){
            CommonToastUtils.showToast("请输入身高")
            return
        }

        if (height.toFloat() < 50 || height.toFloat() > 260){
            CommonToastUtils.showToast("请输入正确身高")
            return
        }

        if(weight.isNullOrEmpty()){
            CommonToastUtils.showToast("请输入体重")
            return
        }

        if(weight.toFloat() < 3 || weight.toFloat() > 300){
            CommonToastUtils.showToast("请输入正确体重")
            return
        }

        if (TimeUtils.getAgeByBirth(birthDay) < 14){
            CommonToastUtils.showToast("需要年满14岁才可使用")
            return
        }

        if(area.isNullOrEmpty()){
            CommonToastUtils.showToast("请输入家庭住址")
            return
        }

        if(medicIds.isNullOrEmpty()){
            CommonToastUtils.showToast("请选择病史")
            return
        }


        if(urgent.isNullOrEmpty()){
            CommonToastUtils.showToast("请输入紧急联系人姓名")
            return
        }


        if(urgentPhone.isNullOrEmpty()){
            CommonToastUtils.showToast("请输入紧急联系人联系方式")
            return
        }


        if(urgentRelation.isNullOrEmpty()){
            CommonToastUtils.showToast("请输入关系")
            return
        }

        if(devMc.isNullOrEmpty()){
            CommonToastUtils.showToast(R.string.please_connect_device)
            return
        }
        if(devNum.isNullOrEmpty()){
            CommonToastUtils.showToast(R.string.please_input_device_code)
            return
        }
        if(code.isNullOrEmpty()){
            CommonToastUtils.showToast(R.string.please_input_active_code)
            return
        }
        if(signPath.isNullOrEmpty()){
            CommonToastUtils.showToast("请完善签名")
            return
        }
        startHttp {
            withContext(Dispatchers.IO) {
                var fileId:String?=null
                if(!path.isNullOrEmpty()){
                    var image = async { uploadImage(path) }
                    val await = image.await()

                    fileId = await.fileId
                }
                var upload = async {uploadInfo(name,sex,  icCard,height,weight,area,urgent,urgentPhone,urgentRelation,fileId,province,city,
                    district,lat,lng,medicNames,medicIds,diseaseList,birthDay,birthdayType) }

                val infoUpload = upload.await() //个人信息上传
                if(infoUpload.code==0){
                    var activeDev =async { active(signPath,devNum,code,devMc,devName) }
                    var signUpload=activeDev.await()
                    if(signUpload.code==0){
                        setBasic.postValue(infoUpload.data)
                    }else{
                        CommonToastUtils.showToast(signUpload.msg)
                    }
                }else{
                    CommonToastUtils.showToast(infoUpload.msg)
                }
            }

        }
    }
    fun submitNew(path: String,name:String,sex:String, icCard:String,height:String,weight:String,area:String,urgent:String,urgentPhone:String,urgentRelation:String
               ,province:String,city:String,district:String,lat:String,lng:String,medicNames:String,medicIds:String ,diseaseList:String,birthDay:String,birthdayType:Int) {

//        if(icCard.length!=18){
//            ToastUtils.show("请输入正确的身份证号")
//            return
//        }
        if(height.isNullOrEmpty()){
            CommonToastUtils.showToast("请输入身高")
            return
        }

        if (height.toFloat() < 50 || height.toFloat() > 260){
            CommonToastUtils.showToast("请输入正确身高")
            return
        }

        if(weight.isNullOrEmpty()){
            CommonToastUtils.showToast("请输入体重")
            return
        }

        if(weight.toFloat() < 3 || weight.toFloat() > 300){
            CommonToastUtils.showToast("请输入正确体重")
            return
        }

        if (TimeUtils.getAgeByBirth(birthDay) < 14){
            CommonToastUtils.showToast("需要年满14岁才可使用")
            return
        }

        if(area.isNullOrEmpty()){
            CommonToastUtils.showToast("请输入家庭住址")
            return
        }

        if(medicIds.isNullOrEmpty()){
            CommonToastUtils.showToast("请选择病史")
            return
        }


        if(urgent.isNullOrEmpty()){
            CommonToastUtils.showToast("请输入紧急联系人姓名")
            return
        }


        if(urgentPhone.isNullOrEmpty()){
            CommonToastUtils.showToast("请输入紧急联系人联系方式")
            return
        }


        if(urgentRelation.isNullOrEmpty()){
            CommonToastUtils.showToast("请输入关系")
            return
        }

        startHttp {
            withContext(Dispatchers.IO) {
                var fileId:String?=null
                if(!path.isNullOrEmpty()){
                    var image = async { uploadImage(path) }
                    val await = image.await()

                    fileId = await.fileId
                }
                var upload = async {uploadInfo(name,sex,  icCard,height,weight,area,urgent,urgentPhone,urgentRelation,fileId,province,city,
                    district,lat,lng,medicNames,medicIds,diseaseList,birthDay,birthdayType) }

                val infoUpload = upload.await() //个人信息上传
                if(infoUpload.code==0){
                    CommonToastUtils.showSucceedToast("提交成功")
                    setBasic.postValue(infoUpload.data)
                }else{
                    CommonToastUtils.showToast(infoUpload.msg)
                }
            }

        }
    }

    fun activeDevice(path:String,devNum:String,code:String,devMc:String,devName:String){
        startHttp {
            withContext(Dispatchers.IO){
                var file= File(path)
                var fileBody=MultipartBody.Part.createFormData("file",file.name,retrofits.getMultiPartFileRb(file))
                var response= apiInterface().activite(fileBody,retrofits.getRequestBody(devNum.replace(" ", "")),retrofits.getRequestBody(code.replace(" ", "")),retrofits.getRequestBody(devMc),retrofits.getRequestBody(devName))
                if (response.code == 0){
                    activeLive.postValue(response.data)
                }else{
                    CommonToastUtils.showToast(response.msg)
                }
            }
        }
    }

    /**
     * 激活设备 签名文件上传
     */
    private  suspend fun active(path:String,devNum:String,code:String,devMc:String,devName:String):RespBody<NotAccepted>{
        var file= File(path)
        var fileBody=MultipartBody.Part.createFormData("file",file.name,retrofits.getMultiPartFileRb(file))
        var response= apiInterface().activite(fileBody,retrofits.getRequestBody(devNum.replace(" ", "")),retrofits.getRequestBody(code.replace(" ", "")),retrofits.getRequestBody(devMc),retrofits.getRequestBody(devName))
        return response
    }


    private suspend fun uploadInfo(name:String,sex:String,  icCard:String,height:String,weight:String,area:String,
                                   urgent:String,urgentPhone:String,urgentRelation:String,
                                   fileId:String?,province:String,city:String,district:String,lat:String,lng:String,medicNames:String,medicIds:String,diseaseList:String,birthDay:String,birthdayType:Int): RespBody<NotAccepted> {
        var json=JSONObject()
        json.put("name",name)
        json.put("sex",sex)
        json.put("idCard",icCard)
        json.put("height",height)
        json.put("weight",weight)
        json.put("area",area)

        json.put("medicalHistory",medicNames)
        json.put("historyId",medicIds)
        json.put("latitude",lat)
        json.put("longitude",lng)
        json.put("province",province)
        json.put("city",city)
        json.put("district",district)
        json.put("birthday",birthDay)
        json.put("birthdayType",birthdayType)
        if(diseaseList.isEmpty()){
            json.put("diseaseList","")
        }else{
            var array=JSONArray(diseaseList) //去掉转移的斜杠
            json.put("diseaseList",array)
        }

        json.put("urgent",urgent)
        json.put("urgentPhone",urgentPhone)
        json.put("urgentRelation",urgentRelation)

        if(!fileId.isNullOrEmpty()){
            json.put("avatarUrl",fileId)
        }
        var rb=retrofits.getRequestBody(json.toString())
        var body=apiInterface().setUpdateUser(rb)
        return body
    }

    private suspend fun uploadImage(path: String): ImageUploadBean {
        var f = File(path)
        var fileRb =
            MultipartBody.Part.createFormData("file", f.name, retrofits.getMultiPartFileRb(f))
        var body = apiInterface().uploadImage(fileRb)
        return body.data
    }


    //1:用户协议 2:管家协议 3:隐私协议 7:佩戴须知
//    fun getPrev(type:Int){
//        startHttp {
//            var response=apiInterface().getPrev(type)
//            response.getCodeStatus(prevLive,nowData)
//        }
//    }
}