<template>
  <div class="flow-timeline">
    <!-- 线性展示：所有审批节点按流程拓扑顺序依次排列（分支节点同样顺序展示） -->
    <div v-for="node in linearNodes" :key="node.id" class="flow-main-row">
      <NodeCard
        :node="node"
        :is-expanded="isNodeExpanded(node.id)"
        @toggle-node="toggleNodeExpand"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { computed, ref, watch } from 'vue'
import { buildFlowLayout, type FlowLayoutNode } from '@/utils/flowLayout'
import type { ProcessProgress } from '@/types/flow'
import NodeCard from './NodeCard.vue'

const props = defineProps<{
  progress: ProcessProgress | null
}>()

// 用布局算法解析状态，但输出"线性平铺"的节点列表（分支节点按顺序列出，不分组展示）
const linearNodes = computed<FlowLayoutNode[]>(() => {
  const def = props.progress?.definition
  if (!def?.flowJson) return []
  try {
    const model = JSON.parse(def.flowJson)
    const rows = buildFlowLayout(
      model.nodes || [],
      model.edges || [],
      props.progress?.nodes || [],
      props.progress?.records || [],
      props.progress?.instance?.currentNode
    )
    const nodes: FlowLayoutNode[] = []
    for (const row of rows) {
      if (row.kind === 'start' || row.kind === 'end') continue // 线性视图不展示起止标记
      if (row.kind === 'branch') {
        // 分支行：按分支顺序平铺其中的节点
        for (const br of row.branches || []) nodes.push(...br.nodes)
      } else {
        nodes.push(...(row.nodes || []))
      }
    }
    return nodes
  } catch {
    return []
  }
})

// 展开/收起（子节点）
const expandedSet = ref<Set<string>>(new Set())
function isNodeExpanded(id: string): boolean {
  return expandedSet.value.has(id)
}
function toggleNodeExpand(id: string) {
  const next = new Set(expandedSet.value)
  if (next.has(id)) next.delete(id)
  else next.add(id)
  expandedSet.value = next
}

// 数据变化后自动展开"进行中"的节点及子节点
watch(
  () => props.progress,
  () => {
    if (!props.progress?.nodes) return
    const next = new Set<string>()
    for (const node of props.progress.nodes) {
      if (node.subNodes?.length) {
        const hasCurrent = node.status === 'current' || node.subNodes.some((s) => s.status === 'current')
        if (hasCurrent) next.add(node.nodeId)
      }
    }
    expandedSet.value = next
    setTimeout(() => {
      document
        .querySelectorAll('.flow-timeline .sub-node-item.current-sub-node')
        .forEach((el) => el.scrollIntoView({ behavior: 'smooth', block: 'center' }))
    }, 60)
  },
  { immediate: true }
)
</script>

<style scoped>
.flow-timeline {
  position: relative;
  padding-left: 18px;
}
.flow-timeline::before {
  content: '';
  position: absolute;
  left: 7px;
  top: 8px;
  bottom: 8px;
  width: 2px;
  background: #e4e7ed;
}

/* 线性主流程行 */
.flow-main-row {
  position: relative;
  padding: 4px 0;
  z-index: 1;
}
</style>
