Dashboard.vue 35.3 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010
<script lang="ts" setup>
/**
 * 设备监控界面
 * @author zzy
 * @date 2026-01-05
 */
import { ref, onMounted, onBeforeUnmount, computed, watch } from 'vue'
import { useI18n } from 'vue-i18n'
import { useToast } from 'vuestic-ui'
import mapsApi from '../../../services/maps'
import robotTasksApi from '../../../services/robotTasks'
import { robotStatusWs, type RobotStatus, type StorageLocation } from '../../../services/robotStatusWs'
import RobotStatusCard from './cards/RobotStatusCard.vue'

const { t } = useI18n()
const { init: notify } = useToast()

// 地图列表
const mapList = ref<any[]>([])
const selectedMapId = ref<string | null>(null)
const isLoading = ref(false)

// 机器人状态列表
const robotList = ref<RobotStatus[]>([])
let unsubscribeWs: (() => void) | null = null
let unsubscribeLocationWs: (() => void) | null = null

// 当前地图数据
const currentMap = ref({
  id: null as string | null,
  name: '',
  code: '',
  type: 1,
  nodes: [] as any[],
  edges: [] as any[]
})

// 画布相关
const NODE_DIAMETER = 256
const NODE_RADIUS = NODE_DIAMETER / 2
const MIN_SCALE = 0.005
const svgRef = ref<HTMLElement | null>(null)
const canvasSize = ref({ width: 0, height: 0 })
const viewport = ref({ x: 0, y: 0, scale: 0.1 })
let resizeObserver: ResizeObserver | null = null
let isPanning = false
let panStart = { x: 0, y: 0 }
let viewportStart = { x: 0, y: 0 }

// 背景图
const bgImageUrl = ref('')
const bgImgSize = ref({ width: 0, height: 0 })
const bgScale = ref(1)
const bgOpacity = ref(0.6)
const bgRotation = ref(0)
const bgOffsetX = ref(0)
const bgOffsetY = ref(0)
const bgWorldWidth = computed(() => Math.max(0, Math.round((bgImgSize.value.width || 0) * (bgScale.value || 0))))
const bgWorldHeight = computed(() => Math.max(0, Math.round((bgImgSize.value.height || 0) * (bgScale.value || 0))))

// 节点和边
const nodes = computed(() => currentMap.value.nodes || [])
const edges = computed(() => currentMap.value.edges || [])

// 选中的节点(支持多选,最多2个)
const selectedNodeIds = ref<string[]>([])

// 任务起点和终点(显示code,存储id)
const startNodeCode = ref('')
const endNodeCode = ref('')
const startNodeId = ref('')
const endNodeId = ref('')

// 监听选中节点变化,自动填充起点终点
watch(selectedNodeIds, (ids) => {
  const node1 = ids.length >= 1 ? nodes.value.find((n: any) => n.id === ids[0]) : null
  const node2 = ids.length >= 2 ? nodes.value.find((n: any) => n.id === ids[1]) : null
  console.log(node1,node2)
  startNodeCode.value = node1?.storageLocations[0].locationName || ''
  startNodeId.value = node1?.storageLocations[0].locationId || ''
  endNodeCode.value = node2?.storageLocations[0].locationName || ''
endNodeId.value = node2?.storageLocations[0].locationId || ''
}, { deep: true })

// 执行任务
const executeTask = async () => {
  if (!startNodeId.value || !endNodeId.value) {
    notify({ message: t('dashboard.taskValidation') || '请输入起点和终点', color: 'warning' })
    return
  }
  try {
    isLoading.value = true
    const payload = {
      beginLocationId: startNodeId.value,
      endLocationId: endNodeId.value,
    }
    const res = await robotTasksApi.createOrUpdate(payload)
    if (res?.success === false || res?.Success === false) {
      notify({ message: res.message || res.Message || t('dashboard.taskFailed'), color: 'danger' })
    } else {
      notify({ message: res?.message || res?.Message || t('dashboard.taskCreated'), color: 'success' })
      startNodeCode.value = ''
      endNodeCode.value = ''
      startNodeId.value = ''
      endNodeId.value = ''
    }
  } catch (err: any) {
    notify({ message: err?.message || t('dashboard.taskFailed'), color: 'danger' })
  } finally {
    isLoading.value = false
  }
}

// 判断节点是否在当前视口可见范围内
const isNodeInViewport = (node: any, width: number, height: number) => {
  const screenX = viewport.value.x + node.x * viewport.value.scale
  const screenY = viewport.value.y - node.y * viewport.value.scale
  const margin = NODE_RADIUS * viewport.value.scale
  return screenX >= -margin && screenX <= width + margin && screenY >= -margin && screenY <= height + margin
}

