SmartLightH5Oee.vue 24.2 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
<template>
  <div class="h5-page">
    <div class="topbar">
      <el-button text @click="goBack">返回</el-button>
      <div class="title">OEE时序</div>
      <div class="spacer"></div>
    </div>

    <div class="content">
      <div class="device">{{ deviceName || '-' }}</div>

      <div class="query">
        <div class="query-left">
          <div class="query-label">日查询</div>
          <el-date-picker
            v-model="queryDate"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="选择日期"
            style="width: 150px;"
            @change="fetchLampData"
          />
        </div>
        <el-button type="primary" :loading="loading" @click="fetchLampData">查询</el-button>
      </div>

      <el-empty v-if="!dtuSn" description="缺少 dtuSn" />

      <template v-else>
        <div class="section">
          <div class="section-title">OEE时序</div>
          <div class="timeline-wrap" ref="timelineRef" @wheel.prevent="onWheel">
            <canvas
              ref="canvasRef"
              :width="canvasW"
              :height="canvasH"
              class="timeline-canvas"
              @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="section">
          <div class="section-title">当日时长分布和异常原因分布</div>
          <div class="charts">
            <div class="chart-card">
              <div class="chart-title">当日时长分布</div>
              <div class="legend">
                <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-wrap">
                <canvas
                  ref="pieCanvasRef"
                  width="280"
                  height="280"
                  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="chart-card">
              <div class="chart-title">异常原因分布</div>
              <div class="legend">
                <div class="legend-item"><span class="dot red"></span>红灯未知原因</div>
                <div class="legend-item"><span class="dot yellow"></span>黄灯未知原因</div>
              </div>
              <div class="pie-wrap">
                <canvas
                  ref="reasonCanvasRef"
                  width="280"
                  height="280"
                  class="pie-canvas"
                  @mousemove="onReasonMouseMove"
                  @mouseleave="reasonHoverItem = null"
                ></canvas>
                <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 class="section">
          <div class="section-title">OEE时序详情</div>
          <el-empty v-if="!loading && tableData.length === 0" description="暂无数据" />
          <div v-else class="detail-list">
            <div v-for="(row, idx) in tableData" :key="idx" class="detail-item">
              <div class="detail-top">
                <div class="detail-time">{{ row.startTime }}</div>
                <el-tag :type="statusTagType(row.statusName)" size="small">{{ row.statusName }}</el-tag>
              </div>
              <div class="detail-row">
                <div class="k">运行时长</div>
                <div class="v">{{ row.durationText }}</div>
              </div>
              <div class="detail-row">
                <div class="k">原因</div>
                <div class="v">{{ row.reason }}</div>
              </div>
              <div class="detail-row">
                <div class="k">操作人</div>
                <div class="v">{{ row.operator }}</div>
              </div>
            </div>
          </div>
        </div>

        
      </template>
    </div>
  </div>
</template>

<script setup>
import { computed, nextTick, onMounted, reactive, ref, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { apiFetch } from '../config/api.js'

const route = useRoute()
const router = useRouter()

const deviceName = computed(() => String(route.query.deviceName || ''))
const dtuSn = computed(() => String(route.query.dtuSn || ''))
const queryDate = ref(new Date().toISOString().slice(0, 10))
const loading = ref(false)

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秒' })

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
}

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())
}

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

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

async function fetchLampData() {
  if (!dtuSn.value) return
  loading.value = true
  try {
    const res = await apiFetch(`/api/device/lampData?dtuSn=${encodeURIComponent(dtuSn.value)}&date=${encodeURIComponent(queryDate.value)}`)
    const data = await res.json()
    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 (e) {
    ElMessage.error('获取OEE数据失败')
    console.warn(e)
  } finally {
    loading.value = false
  }
}

const CANVAS_H = 100
const timelineRef = ref(null)
const canvasRef = ref(null)
const hoverSeg = ref(null)
const tooltipPos = reactive({ x: 0, y: 0 })
const canvasW = ref(320)
const canvasH = ref(CANVAS_H)
const zoomLevel = ref(1)
const viewOffsetX = ref(0)
const minZoom = 0.001
const maxZoom = 1

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
  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
}

