X6Graph.vue 17.1 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
<template>
  <div class="factory-map">
    <div class="toolbar">
      <div class="toolbar-left">
        <h3>智能工厂工位监控系统</h3>
        <div class="stats">
          <span class="stat-item">
            <i class="el-icon-check"></i> 空闲工位: {{ idleStations }}
          </span>
          <span class="stat-item">
            <i class="el-icon-loading"></i> 执行任务: {{ busyStations }}
          </span>
          <span class="stat-item">
            <i class="el-icon-box"></i> 有托盘: {{ palletStations }}
          </span>
        </div>
      </div>
      <div class="toolbar-right">
        <button @click="startTask" :disabled="!selectedFrom || !selectedTo || selectedFrom === selectedTo" class="btn-primary">
          执行任务 ({{ selectedFrom }} → {{ selectedTo }})
        </button>
        <button @click="resetSelection" class="btn-secondary">清空选择</button>
        <button @click="refreshData" class="btn-secondary">刷新数据</button>
      </div>
    </div>

    <div class="graph-container">
      <div ref="graphContainer" class="graph"></div>
    </div>

    <div class="info-panel" v-if="selectedStation">
      <h4>工位详情</h4>
      <p><strong>工位编号:</strong> {{ selectedStation.id }}</p>
      <p><strong>状态:</strong>
        <span :class="getStatusClass(selectedStation.status)">
          {{ getStatusText(selectedStation.status) }}
        </span>
      </p>
      <p><strong>托盘状态:</strong> {{ selectedStation.hasPallet ? '有托盘' : '无托盘' }}</p>
      <p><strong>当前任务:</strong> {{ selectedStation.currentTask || '无' }}</p>
      <p v-if="selectedStation.nextTask"><strong>待执行任务:</strong> {{ selectedStation.nextTask }}</p>
      <button @click="clearStationSelection" class="btn-small">关闭</button>
    </div>
  </div>
</template>

<script>
import { Graph } from '@antv/x6'