// 平滑动画到目标视图
let animationId: number | null = null
const animateToShowSelectedNodes = () => {
  if (selectedNodeIds.value.length < 2) return

  // 直接从 SVG 获取尺寸
  const svg = svgRef.value
  if (!svg) return
  const rect = svg.getBoundingClientRect()
  const width = rect.width
  const height = rect.height
  if (!width || !height) return

  const node1 = nodes.value.find((n: any) => n.id === selectedNodeIds.value[0])
  const node2 = nodes.value.find((n: any) => n.id === selectedNodeIds.value[1])
  if (!node1 || !node2) return

  // 如果两个节点都在当前视口内,不进行缩放移动
  if (isNodeInViewport(node1, width, height) && isNodeInViewport(node2, width, height)) return

  // 计算两节点的边界
  const pad = 500
  const xMin = Math.min(node1.x, node2.x) - pad
  const xMax = Math.max(node1.x, node2.x) + pad
  const yMin = Math.min(node1.y, node2.y) - pad
  const yMax = Math.max(node1.y, node2.y) + pad

  // 计算目标缩放和位置
  const worldW = xMax - xMin || 100
  const worldH = yMax - yMin || 100
  const scaleX = width / worldW
  const scaleY = height / worldH
  const targetScale = Math.max(MIN_SCALE, Math.min(scaleX, scaleY) * 0.8)
  const centerX = (xMin + xMax) / 2
  const centerY = (yMin + yMax) / 2
  const targetX = width / 2 - centerX * targetScale
  const targetY = height / 2 + centerY * targetScale

  // 取消之前的动画
  if (animationId) cancelAnimationFrame(animationId)

  // 平滑动画
  const startX = viewport.value.x
  const startY = viewport.value.y
  const startScale = viewport.value.scale
  const duration = 400
  const startTime = performance.now()

  const easeOutCubic = (t: number) => 1 - Math.pow(1 - t, 3)

  const animate = (now: number) => {
    const elapsed = now - startTime
    const progress = Math.min(elapsed / duration, 1)
    const eased = easeOutCubic(progress)

    viewport.value.x = startX + (targetX - startX) * eased
    viewport.value.y = startY + (targetY - startY) * eased
    viewport.value.scale = startScale + (targetScale - startScale) * eased

    if (progress < 1) {
      animationId = requestAnimationFrame(animate)
    } else {
      animationId = null
    }
  }

  animationId = requestAnimationFrame(animate)
}

// 节点点击事件(支持多选,最多2个)
const onNodeClick = (node: any, e: MouseEvent) => {
  e.stopPropagation()
  const idx = selectedNodeIds.value.indexOf(node.id)
  if (idx >= 0) {
    selectedNodeIds.value.splice(idx, 1)
  } else if (selectedNodeIds.value.length < 2) {
    selectedNodeIds.value.push(node.id)
    if (selectedNodeIds.value.length === 2) {
      setTimeout(() => animateToShowSelectedNodes(), 50)
    }
  } else {
    selectedNodeIds.value[1] = node.id
    setTimeout(() => animateToShowSelectedNodes(), 50)
  }
}

// 判断节点是否选中
const isNodeSelected = (id: string) => selectedNodeIds.value.includes(id)

// 选中节点的颜色(起点绿色,终点红色)
const getSelectedNodeColor = (id: string) => {
  const idx = selectedNodeIds.value.indexOf(id)
  return idx === 0 ? '#28a745' : idx === 1 ? '#dc3545' : '#0d6efd'
}

// 指引线路径(选中两个节点时显示)
const guideLine = computed(() => {
  if (selectedNodeIds.value.length < 2) return null
  const node1 = nodes.value.find((n: any) => n.id === selectedNodeIds.value[0])
  const node2 = nodes.value.find((n: any) => n.id === selectedNodeIds.value[1])
  if (!node1 || !node2) return null
  return { x1: node1.x, y1: -node1.y, x2: node2.x, y2: -node2.y }
})

// 世界边界
const worldBounds = computed(() => {
  const ns = nodes.value
  if (!ns.length) return { xMin: -50, xMax: 50, yMin: -50, yMax: 50 }
  let xMin = Infinity, xMax = -Infinity, yMin = Infinity, yMax = -Infinity
  ns.forEach((n: any) => {
    if (n.x < xMin) xMin = n.x
    if (n.x > xMax) xMax = n.x
    if (n.y < yMin) yMin = n.y
    if (n.y > yMax) yMax = n.y
  })
  const pad = 20
  return { xMin: xMin - pad, xMax: xMax + pad, yMin: yMin - pad, yMax: yMax + pad }
})

// 加载地图列表
const loadMapList = async () => {
  try {
    const params = { pageNumber: 1, pageSize: 100, filterModel: JSON.stringify({ active: { filterType: 'text', type: 'equals', filter: 'true' } }) }
    const res = await mapsApi.list(params)
    const data = (res && (res.Data ?? res.data)) || []
    mapList.value = Array.isArray(data) ? data.filter((m: any) => m.active) : []
    // 默认选择第一个地图
    if (mapList.value.length > 0 && !selectedMapId.value) {
      selectedMapId.value = mapList.value[0].mapId
    }
  } catch (err: any) {
    notify({ message: err?.message || t('dashboard.loadMapListFailed'), color: 'danger' })
  }
}

