package com.xty.base.vm

import androidx.lifecycle.MutableLiveData
import com.xty.network.model.ChatBean
import com.xty.network.model.MqTTBean
import com.xty.network.model.RespBody
import okhttp3.MultipartBody
import org.json.JSONObject
import java.io.File

class ChatMsgVm : BaseVm() {
    val chatList by lazy { MutableLiveData<RespBody<MutableList<ChatBean>>>() }
    val sendLive by lazy { MutableLiveData<RespBody<ChatBean>>() }
    val sendMedic  by lazy { MutableLiveData<RespBody<String>>() }
    val mqttChat by lazy { MutableLiveData<RespBody<MqTTBean>>() }

    fun getHistoryMsgList(fromUserId:String,userId: String) {
        startHttp {
            var json = JSONObject()
            json.put("toUserId", userId)
            json.put("fromUserId", fromUserId)
            json.put("message_category", 2)

            var response = apiInterface().getChatList(retrofits.getRequestBody(json.toString()))
                response.getCodeStatus(chatList, nowData)
        }
    }

    fun getMqttInfo() {
        startHttp {
            var response = apiInterface().getMqttInfo()
            response.getCodeStatus(mqttChat, nowData)
        }
    }

    fun saveChat(fromUserId:String,toUserId: String, msg: String) {
        startHttp {
            var json = JSONObject()
            json.put("process_detail", msg)
            json.put("from_user_id", fromUserId)
            json.put("to_user_id", toUserId)
            json.put("type", 1)
            var response = apiInterface().saveChat(retrofits.getRequestBody(json.toString()))
            response.getCodeStatus(sendLive, nowData)
        }
    }

    /**
     * 媒体上传
     * fileType  图片1   视频 3
     */
    fun saveChatMedia(path:String,messageId:String,fileType:Int,toUserId: String,fromUserId:String,audioTime:Int=0) {
        startHttp(isShowLoading = (fileType != 2))  {
            var file=File(path)
            var part=MultipartBody.Part.createFormData("file",file.name,retrofits.getMultiPartFileRb(file))
           var msgId= retrofits.getRequestBody(messageId)
            var type=retrofits.getRequestBody("$fileType")
            var toId=retrofits.getRequestBody(toUserId)
            var fromId=retrofits.getRequestBody(fromUserId)
            var typeBody=retrofits.getRequestBody("1")
            var audioTimeLength=retrofits.getRequestBody(audioTime.toString())
            var response = apiInterface().saveChatMedia(part,msgId,type,toId,fromId,typeBody,audioTimeLength)
            response.getCodeStatus(sendMedic, nowData)
        }
    }
}