package com.cheng.blzb.ui.fragment.mine.order.cert

import android.content.Context
import androidx.lifecycle.MutableLiveData
import com.cheng.blzb.bean.OrderEntity
import com.cheng.blzb.bean.UploadFileEntity
import com.cheng.blzb.net.ApiFactory
import com.cheng.blzb.utils.BitmapUtils
import com.example.base.extensions.toast
import com.example.base.utils.L
import com.example.base.viewmodel.BaseViewModel
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.MultipartBody
import okhttp3.RequestBody

class CertificateViewModel : BaseViewModel() {
    val orderLiveData = MutableLiveData<OrderEntity>()
    val updateLiveData = MutableLiveData<Any>()
    val imageLiveData = MutableLiveData<UploadFileEntity>()

    fun getOrderInfo(orderId: String) {
        showDialog()
        launchOnUiTryCatch({
            val response = ApiFactory.apiService.getOrderInfo(orderId)
            if (response.status) {
                orderLiveData.postValue(response.data)
            } else toast(response.message, true)
            dismissDialog()
        }, {
            dismissDialog()
            setError(it)
            L.d(it)
        })
    }

    fun updateOrder(requestBody: RequestBody) {
        showDialog()
        launchOnUiTryCatch({
            val response = ApiFactory.apiService.updateOrder(requestBody)
            if (response.status) {
                updateLiveData.postValue(Any())
            } else toast(response.message, true)
            dismissDialog()
        }, {
            dismissDialog()
            setError(it)
            L.d(it)
        })
    }

    fun uploadImg(context: Context, path: String) {
        showDialog()
        BitmapUtils.compressImg(context, path) {
            launchOnUiTryCatch({
                val requestFile = RequestBody.create("multipart/form-data".toMediaTypeOrNull(), it)
                val filePart = MultipartBody.Part.createFormData("file", it.getName(), requestFile)
                val response = ApiFactory.apiService.upload(filePart, "certificate")
                if (response.status) {
                    imageLiveData.postValue(response.data)
                } else toast(response.message, true)
                dismissDialog()
            }, {
                dismissDialog()
                L.d(it)
            })
        }
    }
}