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

import androidx.lifecycle.viewModelScope
import com.iscs.bozzys.api.ApiRequest
import com.iscs.bozzys.api.UploadFile
import com.iscs.bozzys.ui.common.VMBase
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch

class VMFormUploadFile : VMBase() {

    private val _state = MutableStateFlow(StateFormUploadFile())

    val state = _state.asStateFlow()

    /**
     * 数据初始化操作
     */
    fun init(values: List<String>) {
        val list = values.map { UploadFile(url = it, state = 1) }.toMutableList()
        _state.value = _state.value.copy(files = list)
    }

    /**
     * 上传文件
     */
    fun uploadFile(file: UploadFile, done: (values: List<String>) -> Unit) {
        viewModelScope.launch(Dispatchers.IO) {
            val list = _state.value.files.toMutableList()
            list.add(0, file)
            _state.value = _state.value.copy(files = list)
            // 执行附件上传
            if (file.file != null) {
                ApiRequest.uploadFile(file.file, type = file.type).onSuccess { rsp ->
                    // 上传成功后修改状态
                    val list = _state.value.files.map { if (it.file?.path == file.file.path) it.copy(url = rsp.data ?: "", state = 1) else it }
                        .toMutableList()
                    _state.value = _state.value.copy(files = list)
                    done(list.map { it.url })
                }.onFailure {
                    val list = _state.value.files.map { if (it.file?.path == file.file.path) it.copy(state = 2) else it }.toMutableList()
                    _state.value = _state.value.copy(files = list)
                }
            }
        }
    }

    /**
     * 删除指定文件
     */
    fun delete(file: UploadFile) {
        val list = _state.value.files.filter { it.url != file.url && ((it.file?.path ?: "") != (file.file?.path ?: "")) }.toMutableList()
        _state.value = _state.value.copy(files = list)
    }

    /**
     * 校验最多可以选择文件个数
     */
    fun checkCanSelect(max: Int = 1): Boolean {
        return if (_state.value.files.size == max) {
            viewModelScope.launch {
                toast.emit("最多可选择${max}个文件")
            }
            false
        } else {
            true
        }
    }

}

/**
 *
 */
data class StateFormUploadFile(val files: MutableList<UploadFile> = mutableListOf())