export default {
  name: 'FactoryMap',
  data() {
    return {
      graph: null,
      stations: [],
      edges: [],
      selectedFrom: null,
      selectedTo: null,
      selectedStation: null,
      taskQueue: [],
      rgvPosition: 'A1',
      stationData: {
        row1: [
          { id: 'A1', name: '工位A1', status: 'idle', hasPallet: false, currentTask: null, nextTask: null, x: 100, y: 150 },
          { id: 'A2', name: '工位A2', status: 'idle', hasPallet: false, currentTask: null, nextTask: null, x: 220, y: 150 },
          { id: 'A3', name: '工位A3', status: 'busy', hasPallet: true, currentTask: '加工中', nextTask: '待质检', x: 340, y: 150 },
          { id: 'A4', name: '工位A4', status: 'idle', hasPallet: false, currentTask: null, nextTask: null, x: 460, y: 150 },
          { id: 'A5', name: '工位A5', status: 'busy', hasPallet: true, currentTask: '待转运', nextTask: null, x: 580, y: 150 },
          { id: 'A6', name: '工位A6', status: 'idle', hasPallet: false, currentTask: null, nextTask: null, x: 700, y: 150 }
        ],
        row2: [
          { id: 'B1', name: '工位B1', status: 'idle', hasPallet: false, currentTask: null, nextTask: null, x: 100, y: 350 },
          { id: 'B2', name: '工位B2', status: 'busy', hasPallet: true, currentTask: '待取货', nextTask: null, x: 220, y: 350 },
          { id: 'B3', name: '工位B3', status: 'idle', hasPallet: false, currentTask: null, nextTask: null, x: 340, y: 350 },
          { id: 'B4', name: '工位B4', status: 'idle', hasPallet: false, currentTask: null, nextTask: null, x: 460, y: 350 },
          { id: 'B5', name: '工位B5', status: 'busy', hasPallet: true, currentTask: '转运中', nextTask: null, x: 580, y: 350 },
          { id: 'B6', name: '工位B6', status: 'idle', hasPallet: false, currentTask: null, nextTask: null, x: 700, y: 350 }
        ]
      }
    }
  },
  computed: {
    idleStations() {
      return this.stations.filter(s => s.status === 'idle').length
    },
    busyStations() {
      return this.stations.filter(s => s.status === 'busy').length
    },
    palletStations() {
      return this.stations.filter(s => s.hasPallet).length
    }
  },
  mounted() {
    this.initStations()
    this.initGraph()
    this.startSimulation()
  },
  beforeDestroy() {
    if (this.graph) this.graph.dispose()
  },
  methods: {
    initStations() {
      this.stations = [...this.stationData.row1, ...this.stationData.row2]
    },
    initGraph() {
      const container = this.$refs.graphContainer
      const width = container.clientWidth
      const height = container.clientHeight

      this.graph = new Graph({
        container, width, height,
        background: { color: '#f0f2f5' },
        grid: { size: 20, visible: true, type: 'dot', args: { color: '#e0e0e0' } },
        panning: { enabled: true, modifiers: 'shift' },
        mousewheel: { enabled: true, modifiers: 'ctrl', factor: 1.1, maxScale: 1.5, minScale: 0.5 },
        interacting: { nodeMovable: false, edgeMovable: false },
        connecting: { enabled: false },
        selecting: { enabled: true, multiple: false } // 启用选择功能,禁用多选
      })

      this.drawTrack()
      this.addStationNodes()
      this.addConnections()
      this.addRGV()
      this.graph.zoomToFit({ padding: 50 })
      this.bindGraphEvents() // 绑定X6原生事件
    },
    drawTrack() {
      const trackY1 = 250, trackY2 = 260
      const startX = 50, endX = 750

      this.graph.addEdge({
        source: { x: startX, y: trackY1 }, target: { x: endX, y: trackY1 },
        attrs: { line: { stroke: '#5a626e', strokeWidth: 4, targetMarker: null, sourceMarker: null } }, zIndex: 1
      })
      this.graph.addEdge({
        source: { x: startX, y: trackY2 }, target: { x: endX, y: trackY2 },
        attrs: { line: { stroke: '#5a626e', strokeWidth: 4, targetMarker: null, sourceMarker: null } }, zIndex: 1
      })

      for (let x = startX + 50; x < endX; x += 100) {
        this.graph.addEdge({
          source: { x: x, y: trackY1 }, target: { x: x, y: trackY2 },
          attrs: { line: { stroke: '#8c9a9e', strokeWidth: 2, strokeDasharray: '5,5', targetMarker: null, sourceMarker: null } }, zIndex: 1
        })
      }
    },
    addStationNodes() {
      this.stations.forEach(station => {
        const node = this.graph.addNode({
          id: station.id, shape: 'rect',
          x: station.x, y: station.y, width: 90, height: 80,
          attrs: {
            body: {
              fill: this.getStationColor(station.status),
              stroke: station.hasPallet ? '#ff9800' : '#40a9ff',
              strokeWidth: station.hasPallet ? 3 : 2,
              rx: 8, ry: 8,
              filter: { name: 'dropShadow', args: { dx: 2, dy: 2, blur: 2, color: 'rgba(0,0,0,0.1)' } }
            },
            label: { text: `${station.name}\n${station.hasPallet ? '📦' : '○'}`, fill: '#333', fontSize: 12, fontWeight: 'bold', lineHeight: 1.4 }
          },
          data: station,
          tools: [{
            name: 'button',
            args: {
              markup: [
                { tagName: 'circle', selector: 'button', attrs: { r: 12, fill: '#52c41a', stroke: '#fff', 'stroke-width': 2, cursor: 'pointer' } },
                { tagName: 'text', textContent: '✓', selector: 'icon', attrs: { fill: '#fff', 'font-size': 12, 'text-anchor': 'middle', 'pointer-events': 'none', y: 2 } }
              ],
              x: '100%', y: '0%', offset: { x: -15, y: 5 },
              onClick: ({ cell }) => {
                if (cell && cell.data) this.selectStation(cell.data.id)
              }
            }
          }]
        })
      })
    },
    addConnections() {
      this.stations.forEach(station => {
        const trackY = station.y < 250 ? 250 : 260
        this.graph.addEdge({
          source: { cell: station.id, port: 'bottom' },
          target: { x: station.x + 45, y: trackY },
          attrs: { line: { stroke: '#b0bec5', strokeWidth: 2, strokeDasharray: '5,5', targetMarker: null, sourceMarker: null } },
          connector: { name: 'normal' }, zIndex: 0
        })
      })
    },
    addRGV() {
      const rgvNode = this.graph.addNode({
        id: 'rgv', shape: 'circle',
        x: 100, y: 255, width: 30, height: 30,
        attrs: {
          body: { fill: '#ff6b6b', stroke: '#c92a2a', strokeWidth: 2, filter: { name: 'dropShadow', args: { dx: 2, dy: 2, blur: 3, color: 'rgba(0,0,0,0.2)' } } },
          label: { text: 'RGV', fill: '#fff', fontSize: 10, fontWeight: 'bold' }
        },
        data: { type: 'rgv', position: 'A1' }, zIndex: 10
      })
      setInterval(() => {
        if (rgvNode) {
          rgvNode.attr('body/fill', '#ff8787')
          setTimeout(() => rgvNode && rgvNode.attr('body/fill', '#ff6b6b'), 300)
        }
      }, 2000)
    },
    bindGraphEvents() {
      // 绑定X6原生节点点击事件,解决Vue事件无法穿透SVG问题
      this.graph.on('node:click', ({ node }) => {
        if (node && node.data) this.selectStation(node.data.id)
      })
      // 点击空白处清空选择
      this.graph.on('blank:click', () => {
        this.resetSelection()
      })
    },
    selectStation(stationId) {
      const station = this.stations.find(s => s.id === stationId)
      if (!station) return

      if (!this.selectedFrom) {
        this.selectedFrom = stationId
        this.highlightStation(stationId, '#1890ff')
      } else if (!this.selectedTo && this.selectedFrom !== stationId) {
        this.selectedTo = stationId
        this.highlightStation(stationId, '#52c41a')
      } else {
        this.selectedFrom = stationId
        this.selectedTo = null
        this.clearHighlight()
        this.highlightStation(stationId, '#1890ff')
      }
      this.selectedStation = station
      // 强制更新Vue响应式状态
      this.$forceUpdate()
    },
    highlightStation(stationId, color) {
      const node = this.graph.getCellById(stationId)
      if (node) {
        node.attr('body/stroke', color)
        node.attr('body/strokeWidth', 4)
        node.setSelected(true)
      }
    },
    clearHighlight() {
      this.stations.forEach(station => {
        const node = this.graph.getCellById(station.id)
        if (node) {
          node.attr('body/stroke', station.hasPallet ? '#ff9800' : '#40a9ff')
          node.attr('body/strokeWidth', station.hasPallet ? 3 : 2)
          node.setSelected(false)
        }
      })
      // 清除X6选择状态
      this.graph.clearSelected()
    },
    async startTask() {
      if (!this.selectedFrom || !this.selectedTo || this.selectedFrom === this.selectedTo) return
      const fromStation = this.stations.find(s => s.id === this.selectedFrom)
      const toStation = this.stations.find(s => s.id === this.selectedTo)
      if (!fromStation.hasPallet) { alert('起始工位无托盘!'); return }
      if (toStation.hasPallet) { alert('目标工位有托盘!'); return }

      this.showTaskAnimation(this.selectedFrom, this.selectedTo)
      await this.simulateTask(fromStation, toStation)
      this.resetSelection()
    },
    async simulateTask(fromStation, toStation) {
      await this.moveRGV(fromStation.id)
      fromStation.hasPallet = false
      fromStation.status = 'idle'
      fromStation.currentTask = null
      this.updateStationNode(fromStation.id)

      await this.moveRGV(toStation.id)
      toStation.hasPallet = true
      toStation.status = 'busy'
      toStation.currentTask = '待处理'
      this.updateStationNode(toStation.id)

      this.addTaskRecord(fromStation.id, toStation.id)
    },
    async moveRGV(targetStationId) {
      const rgvNode = this.graph.getCellById('rgv')
      const targetStation = this.stations.find(s => s.id === targetStationId)
      if (!rgvNode || !targetStation) return
      const targetX = targetStation.x + 30
      const targetY = 255

      return new Promise((resolve) => {
        let startX = rgvNode.position().x
        const step = 10
        const interval = setInterval(() => {
          startX += step
          if (startX >= targetX) {
            rgvNode.position(targetX, targetY)
            clearInterval(interval)
            resolve()
          } else {
            rgvNode.position(startX, targetY)
          }
        }, 20)
      })
    },
    showTaskAnimation(fromId, toId) {
      const fromNode = this.graph.getCellById(fromId)
      const toNode = this.graph.getCellById(toId)
      if (fromNode && toNode) {
        fromNode.attr('body/fill', '#ffd966')
        toNode.attr('body/fill', '#ffd966')
        setTimeout(() => {
          fromNode && fromNode.attr('body/fill', this.getStationColor(fromNode.data.status))
          toNode && toNode.attr('body/fill', this.getStationColor(toNode.data.status))
        }, 1000)
      }
    },
    updateStationNode(stationId) {
      const station = this.stations.find(s => s.id === stationId)
      const node = this.graph.getCellById(stationId)
      if (node && station) {
        node.attr('body/fill', this.getStationColor(station.status))
        node.attr('body/stroke', station.hasPallet ? '#ff9800' : '#40a9ff')
        node.attr('body/strokeWidth', station.hasPallet ? 3 : 2)
        node.attr('label/text', `${station.name}\n${station.hasPallet ? '📦' : '○'}`)
        node.setData(station)
      }
    },
    addTaskRecord(fromId, toId) {
      const task = {
        id: Date.now(),
        from: fromId,
        to: toId,
        time: new Date().toLocaleTimeString()
      }
      this.taskQueue.unshift(task)
      console.log(`任务执行: ${fromId} → ${toId} at ${task.time}`)
    },
    resetSelection() {
      // 重置所有选择状态
      this.selectedFrom = null
      this.selectedTo = null
      this.selectedStation = null
      this.clearHighlight()
      // 强制更新Vue视图
      this.$forceUpdate()
    },
    clearStationSelection() {
      this.selectedStation = null
    },
    refreshData() {
      this.stations.forEach(station => {
        if (Math.random() > 0.7) {
          station.status = Math.random() > 0.5 ? 'idle' : 'busy'
          station.hasPallet = station.status === 'busy'
          this.updateStationNode(station.id)
        }
      })
      this.clearHighlight()
      this.selectedStation = null
    },
    getStationColor(status) {
      const colors = {
        idle: '#e6f7ff',
        busy: '#fff1f0'
      }
      return colors[status] || '#f5f5f5'
    },
    getStatusText(status) {
      const texts = {
        idle: '空闲',
        busy: '繁忙'
      }
      return texts[status] || '未知'
    },
    getStatusClass(status) {
      return status === 'idle' ? 'status-idle' : 'status-busy'
    },
    startSimulation() {
      setInterval(() => {
        const randomStation = this.stations[Math.floor(Math.random() * this.stations.length)]
        if (randomStation && Math.random() > 0.8) {
          randomStation.hasPallet = !randomStation.hasPallet
          randomStation.status = randomStation.hasPallet ? 'busy' : 'idle'
          this.updateStationNode(randomStation.id)
        }
      }, 10000)
    }
  }
}
</script>

