OeeDialog.vue 28.6 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
<template>
  <el-dialog
    :model-value="visible"
    @update:model-value="$emit('update:visible', $event)"
    :title="dialogTitle"
    width="calc(100vw - 40px)"
    :style="{ maxWidth: '1400px' }"
    top="3vh"
    destroy-on-close
    class="oee-dialog"
  >
    <template #header>
      <div class="dialog-header">
        <div class="header-left">
          <span class="title-text">{{ dialogTitle }}</span>
          <span class="query-label">查询方式:</span>
          <el-radio-group v-model="queryType" size="small">
            <el-radio-button value="day">日查询</el-radio-button>
          </el-radio-group>
          <el-date-picker v-model="queryDate" type="date" placeholder="选择日期" size="small"
            style="width: 160px; margin-left: 8px;" @change="fetchLampData" />
        </div>
      </div>
    </template>

    <div class="oee-body">
      <!-- OEE时序图 -->
      <div class="chart-section">
        <h4 class="section-title">OEE时序</h4>
        <div class="timeline-chart" ref="timelineRef" @wheel.prevent="onWheel">
          <canvas ref="canvasRef" :width="canvasW" :height="canvasH"
            @mousemove="onCanvasMouseMove" @mouseleave="hoverSeg = null"></canvas>
          <!-- 自定义悬浮提示框 -->
          <div v-if="hoverSeg" class="hover-tooltip" :style="{ left: tooltipPos.x + 'px', top: tooltipPos.y + 'px' }">
            <div class="tip-row"><span class="tip-label">开始时间:</span>{{ hoverSeg.startTimeText }}</div>
            <div class="tip-row"><span class="tip-label">结束时间:</span>{{ hoverSeg.endTimeText }}</div>
            <div class="tip-row"><span class="tip-label">状态:</span><span :style="{ color: stateColorMap[hoverSeg.state] }">{{ stateNameMap[hoverSeg.state] || '未知' }}</span></div>
            <div class="tip-row"><span class="tip-label">持续时长:</span>{{ formatDuration(hoverSeg.duration) }}</div>
          </div>
        </div>
      </div>

      <!-- 底部两栏 -->
      <div class="bottom-grid">
        <!-- 左侧:OEE时序详情表格 -->
        <div class="table-panel">
          <div class="panel-header">
            <h4 class="panel-title">OEE时序详情</h4>
            <div class="panel-actions">
              <el-select v-model="durationFilter" placeholder="请选择" size="small" style="width: 140px;">
                <el-option v-for="n in 60" :key="n" :label="`>${n}分`" :value="n"/>
              </el-select>
            </div>
          </div>
          <el-table :data="filteredTableData" size="small" stripe max-height="400" style="font-size: 12px;">
            <el-table-column prop="startTime" label="开始时间" width="170" />
            <el-table-column prop="status" label="状态" width="80">
              <template #default="{ row }">
                <el-tag :type="statusTagType(row.statusName)" size="small">{{ row.statusName }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="durationText" label="运行时长" sortable width="100" />
            <el-table-column prop="reason" label="原因" />
            <el-table-column prop="operator" label="操作人" width="120" />
          </el-table>
        </div>

        <!-- 右侧:双图表(左右布局) -->
        <div class="chart-panel">
          <!-- 当日时长分布 — 实心饼图 -->
          <div class="sub-chart">
            <h4 class="panel-title">当日时长分布</h4>
            <div class="legend-list">
              <div class="legend-item"><span class="dot green"></span>绿灯</div>
              <div class="legend-item"><span class="dot red"></span>红灯</div>
              <div class="legend-item"><span class="dot yellow"></span>黄灯</div>
            </div>
            <div class="pie-canvas-wrap">
              <canvas ref="pieCanvasRef" width="320" height="320" class="pie-canvas"
                @mousemove="onPieMouseMove" @mouseleave="pieHoverItem = null"></canvas>
              <!-- 饼图悬浮提示框 -->
              <div v-if="pieHoverItem" class="pie-tooltip" :style="{ left: pieTooltipPos.x + 'px', top: pieTooltipPos.y + 'px' }">
                <div class="pie-tip-title">时长详情</div>
                <div class="pie-tip-row"><span class="dot" :style="{ background: pieHoverItem.color }"></span>{{ pieHoverItem.key }}:{{ formatDuration(pieHoverItem.sec) }}</div>
              </div>
            </div>
          </div>
          <!-- 异常原因分布 — 环形图 -->
          <div class="sub-chart">
            <h4 class="panel-title">异常原因分布</h4>
            <div class="legend-list">
              <div class="legend-item"><span class="dot" style="background:#f56c6c"></span>红灯未知原因</div>
              <div class="legend-item"><span class="dot" style="background:#f5a623"></span>黄灯未知原因</div>
            </div>
            <div class="pie-canvas-wrap">
              <canvas ref="reasonCanvasRef" width="320" height="320" class="pie-canvas"
                @mousemove="onReasonMouseMove" @mouseleave="reasonHoverItem = null"></canvas>
              <!-- 异常原因 hover 提示框 -->
              <div v-if="reasonHoverItem" class="pie-tooltip" :style="{ left: reasonTooltipPos.x + 'px', top: reasonTooltipPos.y + 'px' }">
                <div class="pie-tip-title">时长占比</div>
                <div v-for="(row, i) in reasonHoverItem.rows" :key="i" class="pie-tip-row">{{ row.key }}总时长 {{ formatDuration(row.sec) }}</div>
                <div class="pie-tip-row">时长占比 {{ reasonHoverItem.pct }}%</div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, computed, watch, onMounted, nextTick } from 'vue'