// 加载地图详情
const loadMapData = async (mapId: string) => {
  if (!mapId) return
  isLoading.value = true
  try {
    const res = await mapsApi.getDetails(mapId)
    const data = (res && (res.Data ?? res.data)) || res || {}

    currentMap.value.id = String(data.mapId ?? data.id ?? mapId)
    currentMap.value.name = data.mapName ?? data.name ?? ''
    currentMap.value.code = data.mapCode ?? data.code ?? ''
    currentMap.value.type = data.mapType ?? data.type ?? 1

    // 处理节点
    const nodesData = data.mapNodes ?? data.nodes ?? []
    const nodeIdToCodeMap = new Map()
    currentMap.value.nodes = nodesData.map((node: any) => {
      const nodeId = String(node.nodeId ?? node.id)
      const nodeCode = node.nodeCode ?? node.code ?? node.label ?? `N${nodeId}`
      nodeIdToCodeMap.set(nodeId, nodeCode)
      return {
        id: nodeId,
        x: node.x,
        y: node.y,
        code: nodeCode,
        name: node.nodeName ?? node.name ?? '',
        type: node.type,
        storageLocations: node.storageLocations ?? []
      }
    })

    // 处理边
    const edgesData = data.mapEdges ?? data.edges ?? []
    currentMap.value.edges = edgesData.map((edge: any) => {
      const sourceCode = edge.fromNode ? (nodeIdToCodeMap.get(String(edge.fromNode)) ?? edge.sourceCode ?? '') : (edge.sourceCode ?? '')
      const targetCode = edge.toNode ? (nodeIdToCodeMap.get(String(edge.toNode)) ?? edge.targetCode ?? '') : (edge.targetCode ?? '')
      return {
        id: String(edge.edgeId ?? edge.id),
        sourceCode,
        targetCode,
        isReverse: edge.regress ?? edge.isReverse ?? false,
        curve: edge.isCurve ?? edge.curve ?? false,
        radius: edge.radius,
        centerX: edge.centerX,
        centerY: edge.centerY
      }
    })

    // 加载背景图(不添加时间戳,利用浏览器缓存)
    try {
      const fileRes = await mapsApi.getMapFile(mapId)
      const fileData = (fileRes && (fileRes.Data ?? fileRes.data)) || null
      if (fileData && fileData.fileUrl) {
        bgOpacity.value = fileData.opacity ?? 1
        bgRotation.value = fileData.rotation ?? 0
        bgOffsetX.value = fileData.offsetX ?? 0
        bgOffsetY.value = fileData.offsetY ?? 0
        const dbScale = fileData.scale ?? 0

        // 先预加载图片,完成后再设置URL,避免重复请求
        const img = new Image()
        img.crossOrigin = 'anonymous'
        img.onload = () => {
          bgImgSize.value = { width: img.naturalWidth, height: img.naturalHeight }
          bgScale.value = dbScale > 0 && dbScale < 1
            ? Math.max(0.01, 800 / img.naturalWidth)
            : (dbScale || Math.max(0.01, 800 / img.naturalWidth))
          bgImageUrl.value = fileData.fileUrl
          setTimeout(() => resetView(), 50)
        }
        img.src = fileData.fileUrl
      } else {
        bgImageUrl.value = ''
        // 无背景图时直接重置视图
        setTimeout(() => resetView(), 100)
      }
    } catch {
      bgImageUrl.value = ''
      setTimeout(() => resetView(), 100)
    }
  } catch (err: any) {
    notify({ message: err?.message || t('dashboard.loadMapDetailFailed'), color: 'danger' })
  } finally {
    isLoading.value = false
  }
}

// 监听地图选择变化
watch(selectedMapId, (newId) => {
  if (newId) {
    // 清空旧地图的机器人数据和选中状态
    robotList.value = []
    selectedNodeIds.value = []
    loadMapData(newId)
    // 重新订阅新地图的机器人状态
    robotStatusWs.connect(newId)
  }
})

// 获取节点坐标
const getNodeByCode = (code: string) => nodes.value.find((n: any) => n.code === code)

// 边路径(中点在2/3处,与MapEditor一致)
const getEdgePath = (edge: any) => {
  const s = getNodeByCode(edge.sourceCode)
  const t = getNodeByCode(edge.targetCode)
  if (!s || !t) return ''
  const dx = t.x - s.x
  const dy = t.y - s.y
  const xm = s.x + (2 / 3) * dx
  const ym = s.y + (2 / 3) * dy
  return `M ${s.x},${-s.y} L ${xm},${-ym} L ${t.x},${-t.y}`
}

