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.UserCharacteristic
import com.iscs.bozzys.ui.common.VMBase
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
import java.io.File

/**
 * 人脸数据模型页面
 */
class VMFace : VMBase() {

    private val _state = MutableStateFlow(StateFace())

    val state = _state.asStateFlow()

    // 当前用户id
    private var userId = 0

    // 用户名称，上传特征的时候需要调用
    private var username = ""

    /**
     * 做数据初始化操作
     */
    fun init(userId: Int = 0, username: String = "") {
        this.userId = userId
        this.username = username
        getFaceList(true)
    }

    /**
     * 获取人脸数据列表
     */
    fun getFaceList(showLoading: Boolean = false) {
        viewModelScope.launch(Dispatchers.IO) {
            if (showLoading) loading.emit(StateLoading(show = true))
            ApiRequest.getUserCharacteristicList(mutableMapOf("pageNo" to 1, "pageSize" to 10, "userId" to userId, "type" to 2)).onSuccess {
                delay(200)
                loading.emit(StateLoading())
                delay(100)
                _state.value = _state.value.copy(faceList = (it.data?.list ?: emptyList()).toMutableList(), isFirstLoad = false)
            }.onFailure {
                delay(500)
                loading.emit(StateLoading())
                toast.emit(it.getResponse<Any>().msg)
            }
        }
    }

    /**
     * 删除特征数据
     */
    fun deleteFaceData() {
        viewModelScope.launch(Dispatchers.IO) {
            loading.emit(StateLoading(show = true))
            ApiRequest.deleteUserCharacteristic(mutableMapOf("ids" to _state.value.face.id)).onSuccess {
                delay(500)
                loading.emit(StateLoading())
                delay(100)
                getFaceList()
            }.onFailure {
                delay(500)
                loading.emit(StateLoading())
                delay(100)
                toast.emit(it.getResponse<Any>().msg)
            }
        }
    }

    /**
     * 上传人脸照片
     *
     * @param file
     */
    fun uploadUserFace(file: File) {
        viewModelScope.launch(Dispatchers.IO) {
            loading.emit(StateLoading(show = true))
            ApiRequest.uploadUserFace(username, file).onSuccess {
                delay(500)
                loading.emit(StateLoading())
                delay(100)
                getFaceList()
            }.onFailure {
                delay(500)
                loading.emit(StateLoading())
                delay(100)
                val ersp = it.getResponse<Any>()
                if (ersp.code == 500) {
                    toast.emit("未识别到人脸，请重新上传")
                } else {
                    toast.emit(ersp.msg)
                }
            }
        }
    }

    /**
     * 显示删除弹窗
     */
    fun showDeleteTips(face: UserCharacteristic) {
        _state.value = _state.value.copy(showDeleteTips = true, face = face)
    }

    /**
     * 隐藏删除弹窗
     */
    fun hideDeleteTips() {
        _state.value = _state.value.copy(showDeleteTips = false)
    }

}

/**
 * 人脸页面状态存储
 *
 * @param faceList  人脸列表
 * @param showDeleteTips    是否显示删除弹框
 * @param isFirstLoad       是否首次加载，以免
 */
data class StateFace(
    val faceList: MutableList<UserCharacteristic> = mutableListOf(),
    val showDeleteTips: Boolean = false,
    val isFirstLoad: Boolean = true,
    val face: UserCharacteristic = UserCharacteristic()
)