const props = defineProps({
  visible: Boolean,
  device: Object
})
const emit = defineEmits(['update:visible'])

const queryType = ref('day')
const queryDate = ref(new Date())
const durationFilter = ref(null)

// 状态映射
const stateColorMap = { 0: '#909399', 1: '#c0392b', 2: '#e67e22', 3: '#67c23a', 4: '#2463aa' }
const stateNameMap = { '0': '灭灯', '1': '红灯', '2': '黄灯', '3': '绿灯', '4': '蓝灯' }

// 数据
const lampData = ref([])
const stats = reactive({ off: '0秒', red: '0秒', yellow: '0秒', green: '0秒', blue: '0秒' })

// 标题
const dialogTitle = computed(() => {
  const name = props.device?.name || props.device?._raw?.deviceName || '设备'
  return `${name} OEE时序`
})

// 格式化日期 YYYY-MM-DD
function formatDate(d) {
  if (!d) return new Date().toISOString().slice(0, 10)
  const dt = new Date(d)
  const y = dt.getFullYear()
  const m = String(dt.getMonth() + 1).padStart(2, '0')
  const dd = String(dt.getDate()).padStart(2, '0')
  return `${y}-${m}-${dd}`
}

// 秒数 → X分Y秒 / X时X分X秒
function formatDuration(seconds) {
  if (!seconds || seconds <= 0) return '0秒'
  seconds = Number(seconds)
  const h = Math.floor(seconds / 3600)
  const m = Math.floor((seconds % 3600) / 60)
  const s = Math.round(seconds % 60)
  if (h > 0) return `${h}时${m}分${s}秒`
  if (m > 0) return `${m}分${s}秒`
  return `${s}秒`
}

// 解析时长字符串为秒数(用于筛选)
function parseDurationToSec(str) {
  if (!str) return 0
  let total = 0
  const hMatch = str.match(/(\d+)时/)
  const mMatch = str.match(/(\d+)分/)
  const sMatch = str.match(/(\d+)秒/)
  if (hMatch) total += parseInt(hMatch[1]) * 3600
  if (mMatch) total += parseInt(mMatch[1]) * 60
  if (sMatch) total += parseInt(sMatch[1])
  return total
}

// 表格数据
const tableData = computed(() => {
  return lampData.value.map(item => ({
    startTime: item.startTime,
    status: item.lampState,
    statusName: stateNameMap[String(item.lampState)] || '未知',
    duration: item.duration,
    durationText: formatDuration(item.duration),
    reason: '无',
    operator: '设备上传',
  }))
})

// 时长筛选后的表格数据
const filteredTableData = computed(() => {
  if (!durationFilter.value) return tableData.value
  const threshold = durationFilter.value * 60 // 分 → 秒
  return tableData.value.filter(row => parseDurationToSec(row.durationText) >= threshold)
})