// 弧线路径(与MapEditor一致)
const getArcPath = (arc: any) => {
  if (!arc || !arc.radius || arc.centerX == null || arc.centerY == null) return ''

  // 获取起点和终点坐标
  let startX: number, startY: number, endX: number, endY: number
  if (arc.startX != null && arc.startY != null && arc.endX != null && arc.endY != null) {
    startX = arc.startX
    startY = arc.startY
    endX = arc.endX
    endY = arc.endY
  } else {
    const src = getNodeByCode(arc.sourceCode)
    const tgt = getNodeByCode(arc.targetCode)
    if (!src || !tgt) return ''
    startX = src.x
    startY = src.y
    endX = tgt.x
    endY = tgt.y
  }

  const toRad = (deg: number) => deg * (Math.PI / 180)
  const toDeg = (rad: number) => rad * (180 / Math.PI)
  const normDeg = (a: number) => { let x = a % 360; if (x < 0) x += 360; return x }
  const normDelta = (a0: number, a1: number) => {
    const raw = a1 - a0
    let d = ((raw % 360) + 360) % 360
    if (d > 180) d -= 360
    return d
  }

  const startAngle = normDeg(toDeg(Math.atan2(-(startY - arc.centerY), startX - arc.centerX)))
  const endAngle = normDeg(toDeg(Math.atan2(-(endY - arc.centerY), endX - arc.centerX)))
  const delta = normDelta(startAngle, endAngle)
  const sweepFlag = delta > 0 ? 1 : 0
  const midAngle = startAngle + delta * (2 / 3)
  const rx = arc.radius
  const ry = arc.radius

  const x1 = startX
  const y1s = -startY
  const xm = arc.centerX + rx * Math.cos(toRad(midAngle))
  const ym = arc.centerY - ry * Math.sin(toRad(midAngle))
  const xms = xm
  const yms = -ym
  const x2 = endX
  const y2s = -endY
  const largeArcFlag = 0

  return `M ${x1},${y1s} A ${rx},${ry} 0 ${largeArcFlag},${sweepFlag} ${xms},${yms} A ${rx},${ry} 0 ${largeArcFlag},${sweepFlag} ${x2},${y2s}`
}

/**
 * 获取储位状态
 * @param node 节点对象
 * @returns 状态值:0=空闲,1=占用,2=预占用,3=禁用
 * @author zzy
 */
const getStorageStatus = (node: any) => {
  if (!node?.storageLocations?.length) return 0
  return node.storageLocations[0].status ?? 0
}

// 节点填充色(与MapEditor一致)
const getNodeFill = (node: any) => {
  if (!node || !node.type) return '#ffffff'
  if (node.type === 1) return '#74c0fc'  // 高速点
  if (node.type === 4) return '#0d47a1'  // 停车位
  return node.type === 2 ? '#ffb020' : '#ffffff'  // 储位
}

// 节点描边色(与MapEditor一致)
const getNodeStroke = (node: any) => {
  if (!node) return '#6c757d'
  if (!node.type) return '#6c757d'
  if (node.type === 3) return '#28a745'  // 充电点
  if (node.type === 2) return '#d9480f'  // 储位
  if (node.type === 4) return '#0d47a1'  // 停车位
  return '#6c757d'
}

// 画布事件
let hasDragged = false
const onCanvasMouseDown = (e: MouseEvent) => {
  isPanning = true
  hasDragged = false
  panStart = { x: e.clientX, y: e.clientY }
  viewportStart = { x: viewport.value.x, y: viewport.value.y }
}

const onCanvasMouseMove = (e: MouseEvent) => {
  if (!isPanning) return
  const dx = e.clientX - panStart.x
  const dy = e.clientY - panStart.y
  if (Math.abs(dx) > 3 || Math.abs(dy) > 3) hasDragged = true
  viewport.value.x = viewportStart.x + dx
  viewport.value.y = viewportStart.y + dy
}

const onCanvasMouseUp = () => {
  if (isPanning && !hasDragged) {
    selectedNodeIds.value = []
  }
  isPanning = false
}

const onCanvasWheel = (e: WheelEvent) => {
  const rect = (e.currentTarget as HTMLElement).getBoundingClientRect()
  const mx = e.clientX - rect.left
  const my = e.clientY - rect.top
  const factor = e.deltaY < 0 ? 1.1 : 0.9
  const newScale = Math.max(MIN_SCALE, viewport.value.scale * factor)
  const wx = (mx - viewport.value.x) / viewport.value.scale
  const wy = (my - viewport.value.y) / viewport.value.scale
  viewport.value.scale = newScale
  viewport.value.x = mx - wx * newScale
  viewport.value.y = my - wy * newScale
}

