EnergyH5RunStatus.vue 26.4 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
<template>
  <div class="h5-page">
    <div class="topbar">
      <el-button text @click="goBack">返回</el-button>
      <div class="title">运行状态</div>
      <div class="spacer"></div>
    </div>

    <div class="content">
      <div class="device">{{ deviceName || '-' }}</div>
      <el-empty v-if="!dtuSn" description="缺少 dtuSn" />

      <template v-else>
        <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;"
              :disabled-date="disabledDateFuture"
              @change="fetchData"
            />
          </div>
          <el-button type="primary" size="small" :loading="loading" @click="fetchData">查询</el-button>
        </div>

        <div class="section">
          <div class="section-title">
            设备运行状态图
            <span class="leg"><i class="dot g"></i>运行</span>
            <span class="leg"><i class="dot r"></i>停机</span>
            <span class="leg"><i class="dot y"></i>待机</span>
            <span class="leg"><i class="dot gy"></i>离线</span>
          </div>
          <div
            ref="timelineWrapRef"
            class="timeline-wrap"
            @wheel.prevent="onTimelineWheel"
            @pointerdown="onTimelinePointerDown"
            @pointermove="onTimelinePointerMove"
            @pointerup="onTimelinePointerUp"
            @pointercancel="onTimelinePointerUp"
            @pointerleave="onTimelinePointerLeave"
          >
            <canvas ref="timelineCanvasRef" class="timeline-canvas"></canvas>
          </div>
          <div v-if="timelineSelected.show" class="tip-card">
            <div class="tip-title">{{ timelineSelected.statusLabel }}</div>
            <div class="tip-line">开始时间 {{ timelineSelected.startTime }}</div>
            <div class="tip-line">结束时间 {{ timelineSelected.endTime }}</div>
            <div class="tip-line">持续时长 {{ timelineSelected.duration }}</div>
          </div>
        </div>

        <div class="section">
          <div class="section-title">设备用电量</div>
          <div class="subline">总用电量:{{ totalKwh.toFixed(2) }} kw·h</div>
          <div class="bar-scroll">
            <div ref="barWrapRef" class="bar-wrap">
              <canvas
                ref="barCanvasRef"
                class="bar-canvas"
                @pointerdown="onBarPointerDown"
                @pointermove="onBarPointerMove"
                @pointerup="onBarPointerUp"
                @pointercancel="onBarPointerUp"
                @pointerleave="onBarPointerLeave"
              ></canvas>
            </div>
          </div>
          <div v-if="barSelected.show" class="tip-card">
            <div class="tip-title">{{ barSelected.hour }}时</div>
            <div class="tip-line">用电量 {{ barSelected.value }} kw·h</div>
          </div>
        </div>

        <div class="section">
          <div class="section-title">设备运行状态明细</div>
          <div class="pie-box">
            <div ref="pieWrapRef" class="pie-wrap">
              <canvas
                ref="pieCanvasRef"
                class="pie-canvas"
                @pointerdown="onPieTap"
              ></canvas>
            </div>
            <div class="pie-stats">
              <div class="stat-row">
                <div class="stat-k">总时长</div>
                <div class="stat-v">{{ totalDurationFormatted || '-' }}</div>
              </div>
              <div class="stat-row">
                <div class="stat-k">总用电量</div>
                <div class="stat-v">{{ totalKwh.toFixed(2) }} kw·h</div>
              </div>
            </div>
          </div>
          <div v-if="pieSelected.show" class="tip-card" style="margin-top: 10px;">
            <div class="tip-title">{{ pieSelected.statusLabel }}</div>
            <div class="tip-line">占比 {{ pieSelected.percent }}%</div>
          </div>
          <el-empty v-if="!loading && oeeList.length === 0" description="暂无数据" />
          <div v-else class="detail-list">
            <div v-for="(item, idx) in oeeList" :key="idx" class="detail-item">
              <div class="d-row">
                <div class="d-k">开始</div>
                <div class="d-v">{{ formatTime(item.startTime) }}</div>
              </div>
              <div class="d-row">
                <div class="d-k">结束</div>
                <div class="d-v">{{ formatTime(item.endTime) }}</div>
              </div>
              <div class="d-row">
                <div class="d-k">状态</div>
                <div class="d-v">
                  <span class="d-status">
                    <i :class="['dot', statusDotClass(item.runStatus)]"></i>
                    {{ statusLabel(item.runStatus) }}
                  </span>
                </div>
              </div>
              <div class="d-row">
                <div class="d-k">时长</div>
                <div class="d-v">{{ formatDuration(item.duration) }}</div>
              </div>
            </div>
          </div>
        </div>
      </template>
    </div>
  </div>
