package com.iscs.bozzys.api

import androidx.compose.runtime.snapshots.SnapshotStateMap
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Color
import com.iscs.bozzys.ui.pages.edit.step.compose.Anchor
import com.iscs.bozzys.ui.pages.edit.step.compose.Connection
import com.iscs.bozzys.ui.pages.edit.step.compose.NodeUI
import kotlinx.serialization.Serializable
import kotlinx.serialization.json.Json

/**
 * 作业基类信息
 */
@Serializable
data class Job(
    val id: Int = -1,                        // 作业Id
    val orderNo: String = "",                // 作业编号
    val name: String = "",                   // 作业名称
    val type: String = "",                   // 作业类型
    val typeName: String = "",               // 作业类型名称，服务端不返回，本地使用
    val urgencyLevel: String = "",           // 紧急等级
    val designId: Int = -1,                  // sopId
    val designName: String = "",             // 设计模板
    val designContent: String? = null,       // sopInfo
    val description: String = "",            // 描述
    val initiatorId: Int = -1,               // 创建者id
    val initiatorName: String = "",          // 创建者名称
    val initiatorTime: Long = -1L,           // 创建者创建时间
    val status: String = "",                 // 作业状态
    val createTime: Long = -1L,              // 创建时间
    val currentNodeId: String? = null,
    val currentNodeName: String? = null,
    val completionTime: Long? = null,
    val cancellationTime: Long? = null,
    val cancellationReason: String? = null,
    val workflowWorkNodeDOList: List<Node>? = null
) : java.io.Serializable {
    /**
     * 将接口返回的node转换为可显示的Node
     */
    fun toUINodeMap(): SnapshotStateMap<String, NodeUI> {
        val json = Json { ignoreUnknownKeys = true }
        val map = SnapshotStateMap<String, NodeUI>()
        workflowWorkNodeDOList?.forEach {
            val pos = json.decodeFromString<NodePositon>(it.position)
            map[it.id.toString()] = NodeUI(it.id.toString(), Offset(pos.x, pos.y), node = it)
        }
        return map
    }

    fun String.toAnchor(): Anchor {
        return when (this) {
            "left-source" -> Anchor.LEFT
            "right-source" -> Anchor.RIGHT
            "top-source" -> Anchor.TOP
            "bottom-source" -> Anchor.BOTTOM
            "left-target" -> Anchor.LEFT
            "right-target" -> Anchor.RIGHT
            "top-target" -> Anchor.TOP
            "bottom-target" -> Anchor.BOTTOM
            else -> if (this.contains("source")) Anchor.LEFT else Anchor.RIGHT
        }
    }

    /**
     * 将api连线数据转化为UI层连线数据
     */
    fun toUIConnectList(): List<Connection> {
        val connections = ArrayList<Connection>()
        val json = Json { ignoreUnknownKeys = true }
        val nodeInfo: NodeInfo = json.decodeFromString(designContent?.ifEmpty { "{}" } ?: "{}")
        nodeInfo.edges.forEach {
            val fromUuid = it.target
            val toUuid = it.source
            val fromId = workflowWorkNodeDOList?.find { node -> node.uuid == fromUuid }?.id ?: 0
            val fromAnchor = it.targetHandle.toAnchor()
            val toId = workflowWorkNodeDOList?.find { node -> node.uuid == toUuid }?.id ?: 0
            val toAnchor = it.sourceHandle.toAnchor()
            connections.add(Connection(fromId.toString(), toId.toString(), fromAnchor, toAnchor))
        }
        return connections
    }

    /**
     * 获取等级名称和背景色
     */
    fun getLevelNameAndColor(): Pair<String, Color> {
        return when (urgencyLevel) {
            "1" -> "紧急" to Color(0xFFFF9800)
            "2" -> "非常紧急" to Color(0xFFFF4500)
            else -> "正常" to Color(0xFF1E90FF)
        }
    }

    /**
     * 获取任务状态名称
     */
    fun getJobStatusName(): String {
        return when (status) {
            "unreleased" -> "待发布"
            "approved" -> "已审核"
            "running" -> "进行中"
            "completed" -> "已完成"
            else -> status
        }
    }
}