const resetView = () => {
  if (!canvasSize.value.width || !canvasSize.value.height) return
  const { xMin, xMax, yMin, yMax } = worldBounds.value
  // 合并节点边界和背景图边界
  const bgXMin = bgOffsetX.value
  const bgXMax = bgOffsetX.value + bgWorldWidth.value
  const bgYMin = bgOffsetY.value
  const bgYMax = bgOffsetY.value + bgWorldHeight.value
  const hasBg = bgImageUrl.value && bgWorldWidth.value > 0
  const finalXMin = hasBg ? Math.min(xMin, bgXMin) : xMin
  const finalXMax = hasBg ? Math.max(xMax, bgXMax) : xMax
  const finalYMin = hasBg ? Math.min(yMin, bgYMin) : yMin
  const finalYMax = hasBg ? Math.max(yMax, bgYMax) : yMax
  const worldW = finalXMax - finalXMin || 100
  const worldH = finalYMax - finalYMin || 100
  const scaleX = canvasSize.value.width / worldW
  const scaleY = canvasSize.value.height / worldH
  const scale = Math.min(scaleX, scaleY) * 0.9
  const centerX = (finalXMin + finalXMax) / 2
  const centerY = (finalYMin + finalYMax) / 2
  viewport.value.scale = Math.max(MIN_SCALE, scale)
  viewport.value.x = canvasSize.value.width / 2 - centerX * viewport.value.scale
  viewport.value.y = canvasSize.value.height / 2 + centerY * viewport.value.scale
}

const zoomIn = () => {
  viewport.value.scale = Math.min(10, viewport.value.scale * 1.2)
}

const zoomOut = () => {
  viewport.value.scale = Math.max(MIN_SCALE, viewport.value.scale / 1.2)
}

onMounted(async () => {
  await loadMapList()

  // 订阅机器人状态更新
  unsubscribeWs = robotStatusWs.onStatusUpdate((robots) => {
    robotList.value = robots
  })

  // 订阅库位状态更新
  unsubscribeLocationWs = robotStatusWs.onLocationUpdate((locations: StorageLocation[]) => {
    // 按 mapNodeId 更新节点的 storageLocations
    const nodeMap = new Map<string, StorageLocation[]>()
    locations.forEach((loc) => {
      if (loc.mapNodeId) {
        if (!nodeMap.has(loc.mapNodeId)) nodeMap.set(loc.mapNodeId, [])
        nodeMap.get(loc.mapNodeId)!.push(loc)
      }
    })
    currentMap.value.nodes.forEach((node: any) => {
      node.storageLocations = nodeMap.get(node.id) || []
    })
  })

  // 监听画布大小
  if (svgRef.value) {
    const parent = svgRef.value.parentElement
    if (parent) {
      resizeObserver = new ResizeObserver((entries) => {
        for (const entry of entries) {
          canvasSize.value = { width: entry.contentRect.width, height: entry.contentRect.height }
        }
      })
      resizeObserver.observe(parent)
      canvasSize.value = { width: parent.clientWidth, height: parent.clientHeight }
    }
  }
})

onBeforeUnmount(() => {
  if (resizeObserver) resizeObserver.disconnect()
  if (unsubscribeWs) unsubscribeWs()
  if (unsubscribeLocationWs) unsubscribeLocationWs()
  robotStatusWs.disconnect()
})
</script>