// ========== 时序图 Canvas 绘制 ==========
const CANVAS_H = 100
const timelineRef = ref(null)
const canvasRef = ref(null)
const zoomLevel = ref(1)
const minZoom = 0.001
const maxZoom = 1
const hoverSeg = ref(null)
const tooltipPos = reactive({ x: 0, y: 0 })
const containerW = ref(900)        // 容器 CSS 宽度
const canvasW = ref(900)           // canvas 像素宽(=容器宽,1:1映射)
const canvasH = ref(CANVAS_H)      // canvas 像素高
const viewOffsetX = ref(0)         // 视口偏移(数据空间)

// 格式化时间字符串 (用于tooltip)
function formatTimeStr(isoStr) {
  if (!isoStr) return ''
  const d = new Date(isoStr)
  const m = String(d.getMonth() + 1).padStart(2, '0')
  const dd = String(d.getDate()).padStart(2, '0')
  const h = String(d.getHours()).padStart(2, '0')
  const min = String(d.getMinutes()).padStart(2, '0')
  const s = String(d.getSeconds()).padStart(2, '0')
  return `${m}/${dd} ${h}:${min}:${s}`
}

// 计算结束时间
function calcEndTime(startTime, durationSec) {
  if (!startTime) return ''
  const d = new Date(startTime)
  d.setSeconds(d.getSeconds() + (durationSec || 0))
  return formatTimeStr(d.toISOString())
}

function onWheel(e) {
  const container = timelineRef.value
  if (!container) return
  const rect = container.getBoundingClientRect()
  const mx = e.clientX - rect.left

  const mouseDataX = mx * zoomLevel.value + viewOffsetX.value
  // 向上滚动(deltaY < 0)缩小,向下(deltaY > 0)放大
  const delta = e.deltaY < 0 ? 0.8 : 1.25
  const nextZ = Math.max(minZoom, Math.min(maxZoom, zoomLevel.value * delta))
  viewOffsetX.value = mouseDataX - mx * nextZ
  zoomLevel.value = nextZ
}

// 数据空间:24h → plotW 像素(zoom=1时),左侧留 offset 像素放标签
const rawSegments = computed(() => {
  if (!lampData.value.length) return []
  const dayStr = formatDate(queryDate.value)
  const [y, m, d] = dayStr.split('-').map(Number)
  const dayStartMs = new Date(y, m - 1, d).getTime()
  const plotLeft = 55
  const plotW = canvasW.value - plotLeft - 10

  return lampData.value.map(item => {
    const startMs = new Date(item.startTime).getTime()
    const durSec = item.duration || 0
    const endMs = startMs + durSec * 1000

    const startX = ((startMs - dayStartMs) / 86400000) * plotW + plotLeft
    const endX = ((endMs - dayStartMs) / 86400000) * plotW + plotLeft
    const x = Math.max(plotLeft, startX)
    const w = Math.max(1, endX - x)

    return { x, w,
      state: String(item.lampState),
      startTime: item.startTime,
      duration: item.duration,
      startTimeText: formatTimeStr(item.startTime),
      endTimeText: calcEndTime(item.startTime, item.duration),
    }
  })
})

