package com.cheng.blzb.ui.fragment.mine.user

import android.content.Context
import androidx.lifecycle.MutableLiveData
import com.cheng.blzb.bean.UploadFileEntity
import com.cheng.blzb.bean.UserEntity
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 com.huantansheng.easyphotos.models.album.entity.Photo
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.MultipartBody
import okhttp3.RequestBody

class UserSettingViewModel : BaseViewModel() {
    val userInfoLiveData = MutableLiveData<UserEntity>()
    val uploadImgLiveData = MutableLiveData<UploadFileEntity>()
    val uploadUserinfoLiveData = MutableLiveData<Any>()
    val deleteImageLiveData = MutableLiveData<String>()

    fun userInfo() {
        showDialog()
        launchOnUiTryCatch({
            val response = ApiFactory.apiService.userInfo()
            if (response.status) {
                userInfoLiveData.postValue(response.data)
            } else toast(response.message, true)
            dismissDialog()
        }, {
            dismissDialog()
            setError(it)
            L.d(it)
        })
    }

    fun uploadImg(context: Context, photo: Photo) {
        showDialog()
        BitmapUtils.compressImg(context, photo.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, "avatar")
                if (response.status) {
                    uploadImgLiveData.postValue(response.data)
                } else toast(response.message, true)
                dismissDialog()
            }, {
                dismissDialog()
                setError(it)
                L.d(it)
            })
        }
    }

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

    fun deleteImg(id: String) {
        launchOnUiTryCatch({
            val response = ApiFactory.apiService.delUserFile(id)
            if (response.status) {
                deleteImageLiveData.postValue(id)
            }
        }, {
            setError(it)
            L.d(it)
        })
    }
}