<template>
  <div class="device-monitor-wrapper">
    <div class="monitor-main">
      <VaCard class="device-monitor-card">
        <VaCardContent class="device-monitor-content">
        <!-- 顶部工具栏 -->
        <div class="toolbar-container">
          <div class="toolbar-left">
            <VaSelect
              v-model="selectedMapId"
              :options="mapList"
              :placeholder="t('dashboard.selectMap') || '请选择地图'"
              text-by="mapName"
              value-by="mapId"
              class="map-select"
              :loading="isLoading"
            />
            <div class="task-input-group">
              <VaInput
                v-model="startNodeCode"
                :placeholder="t('dashboard.startNode') || '起点'"
                class="node-input"
              />
              <span class="arrow-icon">→</span>
              <VaInput
                v-model="endNodeCode"
                :placeholder="t('dashboard.endNode') || '终点'"
                class="node-input"
              />
              <VaButton
                color="primary"
                @click="executeTask"
                icon="play_arrow"
                round
                :title="t('dashboard.executeTask') || '执行任务'"
                :loading="isLoading"
                class="execute-btn"
              />
            </div>
          </div>
          <div class="toolbar-right">
            <VaButtonGroup class="toolbar-group">
              <VaButton
                color="secondary"
                @click="zoomIn"
                icon="zoom_in"
                size="small"
                :title="t('dashboard.zoomIn')"
              />
              <VaButton
                color="secondary"
                @click="zoomOut"
                icon="zoom_out"
                size="small"
                :title="t('dashboard.zoomOut')"
              />
              <VaButton
                color="secondary"
                @click="resetView"
                icon="history"
                size="small"
                :title="t('dashboard.resetView')"
              />
            </VaButtonGroup>
            <span class="stats-text" v-if="currentMap.id">
              {{ t('dashboard.stats') || '节点' }}: {{ nodes.length }} | {{ t('dashboard.edges') || '边' }}: {{ edges.length }}
            </span>
          </div>
        </div>

        <!-- 地图画布 -->
        <div class="map-canvas-wrapper">
          <div
            v-if="currentMap.id"
            class="topo-canvas"
            @mousedown="onCanvasMouseDown"
            @mousemove="onCanvasMouseMove"
            @mouseup="onCanvasMouseUp"
            @mouseleave="onCanvasMouseUp"
            @wheel.prevent="onCanvasWheel"
          >
            <svg width="100%" height="100%" ref="svgRef">
              <defs>
                <marker id="arrow-black" viewBox="0 0 10 10" refX="10" refY="5" markerUnits="strokeWidth" markerWidth="10" markerHeight="6" orient="auto">
                  <path d="M 0 0 L 10 5 L 0 10 z" fill="#000000" />
                </marker>
                <marker id="arrow-red" viewBox="0 0 10 10" refX="10" refY="5" markerUnits="strokeWidth" markerWidth="10" markerHeight="6" orient="auto">
                  <path d="M 0 0 L 10 5 L 0 10 z" fill="#dc3545" />
                </marker>
                <marker id="arrow-guide" viewBox="0 0 10 10" refX="5" refY="5" markerUnits="strokeWidth" markerWidth="4" markerHeight="4" orient="auto">
                  <path d="M 0 0 L 10 5 L 0 10 z" fill="#ff6b35" />
                </marker>
                <!-- 潜伏车图标 -->
                <symbol id="latent-agv" viewBox="0 0 50 40">
                  <linearGradient id="agvGreen1" x1="0%" y1="0%" x2="100%" y2="0%">
                    <stop offset="0%" stop-color="#90EE90" stop-opacity="0.6"/>
                    <stop offset="100%" stop-color="#90EE90" stop-opacity="0.15"/>
                  </linearGradient>
                  <rect x="5" y="5" width="35" height="30" rx="5" fill="#aa2116"/>
                  <rect x="10" y="10" width="25" height="20" rx="3" fill="#1a1a1a"/>
                  <polygon points="40,12 40,28 48,32 48,8" fill="url(#agvGreen1)"/>
                </symbol>
                <!-- 叉车图标 -->
                <symbol id="forklift-agv" viewBox="-8 0 65 40">
                  <linearGradient id="agvGreen2" x1="0%" y1="0%" x2="100%" y2="0%">
                    <stop offset="0%" stop-color="#90EE90" stop-opacity="0.6"/>
                    <stop offset="100%" stop-color="#90EE90" stop-opacity="0.15"/>
                  </linearGradient>
                  <rect x="-6" y="11" width="35" height="6" rx="3" fill="#1a1a1a"/>
                  <rect x="-6" y="23" width="35" height="6" rx="3" fill="#1a1a1a"/>
                  <ellipse cx="0" cy="14" rx="4" ry="2" fill="#555"/>
                  <ellipse cx="0" cy="26" rx="4" ry="2" fill="#555"/>
                  <rect x="24" y="8" width="16" height="24" rx="4" fill="#aa2116"/>
                  <polygon points="40,12 40,28 50,32 50,8" fill="url(#agvGreen2)"/>
                </symbol>
              </defs>

              <g :transform="`translate(${viewport.x}, ${viewport.y}) scale(${viewport.scale})`">
                <!-- 背景图 -->
                <g v-if="bgImageUrl">
                  <g :transform="`translate(${bgWorldWidth / 2 + bgOffsetX}, ${-bgWorldHeight / 2 - bgOffsetY}) rotate(${bgRotation}) translate(${-bgWorldWidth / 2}, ${bgWorldHeight / 2})`">
                    <image
                      :href="bgImageUrl"
                      :x="0"
                      :y="-bgWorldHeight"
                      :width="bgWorldWidth"
                      :height="bgWorldHeight"
                      :opacity="bgOpacity"
                      preserveAspectRatio="none"
                      crossorigin="anonymous"
                    />
                  </g>
                </g>

                <!-- 网格(简化:只显示坐标轴) -->
                <g class="grid">
                  <line :x1="0" :y1="-worldBounds.yMin" :x2="0" :y2="-worldBounds.yMax" stroke="#adb5bd" :stroke-width="0.2 / viewport.scale" />
                  <line :x1="worldBounds.xMin" y1="0" :x2="worldBounds.xMax" y2="0" stroke="#adb5bd" :stroke-width="0.2 / viewport.scale" />
                </g>

                <!-- 边 -->
                <g class="edges">
                  <g v-for="edge in edges.filter((e: any) => !e.curve)" :key="edge.id">
                    <path
                      :d="getEdgePath(edge)"
                      fill="none"
                      :stroke="edge.isReverse ? '#dc3545' : '#000000'"
                      stroke-width="6"
                      :marker-mid="edge.isReverse ? 'url(#arrow-red)' : 'url(#arrow-black)'"
                    />
                  </g>
                </g>

                <!-- 弧线 -->
                <g class="arcs">
                  <g v-for="arc in edges.filter((e: any) => e.curve)" :key="arc.id">
                    <path
                      :d="getArcPath(arc)"
                      fill="none"
                      :stroke="arc.isReverse ? '#dc3545' : '#000000'"
                      stroke-width="6"
                      :marker-mid="arc.isReverse ? 'url(#arrow-red)' : 'url(#arrow-black)'"
                    />
                  </g>
                </g>

                <!-- 机器人路径线条(橙色) -->
                <g class="robot-paths">
                  <g v-for="robot in robotList" :key="'path-' + robot.robotId">
                    <polyline
                      v-if="robot.path && robot.path.length > 1"
                      :points="robot.path.map((p: number[]) => `${p[0]},${-p[1]}`).join(' ')"
                      fill="none"
                      stroke="#fdb933"
                      stroke-width="160"
                      stroke-linecap="round"
                      stroke-linejoin="round"
                    />
                  </g>
                </g>

                <!-- 节点 -->
                <g class="nodes">
                  <g v-for="node in nodes" :key="node.id" :transform="`translate(${node.x}, ${-node.y})`"
                     @mousedown.stop @click="onNodeClick(node, $event)" style="cursor: pointer">
                    <!-- 储位类型:1000x1000橙黄色方框 -->
                    <g v-if="node.type === 2">
                      <rect x="-500" y="-500" width="1000" height="1000" rx="50" ry="50"
                            :fill="isNodeSelected(node.id) ? '#7bbfea' : '#fcf16e'"
                            :stroke="isNodeSelected(node.id) ? getSelectedNodeColor(node.id) : '#fdb933'"
                            stroke-width="50" />
                      <!-- 库位状态图标:禁用=红叉,占用=绿色托盘,预占用=灰色托盘 -->
                      <g v-if="getStorageStatus(node) === 3" transform="translate(-450,-450)">
                        <line x1="100" y1="100" x2="800" y2="800" stroke="#dc3545" stroke-width="100" stroke-linecap="round"/>
                        <line x1="800" y1="100" x2="100" y2="800" stroke="#dc3545" stroke-width="100" stroke-linecap="round"/>
                      </g>
                      <g v-else-if="getStorageStatus(node) === 1 || getStorageStatus(node) === 2" transform="translate(-450,-450)">
                        <!-- 托盘俯视图:三横三纵木板结构 900x900 -->
                        <rect x="0" y="0" width="900" height="900" rx="30" :fill="getStorageStatus(node) === 1 ? '#8B4513' : '#9e9e9e'" opacity="0.3"/>
                        <!-- 横向木板 -->
                        <rect x="30" y="50" width="840" height="80" rx="10" :fill="getStorageStatus(node) === 1 ? '#A0522D' : '#757575'"/>
                        <rect x="30" y="410" width="840" height="80" rx="10" :fill="getStorageStatus(node) === 1 ? '#A0522D' : '#757575'"/>
                        <rect x="30" y="770" width="840" height="80" rx="10" :fill="getStorageStatus(node) === 1 ? '#A0522D' : '#757575'"/>
                        <!-- 纵向木板 -->
                        <rect x="50" y="30" width="80" height="840" rx="10" :fill="getStorageStatus(node) === 1 ? '#CD853F' : '#888'"/>
                        <rect x="410" y="30" width="80" height="840" rx="10" :fill="getStorageStatus(node) === 1 ? '#CD853F' : '#888'"/>
                        <rect x="770" y="30" width="80" height="840" rx="10" :fill="getStorageStatus(node) === 1 ? '#CD853F' : '#888'"/>
                      </g>
                      <text v-else x="0" y="0" text-anchor="middle" dominant-baseline="central" font-size="200"
                            :fill="isNodeSelected(node.id) ? getSelectedNodeColor(node.id) : '#d68910'">
                        {{ node.name || node.code }}
                      </text>
                    </g>
                    <!-- 非储位类型:圆形 -->
                    <g v-else>
                      <circle :r="NODE_RADIUS"
                              :fill="isNodeSelected(node.id) ? getSelectedNodeColor(node.id) : getNodeFill(node)"
                              :stroke="isNodeSelected(node.id) ? getSelectedNodeColor(node.id) : getNodeStroke(node)"
                              :stroke-width="isNodeSelected(node.id) ? 6 : 2" />
                      <text v-if="!isNodeSelected(node.id) && node.type === 3" x="0" y="0" text-anchor="middle" dominant-baseline="central" :font-size="NODE_RADIUS * 1.4" fill="#28a745">⚡</text>
                      <text v-if="!isNodeSelected(node.id) && node.type === 4" x="0" y="0" text-anchor="middle" dominant-baseline="central" :font-size="NODE_RADIUS * 1.4" fill="#ffffff">P</text>
                    </g>
                  </g>
                </g>

                <!-- 机器人图标 -->
                <g class="robots">
                  <template v-for="robot in robotList" :key="'robot-' + robot.robotId">
                    <g v-if="robot.x != null && robot.y != null"
                       :transform="`translate(${robot.x}, ${-robot.y!}) rotate(${-(robot.theta ?? 0)})`">
                      <use v-if="robot.robotType === 2" href="#forklift-agv" x="-341" y="-853" width="2773" height="1707" />
                      <use v-else href="#latent-agv" x="-1067" y="-853" width="2133" height="1707" />
                      <text x="0" y="1067" text-anchor="middle" font-size="400" fill="#333">{{ robot.robotCode }}</text>
                    </g>
                  </template>
                </g>

                <!-- 指引线(选中两个节点时显示) -->
                <g v-if="guideLine" class="guide-line">
                  <line
                    :x1="guideLine.x1"
                    :y1="guideLine.y1"
                    :x2="guideLine.x2"
                    :y2="guideLine.y2"
                    stroke="#ff6b35"
                    :stroke-width="4 / viewport.scale"
                    stroke-dasharray="20 10"
                    stroke-linecap="round"
                    marker-end="url(#arrow-guide)"
                  />
                </g>
              </g>
            </svg>
          </div>

          <!-- 未选择地图提示 -->
          <div v-else class="empty-state">
            <VaIcon name="map" size="64px" color="secondary" />
            <p>{{ t('dashboard.selectMapHint') || '请从上方下拉框选择要监控的地图' }}</p>
          </div>
        </div>
      </VaCardContent>
    </VaCard>
    </div>

    <!-- 右侧机器人状态面板 -->
    <div class="robot-panel">
      <VaCard class="robot-panel-card">
        <VaCardTitle class="robot-panel-title">
          <VaIcon name="smart_toy" size="small" />
          <span>{{ t('dashboard.robotStatus') }}</span>
          <VaBadge :text="String(robotList.length)" color="primary" />
        </VaCardTitle>
        <VaCardContent class="robot-panel-content">
          <div v-if="robotList.length === 0" class="no-robots">
            <VaIcon name="info" color="secondary" />
            <span>{{ t('dashboard.noRobotData') }}</span>
          </div>
          <div v-else class="robot-list">
            <RobotStatusCard v-for="robot in robotList" :key="robot.robotId" :robot="robot" />
          </div>
        </VaCardContent>
      </VaCard>
    </div>
  </div>