// Canvas 绘制 —— 数据坐标 → 屏幕坐标: screenX = (dataX - viewOffsetX) / zoomLevel
function drawTimeline() {
  const canvas = canvasRef.value
  if (!canvas) return
  const ctx = canvas.getContext('2d')
  const W = canvasW.value
  const H = canvasH.value
  const z = zoomLevel.value
  const vo = viewOffsetX.value

  // 布局参数(参考目标样式:时刻左上、条带居中、时间轴底部)
  const labelLeft = 50       // "时刻" 标签 X 偏移
  const plotLeft = 55        // 数据区起点 X
  const plotW = W - plotLeft - 10 // 数据区宽度
  const barY = 24            // 条带顶部 Y
  const barH = 46            // 条带高度
  const axisY = barY + barH + 8   // 分隔线 Y
  const timeLabelY = H - 4   // 时间标签 Y

  ctx.clearRect(0, 0, W, H)

  // "时刻" 标签
  ctx.fillStyle = '#999'
  ctx.font = '12px sans-serif'
  ctx.fillText('时刻', labelLeft - vo / z, 16)

  // 时间轴标签 — 整数刻度对齐
  const totalSec = 24 * 3600
  // 视口可见时间跨度(秒)
  const visSpanSec = Math.max(60, (W * z / plotW) * totalSec)
  // 根据可见跨度选漂亮步长:确保屏幕上约显示 6~10 个标签
  let stepSec = 14400  // 默认 4 小时
  if (visSpanSec <= 120) stepSec = 30        // <2分钟 → 每30秒
  else if (visSpanSec <= 300) stepSec = 60   // <5分钟 → 每分钟
  else if (visSpanSec <= 600) stepSec = 300  // <10分钟 → 每5分钟
  else if (visSpanSec <= 1800) stepSec = 600 // <30分钟 → 每10分钟
  else if (visSpanSec <= 3600) stepSec = 900 // <1小时 → 每15分钟
  else if (visSpanSec <= 7200) stepSec = 1800// <2小时 → 每30分钟
  else if (visSpanSec <= 28800) stepSec = 3600 // <8小时 → 每小时
  else stepSec = 7200                         // >=8小时 → 每2小时

  ctx.font = '11px sans-serif'
  ctx.fillStyle = '#666'

  // 视口左边界对应的时间(秒)
  const leftSec = ((vo - plotLeft) / plotW) * totalSec
  // 对齐到 stepSec 边界(向下取整),找第一个标签
  let firstSec = Math.floor(leftSec / stepSec) * stepSec
  if (firstSec < 0) firstSec = 0

  // 整数循环,只画整数刻度
  for (let s = firstSec; s <= totalSec + stepSec * 2; s += stepSec) {
    const dataPx = plotLeft + (s / totalSec) * plotW
    const screenPx = (dataPx - vo) / z
    if (screenPx < -50 || screenPx > W + 50) continue

    const h = Math.floor(s / 3600)
    const mm = Math.floor((s % 3600) / 60)
    const ss = s % 60

    if (stepSec < 60) {
      ctx.fillText(`${String(h).padStart(2,'0')}:${String(mm).padStart(2,'0')}:${String(ss).padStart(2,'0')}`, screenPx, timeLabelY)
    } else {
      ctx.fillText(`${String(h).padStart(2,'0')}:${String(mm).padStart(2,'0')}`, screenPx, timeLabelY)
    }
  }

  // 分隔线(条带与时间轴之间)
  ctx.strokeStyle = '#ddd'
  ctx.lineWidth = 1
  ctx.beginPath()
  ctx.moveTo((plotLeft - vo) / z, axisY)
  ctx.lineTo(((plotLeft + plotW) - vo) / z, axisY)
  ctx.stroke()

  // 条带
  const hoveredIdx = hoverSeg.value ? rawSegments.value.indexOf(hoverSeg.value) : -1

  rawSegments.value.forEach((seg, idx) => {
    const sx = (seg.x - vo) / z
    const sw = seg.w / z
    if (sx + sw < -1 || sx > W + 1) return

    ctx.fillStyle = stateColorMap[seg.state] || '#909399'
    ctx.globalAlpha = idx === hoveredIdx ? 0.7 : 1

    // 纯矩形,无圆角
    ctx.fillRect(sx, barY, sw, barH)
  })

  ctx.globalAlpha = 1
}

// 鼠标 hit test
function onCanvasMouseMove(e) {
  const container = timelineRef.value
  if (!container) return
  const rect = container.getBoundingClientRect()
  const mx = e.clientX - rect.left
  const my = e.clientY - rect.top
  const z = zoomLevel.value
  const vo = viewOffsetX.value
  const dataX = mx * z + vo

  // 与 drawTimeline 中一致的条带位置
  const barY = 24
  const barH = 46
  let found = null

  for (let i = rawSegments.value.length - 1; i >= 0; i--) {
    const seg = rawSegments.value[i]
    if (dataX >= seg.x && dataX <= seg.x + seg.w && my >= barY && my <= barY + barH) {
      found = seg
      break
    }
  }

  hoverSeg.value = found
  if (found) {
    tooltipPos.x = Math.min(Math.max(mx + 12, 12), rect.width - 190)
    tooltipPos.y = Math.max(my - 80, 6)
  }
}