<style scoped>
.factory-map {
  width: 100%;
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: #f5f7fa;
  font-family: 'Microsoft YaHei', Arial, sans-serif;
}

.toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 30px;
  background: white;
  box-shadow: 0 2px 8px rgba(0,0,0,0.08);
  z-index: 10;
}

.toolbar-left h3 {
  margin: 0 0 8px 0;
  color: #1890ff;
  font-weight: 600;
}

.stats {
  display: flex;
  gap: 20px;
}

.stat-item {
  display: flex;
  align-items: center;
  gap: 5px;
  font-size: 14px;
  color: #666;
}

.stat-item i {
  font-size: 16px;
}

.toolbar-right {
  display: flex;
  gap: 12px;
}

.btn-primary, .btn-secondary, .btn-small {
  padding: 8px 20px;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
  font-weight: 500;
  transition: all 0.3s;
}

.btn-primary {
  background: #1890ff;
  color: white;
}

.btn-primary:hover:not(:disabled) {
  background: #40a9ff;
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(24,144,255,0.3);
}

.btn-primary:disabled {
  background: #d9d9d9;
  cursor: not-allowed;
}

.btn-secondary {
  background: #f0f2f5;
  color: #666;
  border: 1px solid #d9d9d9;
}

.btn-secondary:hover {
  background: #e6f7ff;
  border-color: #1890ff;
  color: #1890ff;
}

.btn-small {
  padding: 5px 12px;
  font-size: 12px;
  background: #f0f2f5;
  color: #666;
}

.graph-container {
  flex: 1;
  position: relative;
  overflow: hidden;
}

.graph {
  width: 100%;
  height: 100%;
}

.info-panel {
  position: absolute;
  top: 100px;
  right: 30px;
  width: 280px;
  background: white;
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 4px 12px rgba(0,0,0,0.15);
  z-index: 20;
  animation: slideIn 0.3s ease;
}

.info-panel h4 {
  margin: 0 0 15px 0;
  color: #1890ff;
  border-bottom: 2px solid #f0f2f5;
  padding-bottom: 8px;
}

.info-panel p {
  margin: 10px 0;
  font-size: 14px;
  line-height: 1.6;
}

.status-idle {
  color: #52c41a;
  font-weight: bold;
}

.status-busy {
  color: #ff4d4f;
  font-weight: bold;
}

@keyframes slideIn {
  from {
    opacity: 0;
    transform: translateX(30px);
  }
  to {
    opacity: 1;
    transform: translateX(0);
  }
}

/* 滚动条样式 */
::-webkit-scrollbar {
  width: 8px;
  height: 8px;
}

::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 4px;
}

::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 4px;
}

::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}
</style>