import type { NodeTypeDef, WorkflowDefinition } from '@/types/workflow'
import { assignCarParams } from '@/workflow/assignCarParams'
import { notifyParams } from '@/workflow/notifyParams'
import { waitEventParams } from '@/workflow/waitEventParams'
import { deviceControlParams } from '@/workflow/protocolParams'
import { executeActionParams } from '@/workflow/vda5050ActionParams'

/** 控件库分组顺序（左侧 palette 展示顺序） */
export const CATEGORY_ORDER = ['流程入口', '调度动作', '流程逻辑', '事件与信号', '协议控制'] as const

export type NodeCategory = (typeof CATEGORY_ORDER)[number]

export const NODE_CATALOG: NodeTypeDef[] = [
  // ── 流程入口 ──
  {
    type: 'start',
    label: '开始',
    category: '流程入口',
    color: '#67c23a',
    description: '流程起点',
    singleton: true,
    params: []
  },
  {
    type: 'end',
    label: '结束',
    category: '流程入口',
    color: '#909399',
    description: '流程终点',
    params: []
  },

  // ── 调度动作 ──
  {
    type: 'gotoSite',
    label: '前往站点',
    category: '调度动作',
    color: '#e6a23c',
    description: 'AGV 移动到目标站点',
    params: [
      { key: 'siteId', label: '目标站点', type: 'string', required: true, placeholder: '如 S001' }
    ]
  },
  {
    type: 'executeAction',
    label: '执行动作',
    category: '调度动作',
    color: '#e6a23c',
    description: '下发 VDA5050 单条动作指令',
    params: executeActionParams()
  },
  {
    type: 'assignCar',
    label: '分配车辆',
    category: '调度动作',
    color: '#e6a23c',
    description: '为任务指定车辆或车型',
    params: assignCarParams()
  },

  // ── 流程逻辑 ──
  {
    type: 'branch',
    label: '条件分支',
    category: '流程逻辑',
    color: '#9b59b6',
    description: '条件成立与否走不同分支',
    params: [
      { key: 'expression', label: '条件表达式', type: 'textarea', required: true, placeholder: '如 batterySoc > 0.2' }
    ]
  },
  {
    type: 'delay',
    label: '延时事件',
    category: '流程逻辑',
    color: '#9b59b6',
    description: '等待指定秒数后继续',
    params: [
      { key: 'seconds', label: '延时(秒)', type: 'number', required: true, defaultValue: 5 }
    ]
  },

  // ── 事件与信号 ──
  {
    type: 'waitEvent',
    label: '等待事件',
    category: '事件与信号',
    color: '#409eff',
    description: '等待事件触发，超时走另一路',
    params: waitEventParams()
  },
  {
    type: 'notify',
    label: '通知事件',
    category: '事件与信号',
    color: '#409eff',
    description: '调用接口推送 JSON 通知',
    params: notifyParams()
  },

  // ── 协议控制 ──
  {
    type: 'deviceControl',
    label: '设备控制',
    category: '协议控制',
    color: '#13c2c2',
    description: 'Modbus 读等待或写输出',
    params: deviceControlParams()
  }
]

export const NODE_CATALOG_MAP = new Map(NODE_CATALOG.map((n) => [n.type, n]))

export function defaultParamsForType(type: string): Record<string, unknown> {
  const def = NODE_CATALOG_MAP.get(type)
  if (!def) return {}
  const params: Record<string, unknown> = {}
  for (const f of def.params) {
    if (f.defaultValue !== undefined) params[f.key] = f.defaultValue
    else if (f.type === 'boolean') params[f.key] = false
    else if (f.type === 'number') params[f.key] = 0
    else params[f.key] = ''
  }
  return params
}

/** 静态演示用示例流程 */
export const DEMO_WORKFLOW: WorkflowDefinition = {
  id: 'wf-demo-001',
  name: 'A区送料示例',
  version: 1,
  viewport: { x: 0, y: 0, zoom: 1 },
  nodes: [
    { id: 'n1', type: 'start', label: '开始', position: { x: 60, y: 200 }, params: {} },
    { id: 'n2', type: 'assignCar', label: '分配车辆', position: { x: 240, y: 180 }, params: { strategy: 'carId', carId: 'C01' } },
    { id: 'n3', type: 'gotoSite', label: '前往入库点', position: { x: 460, y: 180 }, params: { siteId: 'S001' } },
    {
      id: 'n4',
      type: 'executeAction',
      label: '取货',
      position: { x: 680, y: 180 },
      params: {
        actionType: 'fetch',
        actionParameters: '[{"key":"loadType","value":"pallet"}]'
      }
    },
    { id: 'n5', type: 'waitEvent', label: '等待到达', position: { x: 900, y: 180 }, params: { eventName: 'site.arrived', timeoutSec: 120 } },
    {
      id: 'n6',
      type: 'notify',
      label: '送料完成通知',
      position: { x: 1120, y: 180 },
      params: {
        apiUrl: 'http://127.0.0.1:8080/api/hook/notify',
        dataConfig: '{"event":"delivery.complete","message":"送料完成"}',
        message: '送料完成',
        level: 'info'
      }
    },
    { id: 'n7', type: 'end', label: '结束', position: { x: 1340, y: 200 }, params: {} },
    {
      id: 'n8',
      type: 'notify',
      label: '等待超时告警',
      position: { x: 1120, y: 320 },
      params: {
        apiUrl: 'http://127.0.0.1:8080/api/hook/notify',
        dataConfig: '{"event":"wait.timeout","message":"等待到达超时"}',
        message: '等待到达超时',
        level: 'warn'
      }
    }
  ],
  edges: [
    { id: 'e1', source: 'n1', target: 'n2' },
    { id: 'e2', source: 'n2', target: 'n3' },
    { id: 'e3', source: 'n3', target: 'n4' },
    { id: 'e4', source: 'n4', target: 'n5' },
    { id: 'e5', source: 'n5', target: 'n6', sourceHandle: 'triggered', label: '正常执行' },
    { id: 'e5t', source: 'n5', target: 'n8', sourceHandle: 'timeout', label: '超时执行' },
    { id: 'e6', source: 'n6', target: 'n7' },
    { id: 'e8', source: 'n8', target: 'n7' }
  ]
}