// ========== 监听容器尺寸变化 ==========
function updateCanvasSize() {
  if (!timelineRef.value) return
  // 减去 padding (左右各 6px ≈ 12px)
  containerW.value = timelineRef.value.clientWidth - 12
  canvasW.value = containerW.value
  canvasH.value = CANVAS_H
}

// ========== 饼图 Canvas ==========
const pieCanvasRef = ref(null)
const reasonCanvasRef = ref(null)
const pieHoverItem = ref(null)
const pieTooltipPos = reactive({ x: 0, y: 0 })
const reasonHoverItem = ref(null)
const reasonTooltipPos = reactive({ x: 0, y: 0 })
// 存储饼图扇区角度范围用于 hover 检测
let pieAngleRanges = []
let reasonAngleRanges = []

// 当日时长分布 — 各状态秒数
const stateSeconds = computed(() => ({
  green: parseDurationToSec(stats.green),
  red: parseDurationToSec(stats.red),
  yellow: parseDurationToSec(stats.yellow)
}))

const totalSeconds = computed(() => {
  return stateSeconds.value.green + stateSeconds.value.red + stateSeconds.value.yellow || 1
})

// 异常原因分布 — 只用 lampDurationStats 中红灯 + 黄灯的数据
const reasonStats = computed(() => {
  const redSec = parseDurationToSec(stats.red)
  const yellowSec = parseDurationToSec(stats.yellow)
  const items = []
  if (redSec > 0) items.push({ key: '红灯', sec: redSec, color: '#f56c6c' })
  if (yellowSec > 0) items.push({ key: '黄灯', sec: yellowSec, color: '#f5a623' })
  return items
})

function drawPieChart(canvasRefKey, items, options = {}) {
  const canvas = canvasRefKey?.value
  if (!canvas) return
  const ctx = canvas.getContext('2d')
  const W = canvas.width, H = canvas.height
  const cx = W / 2, cy = H / 2
  const r = Math.min(W, H) / 2 - 8
  const solid = !!options.solid   // 实心饼图(无内圆)
  const innerR = solid ? 0 : r * 0.55

  ctx.clearRect(0, 0, W, H)

  if (!items || items.length === 0) {
    ctx.beginPath()
    ctx.arc(cx, cy, r, 0, Math.PI * 2)
    if (!solid) { ctx.arc(cx, cy, innerR, 0, Math.PI * 2, true) }
    ctx.fillStyle = '#eee'
    ctx.fill()
    ctx.fillStyle = '#999'
    ctx.font = '12px sans-serif'
    ctx.textAlign = 'center'
    ctx.textBaseline = 'middle'
    ctx.fillText('暂无数据', cx, cy)
    // 清空角度范围
    if (canvas === pieCanvasRef.value) pieAngleRanges = []
    if (canvas === reasonCanvasRef.value) reasonAngleRanges = []
    return
  }

  const total = items.reduce((s, i) => s + i.sec, 0) || 1
  let startAngle = -Math.PI / 2

  // 重置对应画布的角度范围
  if (canvas === pieCanvasRef.value) pieAngleRanges = []
  if (canvas === reasonCanvasRef.value) reasonAngleRanges = []

  items.forEach(item => {
    const angle = (item.sec / total) * Math.PI * 2
    const endAngle = startAngle + angle
    const midAngle = startAngle + angle / 2

    // 扇区路径
    ctx.beginPath()
    if (solid) {
      ctx.moveTo(cx, cy)
      ctx.arc(cx, cy, r, startAngle, endAngle)
      ctx.closePath()
    } else {
      ctx.moveTo(cx + innerR * Math.cos(startAngle), cy + innerR * Math.sin(startAngle))
      ctx.arc(cx, cy, r, startAngle, endAngle)
      ctx.arc(cx, cy, innerR, endAngle, startAngle, true)
      ctx.closePath()
    }
    ctx.fillStyle = item.color
    ctx.fill()

    // 记录角度范围用于 hover 检测
    if (canvas === pieCanvasRef.value) {
      pieAngleRanges.push({ ...item, startAngle, endAngle, cx, cy, r, innerR, total })
    } else if (canvas === reasonCanvasRef.value) {
      reasonAngleRanges.push({ ...item, startAngle, endAngle, cx, cy, r, innerR, total })
    }

    // 标签
    if (angle > 0.25) {
      const labelR = solid ? r * 0.65 : (r + innerR) / 2
      const lx = cx + labelR * Math.cos(midAngle)
      const ly = cy + labelR * Math.sin(midAngle)
      const pct = (item.sec / total * 100).toFixed(2)

      ctx.fillStyle = '#fff'
      // canvas 分辨率 320,字体需放大以匹配显示尺寸
      ctx.font = solid ? 'bold 18px sans-serif' : 'bold 16px sans-serif'
      ctx.textAlign = 'center'
      ctx.textBaseline = 'middle'
      ctx.fillText(`${pct}%`, lx, ly - (solid ? 11 : 8))

      ctx.font = solid ? '14px sans-serif' : '12px sans-serif'
      if (solid) {
        const h = Math.floor(item.sec / 3600)
        const m = Math.floor((item.sec % 3600) / 60)
        let durText = ''
        if (h > 0) durText = `${item.key}:${h}.${String(m).padStart(2,'0')}时`
        else if (m > 0) durText = `${item.key}:${m}分`
        else durText = `${item.key}:${Math.round(item.sec % 60)}秒`
        ctx.fillText(durText, lx, ly + 11)
      } else {
        ctx.fillText(item.key, lx, ly + (solid ? 12 : 10))
      }
    }

    startAngle = endAngle
  })
}