const rawSegments = computed(() => {
  if (!lampData.value.length) return []
  const dayStr = queryDate.value || new Date().toISOString().slice(0, 10)
  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)
    }
  })
})

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
  const plotLeft = 55
  const plotW = W - plotLeft - 10
  const barY = 24
  const barH = 46
  const axisY = barY + barH + 8
  const timeLabelY = H - 4

  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)
  let stepSec = 14400
  if (visSpanSec <= 120) stepSec = 30
  else if (visSpanSec <= 300) stepSec = 60
  else if (visSpanSec <= 600) stepSec = 300
  else if (visSpanSec <= 1800) stepSec = 600
  else if (visSpanSec <= 3600) stepSec = 900
  else if (visSpanSec <= 7200) stepSec = 1800
  else if (visSpanSec <= 28800) stepSec = 3600
  else stepSec = 7200

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

  const leftSec = ((vo - plotLeft) / plotW) * totalSec
  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
}

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
  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
  canvasW.value = Math.max(300, timelineRef.value.clientWidth)
  canvasH.value = CANVAS_H
}

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 })
let pieAngleRanges = []
let reasonAngleRanges = []

const stateSeconds = computed(() => ({
  green: parseDurationToSec(stats.green),
  red: parseDurationToSec(stats.red),
  yellow: parseDurationToSec(stats.yellow)
}))

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
  const H = canvas.height
  const cx = W / 2
  const 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()

    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'
      ctx.font = solid ? 'bold 16px sans-serif' : 'bold 14px sans-serif'
      ctx.textAlign = 'center'
      ctx.textBaseline = 'middle'
      ctx.fillText(`${pct}%`, lx, ly - (solid ? 10 : 8))
      ctx.font = solid ? '12px sans-serif' : '12px sans-serif'
      ctx.fillText(item.key, lx, ly + 10)
    }

    startAngle = endAngle
  })
}

function inAngleRange(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)
  const nsa = norm(sa)
  const nea = norm(ea)
  if (nea >= nsa) return na >= nsa && na <= nea
  return na >= nsa || na <= nea
}

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
  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)
    const inRadius = dist <= seg.r && dist >= seg.innerR
    if (!inRadius) continue
    const mouseAngle = Math.atan2(dy, dx)
    if (inAngleRange(mouseAngle, seg.startAngle, seg.endAngle)) {
      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)
  }
}

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)
    if (inAngleRange(mouseAngle, seg.startAngle, seg.endAngle)) {
      found = seg
      break
    }
  }

  if (found || reasonAngleRanges.length > 0) {
    const total = reasonAngleRanges.reduce((s, r) => s + r.sec, 0) || 1
    const pct = ((found ? found.sec / total : 1) * 100).toFixed(2)
    reasonHoverItem.value = found
      ? { rows: [{ key: found.key, sec: found.sec }], pct }
      : { 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)
}

function goBack() {
  if (window.history.length > 1) router.back()
  else router.push({ path: '/smart-light-h5', query: route.query })
}

watch([lampData, zoomLevel, viewOffsetX, canvasW], () => {
  nextTick(drawTimeline)
}, { deep: true })

watch([stats, lampData], () => {
  nextTick(() => {
    drawDurationPie()
    drawReasonPie()
  })
}, { deep: true })

watch([dtuSn, queryDate], () => {
  if (dtuSn.value) fetchLampData()
})

onMounted(() => {
  updateCanvasSize()
  const el = timelineRef.value
  if (el) {
    const ro = new ResizeObserver(updateCanvasSize)
    ro.observe(el)
  }
  nextTick(() => {
    drawDurationPie()
    drawReasonPie()
  })
  if (dtuSn.value) fetchLampData()
})
</script>

