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.FormField
import com.iscs.bozzys.api.FormOption
import com.iscs.bozzys.ui.common.VMBase
import com.iscs.bozzys.ui.pages.compose.getFormListByJsonList
import com.iscs.bozzys.utils.LogUtil
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch

class VMCreateJob : VMBase() {

    // 内部维护
    private val _state = MutableStateFlow(StateCreateJob())

    // 对Compose暴露
    val state = _state.asStateFlow()

    // 表单基准数据
    val json = "[{\"id\":\"job_name\",\"label\":\"作业名称\",\"value\":[\"\"],\"type\":\"input\",\"placeholder\":[\"请输入作业名称\"],\"required\":true},{\"id\":\"job_sop\",\"label\":\"流程模板\",\"value\":[\"\"],\"type\":\"select\",\"placeholder\":[\"\"],\"required\":true,\"options\":[]},{\"id\":\"job_type\",\"label\":\"作业分类\",\"value\":[\"\"],\"type\":\"select\",\"placeholder\":[\"\"],\"options\":[],\"required\":true},{\"id\":\"job_content\",\"label\":\"作业内容\",\"value\":[\"\"],\"type\":\"textarea\",\"placeholder\":[\"\"],\"required\":true},{\"id\":\"job_urgency_level\",\"label\":\"紧急程度\",\"value\":[\"0\"],\"type\":\"radio\",\"placeholder\":[\"\"],\"required\":false,\"options\":[{\"label\":\"普通\",\"value\":\"0\"},{\"label\":\"紧急\",\"value\":\"1\"},{\"label\":\"非常紧急\",\"value\":\"2\"}]}]"

    // 当前作业id
    private var id = 0

    /**
     * 初始化
     * @param id 如果id > 0认为编辑
     */
    fun init(id: Int) {
        this.id = id
        LogUtil.d("JobCreate", "创建时需要的表单 -> $json")
        viewModelScope.launch {
            val job = if (id > 0) ApiRequest.getJobById(id).getOrElse { it.getResponse() }.data else null
            val forms = json.getFormListByJsonList(job)
            _state.value = _state.value.copy(forms = forms)
            // 流程模板
            ApiRequest.getSopList(mutableMapOf("pageNo" to 1, "pageSize" to -1)).onSuccess {
                val data = it.data?.list ?: emptyList()
                val options = data.map { sop -> FormOption(sop.name, sop.id.toString()) }
                val newForms = _state.value.forms.map { form -> if (form.id == "job_sop") form.copy(options = options) else form }
                _state.value = _state.value.copy(forms = newForms)
            }
            // 作业类型
            ApiRequest.getDictData(mutableMapOf("pageNo" to 1, "pageSize" to -1, "dictType" to "work_type")).onSuccess {
                val data = it.data?.list ?: emptyList()
                val options = data.map { dict -> FormOption(dict.label, dict.value) }
                val newForms = _state.value.forms.map { form -> if (form.id == "job_type") form.copy(options = options) else form }
                _state.value = _state.value.copy(forms = newForms)
            }
            // 紧急程度
            ApiRequest.getDictData(mutableMapOf("pageNo" to 1, "pageSize" to -1, "dictType" to "urgency_level")).onSuccess {
                val data = it.data?.list ?: emptyList()
                val options = data.map { dict -> FormOption(dict.label, dict.value) }
                val newForms = _state.value.forms.map { form -> if (form.id == "job_urgency_level") form.copy(options = options) else form }
                _state.value = _state.value.copy(forms = newForms)
            }
        }
    }

    /**
     * 创建作业操作
     */
    fun onNext(done: (Int) -> Unit) {
        viewModelScope.launch {
            // 校验必要参数的值是否有效
            _state.value.forms.forEach {
                if (it.required) {
                    if (it.value.isEmpty() || (it.value.getOrNull(0) ?: "").isEmpty()) {
                        if (listOf("input", "textarea").contains(it.type)) {
                            toast.emit("请输入${it.label}")
                        } else if (listOf("select", "date", "radio").contains(it.type)) {
                            toast.emit("请选择${it.label}")
                        }
                        return@launch
                    }
                }
            }
            // 这里调用创建接口进行作业的创建
            loading.emit(StateLoading(show = true))
            val name = _state.value.forms.find { it.id == "job_name" }?.value?.getOrNull(0) ?: ""
            val sop = _state.value.forms.find { it.id == "job_sop" }?.value?.getOrNull(0) ?: "0"
            val type = _state.value.forms.find { it.id == "job_type" }?.value?.getOrNull(0) ?: ""
            val content = _state.value.forms.find { it.id == "job_content" }?.value?.getOrNull(0) ?: ""
            val level = _state.value.forms.find { it.id == "job_urgency_level" }?.value?.getOrNull(0) ?: ""
            ApiRequest.createOrEditJob(
                id,
                mutableMapOf(
                    "name" to name,
                    "designId" to sop.toInt(),
                    "type" to type,
                    "description" to content,
                    "urgencyLevel" to level
                )
            ).onSuccess {
                delay(500)
                loading.emit(StateLoading())
                toast.emit(if (id > 0) "修改成功" else "创建成功")
                delay(500)
                val res = it.data
                if (res is Boolean) {
                    // 修改返回的数据是布尔型
                    done(id)
                } else if (res is Double) {
                    // 创建成功返回的是Int类型
                    done(res.toInt())
                }
            }.onFailure {
                delay(500)
                loading.emit(StateLoading())
                toast.emit(it.getResponse<Int>().msg)
            }
        }
    }

}

/**
 * 表单数据
 */
data class StateCreateJob(val forms: List<FormField> = listOf())