// 饼图 hover 检测
function onPieMouseMove(e) {
  const canvas = pieCanvasRef.value
  if (!canvas) return
  const rect = canvas.getBoundingClientRect()
  const mx = e.clientX - rect.left
  const my = e.clientY - rect.top
  // 转换为 canvas 内部坐标(考虑 CSS 缩放)
  const scaleX = canvas.width / rect.width
  const scaleY = canvas.height / rect.height
  const px = mx * scaleX
  const py = my * scaleY

  let found = null
  for (let i = pieAngleRanges.length - 1; i >= 0; i--) {
    const seg = pieAngleRanges[i]
    const dx = px - seg.cx
    const dy = py - seg.cy
    const dist = Math.sqrt(dx * dx + dy * dy)

    // 判断是否在扇区内(实心:dist <= r;环形:innerR < dist <= r)
    const inRadius = dist <= seg.r && dist >= seg.innerR
    if (!inRadius) continue

    // 计算鼠标角度,与扇区角度比较
    let mouseAngle = Math.atan2(dy, dx)
    // 归一化角度到 [-PI, PI],然后统一到 startAngle~endAngle 的范围
    // 简化处理:直接比较,考虑跨 -PI 边界的情况
    let a = mouseAngle
    let sa = seg.startAngle
    let ea = seg.endAngle

    // 处理跨边界情况
    function inRange(a, sa, ea) {
      // 标准化为 [0, 2PI)
      const norm = v => { let x = v % (Math.PI * 2); if (x < 0) x += Math.PI * 2; return x }
      const na = norm(a), nsa = norm(sa), nea = norm(ea)
      if (nea >= nsa) return na >= nsa && na <= nea
      else return na >= nsa || na <= nea
    }

    if (inRange(a, sa, ea)) {
      found = seg
      break
    }
  }

  pieHoverItem.value = found
  if (found) {
    pieTooltipPos.x = Math.min(Math.max(mx + 12, 12), rect.width - 160)
    pieTooltipPos.y = Math.max(my - 60, 6)
  }
}

