package com.iscs.bozzys.ui.pages.vm

import androidx.lifecycle.viewModelScope
import com.iscs.bozzys.api.ApiRequest
import com.iscs.bozzys.api.ApiRequest.getResponse
import com.iscs.bozzys.api.ApiRequest.isCodeOk
import com.iscs.bozzys.api.User
import com.iscs.bozzys.event.RefreshEvent
import com.iscs.bozzys.event.RefreshEventBus
import com.iscs.bozzys.ui.common.VMBase
import com.iscs.bozzys.utils.Storage
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
import java.io.File

/**
 * 用户属性编辑界面
 */
class VMProfile : VMBase() {

    private val _state = MutableStateFlow(StateProfile())

    val state = _state.asStateFlow()

    /**
     * 初始化操作
     */
    fun init(user: User) {
        _state.value = _state.value.copy(user = user)
    }

    /**
     * 更新用户头像
     *
     * @param file 用户选择的头像文件
     */
    fun updateUserAvatar(file: File) {
        viewModelScope.launch {
            loading.emit(StateLoading(show = true, content = "更新中"))
            val uploadRsp = ApiRequest.uploadFile(file).getOrElse { it.getResponse() }
            if (!uploadRsp.code.isCodeOk()) {
                delay(1000)
                loading.emit(StateLoading())
                toast.emit(uploadRsp.msg)
                return@launch
            }
            val avatar = uploadRsp.data ?: ""
            val updateRsp = ApiRequest.updateUserProfile(mutableMapOf("avatar" to avatar)).getOrElse { it.getResponse() }
            delay(1000)
            loading.emit(StateLoading())
            if (!updateRsp.code.isCodeOk()) {
                toast.emit(updateRsp.msg)
                return@launch
            }
            // 更新头像数据
            _state.value = _state.value.copy(user = _state.value.user.copy(avatar = avatar))
            // 通知首页更新用户信息
            RefreshEventBus.onRefreshData(RefreshEvent.UpdateUserInfo.apply { value = _state.value.user })
        }
    }

    fun showModifyDialog(title: String, kv: Pair<String, String>) {
        _state.value = _state.value.copy(showModifyDialog = true, modifyDialogTitle = title, modifyKv = kv)
    }

    fun onModifyValueChanged(value: String) {
        _state.value = _state.value.copy(modifyKv = _state.value.modifyKv.first to value)
    }

    fun hideModifyDialog() {
        _state.value = _state.value.copy(showModifyDialog = false)
    }

    fun updateUserInfo() {
        viewModelScope.launch {
            val kv = _state.value.modifyKv
            val params: Pair<String, Any> = if (kv.first == "sex") kv.first to kv.second.toInt() else kv
            loading.emit(StateLoading(show = true, content = "更新中"))
            val updateRsp = ApiRequest.updateUserProfile(mutableMapOf(params)).getOrElse { it.getResponse() }
            delay(1000)
            loading.emit(StateLoading())
            if (!updateRsp.code.isCodeOk()) {
                toast.emit(updateRsp.msg)
                return@launch
            }
            val user = when (kv.first) {
                "nickname" -> _state.value.user.copy(nickname = kv.second)
                "mobile" -> _state.value.user.copy(mobile = kv.second)
                "email" -> _state.value.user.copy(email = kv.second)
                "sex" -> _state.value.user.copy(sex = kv.second.toInt())
                else -> _state.value.user
            }
            // 更新头像数据
            _state.value = _state.value.copy(user = user)
            // 通知首页更新用户信息
            RefreshEventBus.onRefreshData(RefreshEvent.UpdateUserInfo.apply { value = _state.value.user })
        }
    }

    fun showClearCacheDialog() {
        _state.value = _state.value.copy(showClearCacheDialog = true)
    }

    /**
     * 清除指定缓存数据
     */
    fun clearStorageCache() {
        viewModelScope.launch {
            Storage.clearCache()
            delay(500)
            toast.emit("清除成功")
        }

    }

    fun hideClearCacheDialog() {
        _state.value = _state.value.copy(showClearCacheDialog = false)
    }

}

data class StateProfile(
    val user: User = User(),
    val showModifyDialog: Boolean = false,
    val modifyDialogTitle: String = "",
    val modifyKv: Pair<String, String> = "" to "",
    val showClearCacheDialog: Boolean = false,
)