</template>

<style scoped>
.device-monitor-wrapper {
  height: calc(100vh - 80px);
  padding: 0;
  display: flex;
  gap: 12px;
}

.monitor-main {
  flex: 1;
  min-width: 0;
}

.device-monitor-card {
  height: 100%;
}

.device-monitor-content {
  height: 100%;
  display: flex;
  flex-direction: column;
  padding: 12px;
}

/* 右侧机器人面板 */
.robot-panel {
  width: 240px;
  flex-shrink: 0;
}

.robot-panel-card {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.robot-panel-title {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 12px;
  border-bottom: 1px solid var(--va-background-border);
  font-size: 14px;
  font-weight: 600;
}

.robot-panel-content {
  flex: 1;
  overflow-y: auto;
  padding: 8px !important;
}

.no-robots {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  gap: 8px;
  color: var(--va-text-secondary);
  font-size: 13px;
}

.robot-list {
  display: flex;
  flex-direction: column;
}

.toolbar-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 0;
  border-bottom: 1px solid var(--va-background-border);
  margin-bottom: 12px;
}

.toolbar-left {
  display: flex;
  align-items: center;
  gap: 12px;
}

.toolbar-right {
  display: flex;
  align-items: center;
  gap: 16px;
}

.map-select {
  min-width: 250px;
}

.task-input-group {
  display: flex;
  align-items: center;
  gap: 8px;
}

.node-input {
  width: 150px;
}

.execute-btn {
  width: 48px;
  height: 48px;
  font-size: 24px;
}

.arrow-icon {
  font-size: 16px;
  color: var(--va-text-secondary);
}

.toolbar-group {
  display: flex;
}

.stats-text {
  font-size: 13px;
  color: var(--va-text-secondary);
}

.map-canvas-wrapper {
  flex: 1;
  position: relative;
  overflow: hidden;
  border-radius: 8px;
  background: #fafafa;
}

.topo-canvas {
  width: 100%;
  height: 100%;
  cursor: grab;
}

.topo-canvas:active {
  cursor: grabbing;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: var(--va-text-secondary);
  gap: 16px;
}

.empty-state p {
  font-size: 16px;
}
</style>