// 异常原因分布 hover 检测 — tooltip 显示"时长占比"格式
function onReasonMouseMove(e) {
  const canvas = reasonCanvasRef.value
  if (!canvas) return
  const rect = canvas.getBoundingClientRect()
  const mx = e.clientX - rect.left
  const my = e.clientY - rect.top
  const scaleX = canvas.width / rect.width
  const scaleY = canvas.height / rect.height
  const px = mx * scaleX
  const py = my * scaleY

  let found = null
  for (let i = reasonAngleRanges.length - 1; i >= 0; i--) {
    const seg = reasonAngleRanges[i]
    const dx = px - seg.cx
    const dy = py - seg.cy
    const dist = Math.sqrt(dx * dx + dy * dy)
    const inRadius = dist <= seg.r && dist >= seg.innerR
    if (!inRadius) continue

    const mouseAngle = Math.atan2(dy, dx)
    function inRange(a, sa, ea) {
      const norm = v => { let x = v % (Math.PI * 2); if (x < 0) x += Math.PI * 2; return x }
      const na = norm(a), nsa = norm(sa), nea = norm(ea)
      if (nea >= nsa) return na >= nsa && na <= nea
      else return na >= nsa || na <= nea
    }

    if (inRange(mouseAngle, seg.startAngle, seg.endAngle)) {
      found = seg
      break
    }
  }

  // 构造 tooltip 数据:显示所有项 + 总占比
  if (found || reasonAngleRanges.length > 0) {
    const total = reasonAngleRanges.reduce((s, r) => s + r.sec, 0) || 1
    const pct = (found ? found.sec / total : total > 0 ? 1 : 0) * 100
    reasonHoverItem.value = found ? {
      rows: [{ key: found.key, sec: found.sec }],
      pct: pct.toFixed(2)
    } : {
      rows: reasonAngleRanges.map(r => ({ key: r.key, sec: r.sec })),
      pct: '100.00'
    }
    if (!found) {
      // 悬浮在空白区域显示所有数据
      reasonHoverItem.value = {
        rows: reasonAngleRanges.map(r => ({ key: r.key, sec: r.sec })),
        pct: '100.00'
      }
    }
  } else {
    reasonHoverItem.value = null
  }

  if (reasonHoverItem.value) {
    reasonTooltipPos.x = Math.min(Math.max(mx + 12, 12), rect.width - 180)
    reasonTooltipPos.y = Math.max(my - 70, 6)
  }
}

// 绘制当日时长分布饼图(实心)
function drawDurationPie() {
  const { green, red, yellow } = stateSeconds.value
  const items = []
  if (green > 0) items.push({ key: '绿灯', sec: green, color: '#67c23a' })
  if (red > 0) items.push({ key: '红灯', sec: red, color: '#f56c6c' })
  if (yellow > 0) items.push({ key: '黄灯', sec: yellow, color: '#f5a623' })
  drawPieChart(pieCanvasRef, items, { solid: true })
}

// 绘制异常原因分布饼图(环形)
function drawReasonPie() {
  drawPieChart(reasonCanvasRef, reasonStats.value)
}

// ========== 接口调用 ==========
async function fetchLampData() {
  const dtuSn = props.device?._raw?.dtuSn || ''
  const date = formatDate(queryDate.value)
  if (!dtuSn) return
  try {
    const res = await fetch(`/api/device/lampData?dtuSn=${dtuSn}&date=${date}`)
    const data = await res.json()
    // list 中只有一个元素,取其 lampData
    const entry = (data.list && data.list[0]) || {}
    lampData.value = (entry.lampData || []).sort((a, b) =>
      new Date(b.startTime) - new Date(a.startTime)
    )
    // 统计
    const s = data.lampDurationStats || {}
    stats.off = s.off || '0秒'
    stats.red = s.red || '0秒'
    stats.yellow = s.yellow || '0秒'
    stats.green = s.green || '0秒'
    stats.blue = s.blue || '0秒'
  } catch (err) {
    console.error('获取灯数据失败:', err)
  }
}

function statusTagType(status) {
  const map = { '绿灯': '', '黄灯': 'warning', '红灯': 'danger', '蓝灯': '', '灭灯': 'info' }
  return map[status] || ''
}

// 弹窗打开时自动请求
watch(() => props.visible, (val) => {
  if (val) {
    fetchLampData()
    // 等 Vue DOM 更新后获取正确尺寸,再等 dialog 动画结束再次确认
    nextTick(() => {
      updateCanvasSize()
      setTimeout(updateCanvasSize, 350)
    })
  }
})

// 数据或视口变化时重绘
watch([lampData, zoomLevel, viewOffsetX, canvasW], () => {
  nextTick(drawTimeline)
}, { deep: true })

