package com.img.rabbit.viewmodel

import android.content.Context
import android.net.Uri
import androidx.compose.runtime.mutableStateOf
import com.img.rabbit.bean.local.ErrorBean
import com.img.rabbit.bean.local.FileManagerBean
import com.img.rabbit.provider.api.ApiManager
import com.img.rabbit.utils.ImageUtils
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.MultipartBody
import okhttp3.RequestBody
import java.io.IOException

class FeedbackViewModel : BaseViewModel() {
    // 错误状态
    val errorState = mutableStateOf<ErrorBean?>(null)

    // 反馈类型
    private val _feedbackType = mutableStateOf(FeedbackType.FUNCTION)
    val feedbackType: FeedbackType
        get() = _feedbackType.value

    fun setFeedbackType(feedbackType: FeedbackType) {
        _feedbackType.value = feedbackType
    }

    // 补充反馈
    private val _feedbackMore = mutableStateOf("")
    val feedbackMore: String
        get() = _feedbackMore.value

    fun setFeedbackMore(feedbackMore: String) {
        _feedbackMore.value = feedbackMore
    }

    //提供图片
    private val _currentImageUris = mutableStateOf(emptyList<Uri>())
    val currentImageUris: List<Uri>
        get() = _currentImageUris.value

    fun setCurrentImageUris(currentImageUris: List<Uri>) {
        _currentImageUris.value = currentImageUris
    }

    // 上传文件
    private val _uploadFiles = mutableStateOf(emptyList<FileManagerBean>())
    val uploadFiles: List<FileManagerBean>
        get() = _uploadFiles.value

    fun setUploadFiles(uploadFiles: List<FileManagerBean>) {
        _uploadFiles.value = uploadFiles
    }

    // 联系方式
    private val _feedbackContact = mutableStateOf("")
    val feedbackContact: String
        get() = _feedbackContact.value

    fun setFeedbackContact(feedbackContact: String) {
        _feedbackContact.value = feedbackContact
    }


    fun uploadImage(context: Context, uri: Uri) {
        isLoading.value = true // 开始加载
        mLaunch {
            try {
                val compressedUri = ImageUtils.imageCompressToUri(context, uri) ?: throw IOException("无法压缩图片")
                val requestFile = RequestBody.create("multipart/form-data".toMediaTypeOrNull(), compressedUri)
                val filePart = MultipartBody.Part.createFormData("file", uri.lastPathSegment, requestFile)
                val response = ApiManager.serviceVo.upload(filePart, "feedback")
                if (response.status) {
                    val updateFile = FileManagerBean(response.data, uri)
                    setUploadFiles(uploadFiles + updateFile)
                }else{
                    errorState.value = ErrorBean(response.code.toString(), response.message.ifEmpty { "上传失败" })
                }
                isLoading.value = false // 开始加载
            }catch (e: IOException){
                e.printStackTrace()
                isLoading.value = false // 开始加载
            }

        }
    }

    fun batchDeleteImage(uris: List<Uri>) {
        isLoading.value = true // 开始加载
        uris.forEach {
            deleteImage(it)
        }
    }

    fun deleteImage(uri: Uri) {
        isLoading.value = true // 开始加载
        val fileId = uploadFiles.firstOrNull { it.uri == uri }?.fileEntity?.id
        if(fileId.isNullOrEmpty()){
            isLoading.value = false // 开始加载
            return
        }
        mLaunch {
            val response = ApiManager.serviceVo.deleteFile(fileId)
            if (response.status) {
                setUploadFiles(uploadFiles.filter { it.uri != uri })
            }else{
                errorState.value = ErrorBean(response.code.toString(), response.message.ifEmpty { "删除失败" })
            }
            isLoading.value = false // 开始加载
        }
    }

    fun submitFeedback(requestBody: RequestBody) {
        isLoading.value = true // 开始加载
        mLaunch {
            val response = ApiManager.serviceVo.feedback(requestBody)
            if (response.status) {
                errorState.value = ErrorBean(response.code.toString(), response.message.ifEmpty { "谢谢您的反馈！" })
            }else{
                errorState.value = ErrorBean(response.code.toString(), response.message.ifEmpty { "提交失败..." })
            }
            isLoading.value = false // 开始加载
        }
    }

    enum class FeedbackType(val keyName: String, val value: String) {
        FUNCTION("function", "功能问题"),
        FEATURE("feature", "功能建议"),
        OTHER("other", "其他")
    }
}