</template>

<script setup>
import { computed, nextTick, onBeforeUnmount, onMounted, ref } 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 dtuSn = computed(() => String(route.query.dtuSn || ''))
const deviceName = computed(() => String(route.query.deviceName || ''))

function goBack() {
  router.back()
}

const queryDate = ref(new Date().toISOString().slice(0, 10))
const loading = ref(false)

const oeeList = ref([])
const kwhList = ref([])
const totalKwh = ref(0)
const statusStats = ref([])
const totalDurationFormatted = ref('')

function disabledDateFuture(time) {
  return time.getTime() > Date.now()
}

const STATUS_MAP = { 0: '离线', 1: '停机', 2: '运行', 3: '待机' }
const STATUS_COLORS = { 0: '#909399', 1: '#e74c3c', 2: '#67c23a', 3: '#c5d94e' }
function statusLabel(s) {
  return STATUS_MAP[Number(s)] || '未知'
}
function statusDotClass(s) {
  return { 0: 'gy', 1: 'r', 2: 'g', 3: 'y' }[Number(s)] || 'gy'
}

function formatDuration(seconds) {
  if (!seconds && seconds !== 0) return '0秒'
  seconds = Number(seconds)
  if (seconds <= 0) return '0秒'
  const h = Math.floor(seconds / 3600)
  const m = Math.floor((seconds % 3600) / 60)
  const s = Math.floor(seconds % 60)
  let str = ''
  if (h > 0) str += h + '时'
  if (m > 0) str += m + '分'
  if (s > 0 || !str) str += s + '秒'
  return str
}