<style scoped>
.h5-page {
  min-height: 100vh;
  background-color: #f5f6f8;
}

.topbar {
  position: sticky;
  top: 0;
  z-index: 10;
  height: 48px;
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 0 8px;
  background: #fff;
  border-bottom: 1px solid rgba(0, 0, 0, 0.06);
}

.title {
  flex: 1 1 auto;
  text-align: center;
  font-weight: 700;
  color: #111827;
}

.spacer {
  width: 48px;
}

.content {
  padding: 12px;
}

.device {
  font-size: 14px;
  font-weight: 700;
  color: #0f172a;
  margin-bottom: 10px;
  word-break: break-all;
}

.query {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 10px;
  margin-bottom: 10px;
}

.query-left {
  display: flex;
  align-items: center;
  gap: 8px;
}

.query-label {
  font-size: 12px;
  color: #64748b;
}

.section {
  background: #fff;
  border-radius: 12px;
  padding: 12px;
  box-shadow: 0 1px 2px rgba(15, 23, 42, 0.06);
  margin-top: 10px;
}

.section-title {
  font-weight: 700;
  color: #0f172a;
  font-size: 14px;
  margin-bottom: 10px;
}

.timeline-wrap {
  position: relative;
  padding: 6px;
  border: 1px solid rgba(0, 0, 0, 0.06);
  border-radius: 10px;
  overflow: hidden;
  background: #fff;
}

.timeline-canvas {
  width: 100%;
  height: 100px;
  display: block;
}

.hover-tooltip {
  position: absolute;
  width: 180px;
  padding: 8px 10px;
  background: rgba(17, 24, 39, 0.92);
  color: #fff;
  font-size: 12px;
  border-radius: 10px;
  pointer-events: none;
}

.tip-row {
  line-height: 1.45;
}

.tip-label {
  opacity: 0.85;
}

.detail-list {
  display: grid;
  gap: 10px;
}

.detail-item {
  border: 1px solid rgba(0, 0, 0, 0.06);
  border-radius: 12px;
  padding: 10px;
}

.detail-top {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 10px;
  margin-bottom: 6px;
}

.detail-time {
  font-weight: 700;
  color: #0f172a;
  font-size: 13px;
}

.detail-row {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 12px;
  font-size: 12px;
  padding-top: 4px;
}

.detail-row .k {
  color: #64748b;
}

.detail-row .v {
  color: #0f172a;
  font-weight: 600;
}

.charts {
  display: grid;
  gap: 12px;
}

.chart-card {
  border: 1px solid rgba(0, 0, 0, 0.06);
  border-radius: 12px;
  padding: 10px;
}

.chart-title {
  font-weight: 700;
  color: #0f172a;
  font-size: 13px;
  margin-bottom: 8px;
}

.legend {
  display: flex;
  gap: 12px;
  flex-wrap: wrap;
  color: #475569;
  font-size: 12px;
  margin-bottom: 8px;
}

.legend-item {
  display: inline-flex;
  align-items: center;
  gap: 6px;
}

.dot {
  width: 10px;
  height: 10px;
  border-radius: 999px;
}

.dot.green {
  background: #67c23a;
}

.dot.red {
  background: #f56c6c;
}

.dot.yellow {
  background: #f5a623;
}

.pie-wrap {
  position: relative;
  display: flex;
  justify-content: center;
}

.pie-canvas {
  width: 240px;
  height: 240px;
}

.pie-tooltip {
  position: absolute;
  min-width: 160px;
  padding: 8px 10px;
  background: rgba(17, 24, 39, 0.92);
  color: #fff;
  font-size: 12px;
  border-radius: 10px;
  pointer-events: none;
}

.pie-tip-title {
  font-weight: 700;
  margin-bottom: 6px;
}

.pie-tip-row {
  display: flex;
  align-items: center;
  gap: 6px;
  line-height: 1.45;
}

.pie-tip-row .dot {
  width: 8px;
  height: 8px;
}
</style>