// 饼图数据变化时重绘
watch([stats, lampData], () => {
  nextTick(() => {
    drawDurationPie()
    drawReasonPie()
  })
}, { deep: true })

onMounted(() => {
  updateCanvasSize()
  const el = timelineRef.value
  if (!el) return
  const ro = new ResizeObserver(updateCanvasSize)
  ro.observe(el)
  // 初始绘制饼图
  nextTick(() => { drawDurationPie(); drawReasonPie() })
})
</script>

<style scoped>
.oee-dialog :deep(.el-dialog) {
  max-height: 92vh;
  display: flex;
  flex-direction: column;
}
.oee-dialog :deep(.el-dialog__header) {
  padding: 12px 20px;
  border-bottom: 1px solid #e8e8e8;
  margin: 0;
  flex-shrink: 0;
}
.oee-dialog :deep(.el-dialog__body) {
  overflow-y: auto;
  flex: 1;
}
.dialog-header {
  display: flex;
  align-items: center;
}
.header-left {
  display: flex;
  align-items: center;
  gap: 8px;
}
.title-text {
  font-size: 15px;
  font-weight: bold;
  color: #333;
}
.query-label {
  font-size: 13px;
  color: #666;
  white-space: nowrap;
}

.oee-body { padding: 0; }
.chart-section {
  border-bottom: 1px solid #ebeef5;
  padding: 12px 16px;
}
.section-title {
  font-size: 14px;
  font-weight: bold;
  color: #333;
  margin: 0 0 8px 0;
}
.timeline-chart {
  background: #fff;
  border: 1px solid #e0e0e0;
  border-radius: 4px;
  padding: 6px;
  overflow: hidden;
  position: relative;
}
.timeline-chart canvas {
  display: block;
}

.hover-tooltip {
  position: absolute;
  background: rgba(32, 40, 52, 0.92);
  color: #fff;
  font-size: 12px;
  padding: 10px 14px;
  border-radius: 6px;
  pointer-events: none;
  z-index: 100;
  white-space: nowrap;
  box-shadow: 0 4px 16px rgba(0,0,0,0.25);
  line-height: 1.7;
}
.tip-row { white-space: nowrap; }
.tip-label { color: #aaa; }

.bottom-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 12px;
}
.table-panel {
  border: 1px solid #ebeef5;
  border-radius: 4px;
  overflow: hidden;
}
.panel-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  border-bottom: 1px solid #ebeef5;
  background: #fafafa;
}
.panel-title {
  font-size: 14px;
  font-weight: bold;
  color: #333;
  margin: 0;
}
.panel-actions { display: flex; gap: 8px; }

.chart-panel {
  border: 1px solid #ebeef5;
  border-radius: 4px;
  padding: 16px;
  background: #fafafa;
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: center;
  gap: 56px;
}
.sub-chart {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
  flex: 0 0 auto;
}
.sub-chart .panel-title {
  font-size: 13px;
  font-weight: bold;
  color: #333;
  margin: 0;
}
.legend-list {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
  justify-content: center;
  font-size: 12px;
  color: #666;
}
.legend-item {
  display: flex;
  align-items: center;
  gap: 4px;
}
.dot {
  width: 10px;
  height: 10px;
  border-radius: 50%;
}
.dot.blue { background: #409eff; }
.dot.red { background: #f56c6c; }
.dot.yellow { background: #f5a623; }
.dot.green { background: #67c23a; }
.dot.gray { background: #909399; }

.pie-canvas-wrap {
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
}
.pie-canvas {
  width: 200px;
  height: 200px;
}
.pie-tooltip {
  position: absolute;
  background: rgba(255, 255, 255, 0.96);
  color: #333;
  font-size: 12px;
  padding: 8px 14px;
  border-radius: 6px;
  pointer-events: none;
  z-index: 100;
  box-shadow: 0 2px 12px rgba(0,0,0,0.15);
  border: 1px solid #e4e7ed;
  white-space: nowrap;
}
.pie-tip-title {
  font-weight: bold;
  margin-bottom: 4px;
  color: #333;
  border-bottom: 1px solid #ebeef5;
  padding-bottom: 4px;
}
.pie-tip-row {
  display: flex;
  align-items: center;
  gap: 6px;
}
</style>