function formatTime(ts) {
  if (!ts) return '-'
  const d = new Date(String(ts).replace(/-/g, '/'))
  if (Number.isNaN(d.getTime())) return String(ts).slice(0, 19)
  return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')} ${String(d.getHours()).padStart(2, '0')}:${String(
    d.getMinutes()
  ).padStart(2, '0')}:${String(d.getSeconds()).padStart(2, '0')}`
}

async function fetchData() {
  if (!dtuSn.value || !queryDate.value) return
  loading.value = true
  try {
    const res = await apiFetch(`/api/energy/detail?dtuSn=${encodeURIComponent(dtuSn.value)}&date=${encodeURIComponent(queryDate.value)}`)
    const data = await res.json()
    if (data?.code !== 200) throw new Error('bad response')
    oeeList.value = data?.oeeData?.list || []
    statusStats.value = data?.oeeData?.statusStats || []
    totalDurationFormatted.value = data?.oeeData?.totalDurationFormatted || ''
    kwhList.value = data?.kwhData?.list || []
    totalKwh.value = Number(data?.kwhData?.totalKwh || 0)
    timelineSelected.value.show = false
    barSelected.value.show = false
    pieSelected.value.show = false
    zoomLevel.value = 1
    viewOffsetX.value = 0
    await nextTick()
    drawAll()
  } catch (e) {
    ElMessage.error('获取数据失败')
    console.warn(e)
  } finally {
    loading.value = false
  }
}

const dpr = window.devicePixelRatio || 1
function setupCanvas(canvas, cssW, cssH) {
  canvas.style.width = cssW + 'px'
  canvas.style.height = cssH + 'px'
  canvas.width = Math.round(cssW * dpr)
  canvas.height = Math.round(cssH * dpr)
  const ctx = canvas.getContext('2d')
  ctx.setTransform(dpr, 0, 0, dpr, 0, 0)
  return { ctx, W: cssW, H: cssH }
}

const timelineCanvasRef = ref(null)
const timelineWrapRef = ref(null)
const barCanvasRef = ref(null)
const barWrapRef = ref(null)
const pieCanvasRef = ref(null)
const pieWrapRef = ref(null)

const zoomLevel = ref(1)
const viewOffsetX = ref(0)
let timelineRects = []
let barRects = []

const timelineSelected = ref({
  show: false,
  startTime: '',
  endTime: '',
  statusLabel: '',
  duration: ''
})
const barSelected = ref({ show: false, hour: '', value: '' })
const pieSelected = ref({ show: false, status: -1, statusLabel: '', percent: '0.00' })

function clamp(v, min, max) {
  return Math.max(min, Math.min(max, v))
}

function getDayBounds() {
  const dateStr = queryDate.value || ''
  const start = dateStr ? new Date(dateStr) : new Date()
  start.setHours(0, 0, 0, 0)
  const end = new Date(start)
  end.setHours(23, 59, 59, 999)
  return { startMs: start.getTime(), endMs: end.getTime() + 1 }
}

function parseTimeMs(v) {
  if (!v) return NaN
  const d = new Date(String(v).replace(/-/g, '/'))
  return d.getTime()
}

function buildSegments() {
  const { startMs } = getDayBounds()
  return (oeeList.value || [])
    .map((item, idx) => {
      const sMs = parseTimeMs(item.startTime)
      const eMs = parseTimeMs(item.endTime)
      const durSec = Number(item.duration || 0)
      const startMs2 = Number.isFinite(sMs) ? sMs : NaN
      let endMs2 = Number.isFinite(eMs) ? eMs : NaN
      if (!Number.isFinite(endMs2) && Number.isFinite(startMs2) && durSec > 0) endMs2 = startMs2 + durSec * 1000
      if (!Number.isFinite(startMs2) || !Number.isFinite(endMs2)) return null
      const startSec = clamp((startMs2 - startMs) / 1000, 0, 86400)
      const endSec = clamp((endMs2 - startMs) / 1000, 0, 86400)
      const st = Number(item.runStatus ?? 0)
      return {
        index: idx,
        startSec,
        endSec: Math.max(startSec, endSec),
        runStatus: st,
        startTime: item.startTime,
        endTime: item.endTime,
        duration: formatDuration(item.duration)
      }
    })
    .filter(Boolean)
}

function drawTimeline() {
  const canvas = timelineCanvasRef.value
  const wrap = timelineWrapRef.value
  if (!canvas || !wrap) return
  const cssW = Math.max(320, wrap.clientWidth)
  const cssH = 140
  const { ctx, W, H } = setupCanvas(canvas, cssW, cssH)
  ctx.clearRect(0, 0, W, H)

  const PAD_L = 10
  const PAD_R = 10
  const PAD_T = 26
  const PAD_B = 26
  const plotW = W - PAD_L - PAD_R
  const plotH = H - PAD_T - PAD_B

  ctx.fillStyle = '#64748b'
  ctx.font = '10px sans-serif'
  ctx.textAlign = 'center'
  ctx.textBaseline = 'middle'
  for (let i = 0; i <= 6; i++) {
    const hour = i * 4
    const x = PAD_L + (plotW * i) / 6
    ctx.fillText(String(hour).padStart(2, '0') + ':00', x, 12)
    if (i > 0) {
      ctx.strokeStyle = 'rgba(0,0,0,0.06)'
      ctx.beginPath()
      ctx.moveTo(x, PAD_T)
      ctx.lineTo(x, PAD_T + plotH)
      ctx.stroke()
    }
  }

  const z = zoomLevel.value
  const maxOffset = Math.max(0, plotW * (z - 1))
  viewOffsetX.value = clamp(viewOffsetX.value, 0, maxOffset)
  const vo = viewOffsetX.value

  ctx.fillStyle = 'rgba(15,23,42,0.04)'
  ctx.fillRect(PAD_L, PAD_T, plotW, plotH)

  const segs = buildSegments()
  timelineRects = []
  const barY = PAD_T + 14
  const barH = plotH - 28

  segs.forEach(seg => {
    const sx = PAD_L + (seg.startSec / 86400) * plotW * z - vo
    const ex = PAD_L + (seg.endSec / 86400) * plotW * z - vo
    const w = Math.max(1, ex - sx)
    if (sx > PAD_L + plotW || sx + w < PAD_L) return
    const x = clamp(sx, PAD_L, PAD_L + plotW)
    const w2 = clamp(sx + w, PAD_L, PAD_L + plotW) - x
    ctx.fillStyle = STATUS_COLORS[seg.runStatus] || '#909399'
    ctx.fillRect(x, barY, w2, barH)
    timelineRects.push({ x, y: barY, w: w2, h: barH, seg })
  })

  ctx.strokeStyle = 'rgba(0,0,0,0.08)'
  ctx.strokeRect(PAD_L, barY, plotW, barH)

  if (z > 1) {
    const ratio = vo / maxOffset
    const trackY = H - 12
    const trackW = plotW
    const thumbW = Math.max(40, trackW / z)
    const thumbX = PAD_L + (trackW - thumbW) * ratio
    ctx.fillStyle = 'rgba(148,163,184,0.35)'
    ctx.fillRect(PAD_L, trackY, trackW, 4)
    ctx.fillStyle = 'rgba(100,116,139,0.55)'
    ctx.fillRect(thumbX, trackY, thumbW, 4)
  }
}

let tlPointerDown = false
let tlStartX = 0
let tlStartOffset = 0
let tlMoved = false

function onTimelinePointerDown(e) {
  tlPointerDown = true
  tlMoved = false
  tlStartX = e.clientX
  tlStartOffset = viewOffsetX.value
  e.currentTarget.setPointerCapture?.(e.pointerId)
}

function onTimelinePointerMove(e) {
  if (!tlPointerDown) return
  const dx = e.clientX - tlStartX
  if (Math.abs(dx) > 3) tlMoved = true
  const wrap = timelineWrapRef.value
  if (!wrap) return
  const cssW = Math.max(320, wrap.clientWidth)
  const plotW = cssW - 20
  const z = zoomLevel.value
  const maxOffset = Math.max(0, plotW * (z - 1))
  viewOffsetX.value = clamp(tlStartOffset - dx, 0, maxOffset)
  drawTimeline()
}

function onTimelinePointerUp(e) {
  if (!tlPointerDown) return
  tlPointerDown = false
  if (!tlMoved) {
    const rect = e.currentTarget.getBoundingClientRect()
    const mx = e.clientX - rect.left
    const my = e.clientY - rect.top
    const hit = timelineRects.find(r => mx >= r.x && mx <= r.x + r.w && my >= r.y && my <= r.y + r.h)
    if (hit) {
      timelineSelected.value = {
        show: true,
        startTime: formatTime(hit.seg.startTime),
        endTime: formatTime(hit.seg.endTime),
        statusLabel: statusLabel(hit.seg.runStatus),
        duration: hit.seg.duration
      }
    } else {
      timelineSelected.value = { show: false, startTime: '', endTime: '', statusLabel: '', duration: '' }
    }
  }
  e.currentTarget.releasePointerCapture?.(e.pointerId)
}

function onTimelinePointerLeave() {
  tlPointerDown = false
}

function onTimelineWheel(e) {
  const wrap = timelineWrapRef.value
  if (!wrap) return
  const cssW = Math.max(320, wrap.clientWidth)
  const plotW = cssW - 20
  const oldZ = zoomLevel.value
  const delta = e.deltaY > 0 ? -0.15 : 0.15
  const nextZ = clamp(oldZ + delta, 1, 6)
  if (nextZ === oldZ) return
  const maxOffsetOld = Math.max(0, plotW * (oldZ - 1))
  const anchor = maxOffsetOld > 0 ? viewOffsetX.value / maxOffsetOld : 0
  zoomLevel.value = nextZ
  const maxOffsetNew = Math.max(0, plotW * (nextZ - 1))
  viewOffsetX.value = clamp(anchor * maxOffsetNew, 0, maxOffsetNew)
  drawTimeline()
}

function drawBars() {
  const canvas = barCanvasRef.value
  const wrap = barWrapRef.value
  if (!canvas || !wrap) return
  const list = kwhList.value || []
  const PAD_L = 34
  const PAD_R = 16
  const PAD_T = 18
  const PAD_B = 34
  const colW = 12
  const gap = 6
  const baseW = Math.max(320, wrap.clientWidth)
  const cssW = Math.max(baseW, PAD_L + PAD_R + list.length * (colW + gap) + gap)
  const cssH = 220
  const { ctx, W, H } = setupCanvas(canvas, cssW, cssH)
  ctx.clearRect(0, 0, W, H)

  const plotW = W - PAD_L - PAD_R
  const plotH = H - PAD_T - PAD_B
  const maxVal = Math.max(1, ...list.map(i => Number(i.value || 0)))

  ctx.strokeStyle = 'rgba(0,0,0,0.06)'
  ctx.lineWidth = 1
  ctx.fillStyle = '#94a3b8'
  ctx.font = '10px sans-serif'
  ctx.textAlign = 'end'
  for (let i = 0; i <= 4; i++) {
    const v = (maxVal * i) / 4
    const y = PAD_T + plotH * (1 - i / 4)
    ctx.fillText(v.toFixed(1), PAD_L - 4, y + 3)
    if (i > 0) {
      ctx.beginPath()
      ctx.moveTo(PAD_L, y)
      ctx.lineTo(W - PAD_R, y)
      ctx.stroke()
    }
  }

  ctx.strokeStyle = 'rgba(0,0,0,0.08)'
  ctx.lineWidth = 1.5
  ctx.beginPath()
  ctx.moveTo(PAD_L, PAD_T + plotH)
  ctx.lineTo(W - PAD_R, PAD_T + plotH)
  ctx.stroke()

  barRects = []
  list.forEach((item, idx) => {
    const val = Number(item.value || 0)
    const h = (val / maxVal) * plotH
    const x = PAD_L + gap + idx * (colW + gap)
    const y = PAD_T + plotH - h
    const isSel = barSelected.value.show && Number(barSelected.value.hour) === idx + 1
    ctx.fillStyle = isSel ? 'rgba(64,158,255,0.9)' : 'rgba(64,158,255,0.55)'
    ctx.fillRect(x, y, colW, h)
    if ((idx + 1) % 3 === 0 || idx === 0 || idx === list.length - 1) {
      ctx.save()
      ctx.fillStyle = '#64748b'
      ctx.font = '9px sans-serif'
      ctx.textAlign = 'center'
      ctx.translate(x + colW / 2, PAD_T + plotH + 14)
      ctx.fillText(String(idx + 1), 0, 0)
      ctx.restore()
    }
    barRects.push({ x, y, w: colW, h, idx, val })
  })
}

let pieRanges = []
function buildPieSlices() {
  const stats = statusStats.value || []
  if (!stats.length) return []
  const totalPct = stats.reduce((sum, s) => sum + (Number(s.percent) || 0), 0)
  const MIN_SLICE_DEG = 2
  const sliceInfos = stats.map((s, i) => {
    const pct = Number(s.percent) || 0
    const deg = pct > 0 && totalPct > 0 ? (pct / totalPct) * 360 : MIN_SLICE_DEG
    return { index: i, status: Number(s.status), percent: pct, deg }
  })
  const hasNonZero = sliceInfos.some(si => si.percent > 0)
  if (!hasNonZero && sliceInfos.length > 0) {
    const eq = 360 / sliceInfos.length
    sliceInfos.forEach(si => (si.deg = eq))
  } else if (hasNonZero) {
    const usedByNonZero = sliceInfos.filter(si => si.percent > 0).reduce((s, si) => s + si.deg, 0)
    const zeroCount = sliceInfos.filter(si => si.percent === 0).length
    const remaining = Math.max(0, 360 - usedByNonZero - zeroCount * MIN_SLICE_DEG)
    sliceInfos.forEach(si => {
      if (si.percent > 0) si.deg = si.deg + (si.deg / usedByNonZero) * remaining
    })
  }
  let startAngle = -Math.PI / 2
  sliceInfos.forEach(si => {
    const sliceAngle = (si.deg / 180) * Math.PI
    si.startAngle = startAngle
    si.endAngle = startAngle + sliceAngle
    si.midAngle = startAngle + sliceAngle / 2
    startAngle = si.endAngle
  })
  return sliceInfos
}

function drawPie() {
  const canvas = pieCanvasRef.value
  const wrap = pieWrapRef.value
  if (!canvas || !wrap) return
  const cssW = Math.max(320, wrap.clientWidth)
  const cssH = 240
  const { ctx, W, H } = setupCanvas(canvas, cssW, cssH)
  ctx.clearRect(0, 0, W, H)

  const slices = buildPieSlices()
  pieRanges = []
  if (!slices.length) {
    ctx.fillStyle = '#999'
    ctx.font = '13px sans-serif'
    ctx.textAlign = 'center'
    ctx.textBaseline = 'middle'
    ctx.fillText('暂无数据', W / 2, H / 2)
    return
  }

  const cx = W * 0.42
  const cy = H * 0.54
  const radius = Math.min(cx, cy) - 18
  slices.forEach(si => {
    pieRanges.push({ ...si, cx, cy, radius })
  })

  const selectedStatus = pieSelected.value.show ? pieSelected.value.status : -999
  slices.forEach(si => {
    if (si.status === selectedStatus) return
    ctx.beginPath()
    ctx.moveTo(cx, cy)
    ctx.arc(cx, cy, radius, si.startAngle, si.endAngle)
    ctx.closePath()
    ctx.fillStyle = STATUS_COLORS[si.status] || '#ccc'
    ctx.globalAlpha = 0.85
    ctx.fill()
    ctx.globalAlpha = 1
  })

  const sel = slices.find(s => s.status === selectedStatus)
  if (sel) {
    const expandR = radius + 6
    const offset = 6
    const ox = cx + Math.cos(sel.midAngle) * offset
    const oy = cy + Math.sin(sel.midAngle) * offset
    ctx.save()
    ctx.shadowColor = 'rgba(0,0,0,0.25)'
    ctx.shadowBlur = 12
    ctx.shadowOffsetY = 3
    ctx.beginPath()
    ctx.moveTo(ox, oy)
    ctx.arc(ox, oy, expandR, sel.startAngle, sel.endAngle)
    ctx.closePath()
    ctx.fillStyle = STATUS_COLORS[sel.status] || '#ccc'
    ctx.fill()
    ctx.restore()
  }

  slices.forEach(si => {
    const { midAngle } = si
    const lineStartX = cx + Math.cos(midAngle) * radius
    const lineStartY = cy + Math.sin(midAngle) * radius
    const elbowLen = 12
    const elbowX = cx + Math.cos(midAngle) * (radius + elbowLen)
    const elbowY = cy + Math.sin(midAngle) * (radius + elbowLen)
    const leftSide = midAngle > Math.PI / 2 && midAngle <= Math.PI * 1.5
    const textDir = leftSide ? -1 : 1
    const textLen = 34
    const lineEndX = elbowX + textDir * textLen
    const lineEndY = elbowY

    ctx.strokeStyle = 'rgba(0,0,0,0.25)'
    ctx.lineWidth = 0.8
    ctx.beginPath()
    ctx.moveTo(lineStartX, lineStartY)
    ctx.lineTo(elbowX, elbowY)
    ctx.lineTo(lineEndX, lineEndY)
    ctx.stroke()

    const labelText = `${statusLabel(si.status)}${si.percent.toFixed(si.percent % 1 === 0 ? 0 : 2)}%`
    ctx.fillStyle = '#475569'
    ctx.font = '11px sans-serif'
    ctx.textAlign = leftSide ? 'right' : 'left'
    ctx.textBaseline = 'middle'
    ctx.fillText(labelText, lineEndX + textDir * 4, lineEndY)
  })
}

function onPieTap(e) {
  const canvas = pieCanvasRef.value
  if (!canvas || !pieRanges.length) return
  const rect = canvas.getBoundingClientRect()
  const mx = e.clientX - rect.left
  const my = e.clientY - rect.top
  const first = pieRanges[0]
  const cx = first.cx
  const cy = first.cy
  const dx = mx - cx
  const dy = my - cy
  const dist = Math.sqrt(dx * dx + dy * dy)
  if (dist > first.radius) {
    pieSelected.value = { show: false, status: -1, statusLabel: '', percent: '0.00' }
    drawPie()
    return
  }
  let angle = Math.atan2(dy, dx)
  const inRange = (a, sa, ea) => {
    let na = a - sa
    let nea = ea - sa
    if (nea < 0) nea += Math.PI * 2
    if (na < 0) na += Math.PI * 2
    return na >= 0 && na <= nea
  }
  const hit = [...pieRanges].reverse().find(seg => inRange(angle, seg.startAngle, seg.endAngle))
  if (!hit) {
    pieSelected.value = { show: false, status: -1, statusLabel: '', percent: '0.00' }
  } else {
    pieSelected.value = {
      show: true,
      status: hit.status,
      statusLabel: statusLabel(hit.status),
      percent: (hit.percent || 0).toFixed(2)
    }
  }
  drawPie()
}

let barPointerDown = false
let barMoved = false
let barStartX = 0
let barStartScrollLeft = 0

function onBarPointerDown(e) {
  barPointerDown = true
  barMoved = false
  barStartX = e.clientX
  barStartScrollLeft = e.currentTarget.parentElement?.scrollLeft || 0
  e.currentTarget.setPointerCapture?.(e.pointerId)
}

function onBarPointerMove(e) {
  if (!barPointerDown) return
  const dx = e.clientX - barStartX
  if (Math.abs(dx) > 3) barMoved = true
  const scroller = e.currentTarget.parentElement
  if (scroller && barMoved) scroller.scrollLeft = barStartScrollLeft - dx
}

function onBarPointerUp(e) {
  if (!barPointerDown) return
  barPointerDown = false
  if (!barMoved) {
    const rect = e.currentTarget.getBoundingClientRect()
    const mx = e.clientX - rect.left
    const my = e.clientY - rect.top
    const hit = barRects.find(r => mx >= r.x && mx <= r.x + r.w && my >= r.y && my <= r.y + r.h)
    if (hit) {
      barSelected.value = { show: true, hour: String(hit.idx + 1), value: (hit.val || 0).toFixed(2) }
    } else {
      barSelected.value = { show: false, hour: '', value: '' }
    }
    drawBars()
  }
  e.currentTarget.releasePointerCapture?.(e.pointerId)
}

function onBarPointerLeave() {
  barPointerDown = false
}

function drawAll() {
  drawTimeline()
  drawBars()
  drawPie()
}

let ro = null
onMounted(() => {
  fetchData()
  if ('ResizeObserver' in window) {
    ro = new ResizeObserver(() => drawAll())
    if (timelineWrapRef.value) ro.observe(timelineWrapRef.value)
    if (barWrapRef.value) ro.observe(barWrapRef.value)
    if (pieWrapRef.value) ro.observe(pieWrapRef.value)
  }
})

onBeforeUnmount(() => {
  if (ro) {
    ro.disconnect()
    ro = null
  }
})
</script>

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

.topbar {
  position: sticky;
  top: 0;
  z-index: 10;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 10px 12px;
  background: #fff;
  border-bottom: 1px solid rgba(0, 0, 0, 0.06);
}

.title {
  font-weight: 700;
  color: #0f172a;
}

.spacer {
  width: 48px;
}

.content {
  padding: 12px;
}

.device {
  font-weight: 700;
  color: #0f172a;
  margin-bottom: 10px;
}

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

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

.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-bottom: 10px;
}

.section-title {
  font-weight: 700;
  color: #0f172a;
  font-size: 14px;
  margin-bottom: 8px;
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 10px;
}

.leg {
  display: inline-flex;
  align-items: center;
  gap: 6px;
  font-weight: 500;
  color: #475569;
  font-size: 12px;
}

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

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

.dot.r {
  background: #e74c3c;
}

.dot.y {
  background: #c5d94e;
}

.dot.gy {
  background: #909399;
}

.timeline-wrap {
  border-radius: 10px;
  overflow: hidden;
  background: rgba(15, 23, 42, 0.02);
  touch-action: pan-y;
}

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

.subline {
  font-size: 12px;
  color: #64748b;
  margin-bottom: 8px;
}

.bar-scroll {
  overflow-x: auto;
  -webkit-overflow-scrolling: touch;
  touch-action: pan-x;
}

.bar-wrap {
  min-width: 100%;
}

.bar-canvas {
  height: 220px;
  display: block;
}

.tip-card {
  margin-top: 10px;
  border-radius: 12px;
  padding: 10px 12px;
  background: rgba(64, 158, 255, 0.06);
  border: 1px solid rgba(64, 158, 255, 0.18);
}

.tip-title {
  font-weight: 700;
  color: #0f172a;
  margin-bottom: 6px;
}

.tip-line {
  font-size: 12px;
  color: #334155;
  line-height: 1.6;
}

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

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

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

.d-k {
  color: #64748b;
}

.d-v {
  color: #0f172a;
  font-weight: 600;
  text-align: right;
}

.d-status {
  display: inline-flex;
  align-items: center;
  gap: 6px;
  font-weight: 600;
}

.pie-box {
  display: grid;
  grid-template-columns: 1fr;
  gap: 10px;
  align-items: center;
}

.pie-wrap {
  width: 100%;
}

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

.pie-stats {
  display: grid;
  grid-template-columns: repeat(2, minmax(0, 1fr));
  gap: 10px;
}

.stat-row {
  background: #f8fafc;
  border: 1px solid rgba(0, 0, 0, 0.06);
  border-radius: 10px;
  padding: 10px;
}

.stat-k {
  font-size: 12px;
  color: #64748b;
}

.stat-v {
  margin-top: 6px;
  font-size: 14px;
  font-weight: 800;
  color: #0f172a;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
</style>