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.Job
import com.iscs.bozzys.event.RefreshEvent
import com.iscs.bozzys.event.RefreshEventBus
import com.iscs.bozzys.ui.common.VMBase
import kotlinx.coroutines.async
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch

class VMDetailJob : VMBase() {

    private val _state = MutableStateFlow(StateDetailJob())
    val state = _state.asStateFlow()

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

    /**
     * 数据初始化
     */
    fun init(id: Int) {
        this.id = id
        initEvent()
        getData(true)
    }

    private fun getData(showLoading: Boolean = false) {
        // 获取数据
        viewModelScope.launch {
            if (showLoading) loading.emit(StateLoading(show = true))
            ApiRequest.getJobById(id).onSuccess {
                it.data?.let { job -> getJobStatus(job) }
            }.onFailure {
                delay(1000)
                loading.emit(StateLoading())
                toast.emit(it.getResponse<Any>().msg)
            }
        }
    }

    /**
     * 获取作业状态数据
     *
     * @param job
     */
    private fun getJobStatus(job: Job) {
        viewModelScope.launch {
            // 获取作业类型字典列表
            val typeRsp = ApiRequest.getDictData(mutableMapOf("pageNo" to 1, "pageSize" to -1, "dictType" to "work_type"))
                .getOrElse { it.getResponse() }
            if (!typeRsp.code.isCodeOk()) {
                delay(1000)
                loading.emit(StateLoading())
                toast.emit(typeRsp.msg)
                return@launch
            }
            // 处理作业类型
            val dictList = typeRsp.data?.list ?: emptyList()
            val typeName = dictList.find { dict -> dict.value == job.type }?.label ?: ""
            var nodeId = -1
            // 找到当前执行中的任务
            val currentNodeName = if (job.status == "unreleased") {
                "待作业发布"
            } else {
                val node = job.workflowWorkNodeDOList?.find { it.approvalStatus == "running" }
                nodeId = node?.id ?: -1
                node?.nodeName ?: "--"
            }
            // 寻找下一个待执行的作业
            val connections = job.toUIConnectList()
            var nextNodeName = ""
            connections.forEach {
                if (it.fromId == nodeId.toString()) {
                    // 在这里查找toId，并且是还没有执行过的pending
                    job.workflowWorkNodeDOList?.find { node -> node.id == it.toId.toInt() && node.approvalStatus == "pending" }?.let { node ->
                        nextNodeName = node.nodeName
                        return@forEach
                    }
                } else if (it.toId == nodeId.toString()) {
                    // 在这里查找toId，并且是还没有执行过的pending
                    job.workflowWorkNodeDOList?.find { node -> node.id == it.fromId.toInt() && node.approvalStatus == "pending" }?.let { node ->
                        nextNodeName = node.nodeName
                        return@forEach
                    }
                }
            }
            // 更新数据源
            _state.value = _state.value.copy(job = job.copy(typeName = typeName), currentNodeName = currentNodeName, nextNodeName = nextNodeName)
            delay(500)
            loading.emit(StateLoading())
        }
    }

    /**
     * 初始化事件
     */
    private fun initEvent() {
        viewModelScope.async {
            RefreshEventBus.events.collect { event ->
                when (event) {
                    is RefreshEvent.JobDetail -> getData()
                    else -> {}
                }
            }
        }
    }


}

data class StateDetailJob(val job: Job = Job(), val currentNodeName: String = "", val nextNodeName: String = "")