SmartLightH5UtilizationTab.vue 23.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
<template>
  <div class="util-h5">
    <div class="toolbar">
      <div class="left">
        <el-radio-group v-model="utilQueryMode" size="small" @change="onModeChange">
          <el-radio-button value="day">日查询</el-radio-button>
          <el-radio-button value="week">周查询</el-radio-button>
          <el-radio-button value="month">月查询</el-radio-button>
        </el-radio-group>
      </div>
      <el-button type="primary" size="small" :loading="utilLoading" @click="fetchUtilData">查询</el-button>
    </div>

    <div class="toolbar" style="margin-top: 8px;">
      <div class="left">
        <el-date-picker
          v-if="utilQueryMode === 'day'"
          v-model="utilDate"
          type="date"
          placeholder="选择日期"
          size="small"
          value-format="YYYY-MM-DD"
          :disabled-date="disabledDateFuture"
          style="width: 160px;"
          @change="fetchUtilData"
        />
        <el-date-picker
          v-else-if="utilQueryMode === 'week'"
          v-model="utilWeekDate"
          type="date"
          :format="utilWeekDisplayFormat"
          placeholder="选择周"
          size="small"
          value-format="YYYY-MM-DD"
          :disabled-date="disableNonMonday"
          style="width: 160px;"
          @change="fetchUtilData"
        />
        <el-date-picker
          v-else
          v-model="utilMonthDate"
          type="month"
          placeholder="选择月份"
          size="small"
          value-format="YYYY-MM"
          style="width: 140px;"
          @change="fetchUtilData"
        />
      </div>
    </div>

    <div class="section">
      <div class="section-title">总时长</div>
      <div class="legend-total">
        <div v-for="(seg, i) in utilTotalSegments" :key="i" class="legend-total-item">
          <div class="lt-left">
            <span class="dot" :style="{ background: seg.color }"></span>
            <span class="name">{{ seg.label }}</span>
          </div>
          <div class="lt-right">
            <div class="val">{{ seg.duration }}</div>
            <div class="pct">{{ seg.pct }}</div>
          </div>
        </div>
      </div>
      <div ref="pieTotalWrapRef" class="pie-wrap">
        <canvas ref="pieTotalRef" class="pie-canvas"></canvas>
      </div>
    </div>

    <div class="section">
      <div class="section-title">稼动率</div>
      <div class="subline">稼动率:{{ utilData.availabilityRate || '0%' }}</div>
      <div ref="pieRateWrapRef" class="pie-wrap">
        <canvas ref="pieRateRef" class="pie-canvas"></canvas>
      </div>
    </div>

    <div class="section">
      <div class="section-title">当前机台运行状态</div>
      <div class="legend">
        <div class="legend-item">
          <span class="dot" style="background:#67c23a"></span><span class="name">绿灯</span><span class="val">{{ utilData.currentStatus.green || 0 }}台</span>
        </div>
        <div class="legend-item">
          <span class="dot" style="background:#e6a23c"></span><span class="name">黄灯</span><span class="val">{{ utilData.currentStatus.yellow || 0 }}台</span>
        </div>
        <div class="legend-item">
          <span class="dot" style="background:#f56c6c"></span><span class="name">红灯</span><span class="val">{{ utilData.currentStatus.red || 0 }}台</span>
        </div>
        <div class="legend-item">
          <span class="dot" style="background:#909399"></span><span class="name">灭灯</span><span class="val">{{ utilData.currentStatus.off || 0 }}台</span>
        </div>
      </div>
      <div ref="pieStatusWrapRef" class="pie-wrap">
        <canvas ref="pieStatusRef" class="pie-canvas"></canvas>
      </div>
    </div>

    <div class="section">
      <div class="section-title">异常机台排名</div>
      <div class="subline">黄灯 + 红灯时长</div>
      <div ref="abnormalWrapRef" class="chart-wrap">
        <canvas ref="abnormalRef" class="chart-canvas"></canvas>
      </div>
      <el-empty v-if="!utilLoading && abnormalList.length === 0" description="暂无异常数据" />
    </div>

    <div class="section">
      <div class="section-title">排序</div>
      <div class="stack-toolbar">
        <el-radio-group v-model="sortMode" size="small" @change="redrawStackBar">
          <el-radio-button value="duration">绿灯时长</el-radio-button>
          <el-radio-button value="rate">稼动率</el-radio-button>
        </el-radio-group>
      </div>
      <div class="stack-legend">
        <span class="leg"><i class="dot" style="background:#67c23a"></i>绿灯</span>
        <span class="leg"><i class="dot" style="background:#e6a23c"></i>黄灯</span>
        <span class="leg"><i class="dot" style="background:#f56c6c"></i>红灯</span>
        <span class="leg"><i class="dot" style="background:#909399"></i>灭灯</span>
      </div>
      <div class="stack-scroll">
        <div ref="stackWrapRef" class="stack-wrap">
          <canvas ref="stackRef" class="stack-canvas"></canvas>
        </div>
      </div>
      <el-empty v-if="!utilLoading && (utilData.deviceList || []).length === 0" description="暂无数据" />
    </div>
  </div>
</template>

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

const utilQueryMode = ref('day')
const utilDate = ref('')
const utilWeekDate = ref('')
const utilMonthDate = ref('')
const utilLoading = ref(false)
const sortMode = ref('rate')

const utilData = reactive({
  totalDuration: { green: {}, yellow: {}, red: {}, off: {}, blue: {} },
  availabilityRate: '0%',
  currentStatus: { green: 0, red: 0, off: 0, blue: 0, yellow: 0 },
  abnormalRanking: [],
  deviceList: []
})

const utilWeekDisplayFormat = computed(() => {
  if (!utilWeekDate.value) return ''
  const d = new Date(utilWeekDate.value)
  return `${d.getFullYear()}-${String(getWeekNumber(d)).padStart(2, '0')}周`
})

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

function getWeekNumber(date) {
  const d = new Date(Date.UTC(date.getFullYear(), date.getMonth(), date.getDate()))
  const dayNum = d.getUTCDay() || 7
  d.setUTCDate(d.getUTCDate() + 4 - dayNum)
  const yearStart = new Date(Date.UTC(d.getUTCFullYear(), 0, 1))
  return Math.ceil(((d - yearStart) / 86400000 + 1) / 7)
}

function formatYMD(d) {
  return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`
}

function getCurrentMonday() {
  const today = new Date()
  const day = today.getDay() || 7
  today.setDate(today.getDate() - day + 1)
  return formatYMD(today)
}

function getCurrentYM() {
  const now = new Date()
  return `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}`
}

function getWeekRange(dateStr) {
  if (!dateStr) return { start: '', end: '' }
  const d = new Date(dateStr)
  const day = d.getDay() || 7
  const diff = d.getDate() - day + 1
  const monday = new Date(d.setDate(diff))
  const sunday = new Date(monday)
  sunday.setDate(monday.getDate() + 6)
  return { start: formatYMD(monday), end: formatYMD(sunday) }
}

function getMonthRange(ymStr) {
  if (!ymStr) return { start: '', end: '' }
  const [y, m] = ymStr.split('-').map(Number)
  const lastDay = new Date(y, m, 0).getDate()
  return { start: `${ymStr}-01`, end: `${ymStr}-${String(lastDay).padStart(2, '0')}` }
}

function disableNonMonday(date) {
  return date.getDay() !== 1
}

function setDefaultDate() {
  if (utilQueryMode.value === 'day') {
    if (!utilDate.value) utilDate.value = formatYMD(new Date())
  } else if (utilQueryMode.value === 'week') {
    if (!utilWeekDate.value) utilWeekDate.value = getCurrentMonday()
  } else {
    if (!utilMonthDate.value) utilMonthDate.value = getCurrentYM()
  }
}

function onModeChange() {
  setDefaultDate()
  fetchUtilData()
}

function fmtSecHour(sec) {
  sec = Math.max(0, sec || 0)
  return (sec / 3600).toFixed(2) + '时'
}

function fmtSec(sec) {
  sec = Math.max(0, sec | 0)
  const h = Math.floor(sec / 3600)
  const m = Math.floor((sec % 3600) / 60)
  const s = sec % 60
  if (h > 0) return `${h}时${m}分${s}秒`
  if (m > 0) return `${m}分${s}秒`
  return `${s}秒`
}

const utilTotalSegments = computed(() => {
  const td = utilData.totalDuration
  const totalSec = (td.green?.seconds || 0) + (td.yellow?.seconds || 0) + (td.red?.seconds || 0) + (td.off?.seconds || 0)
  if (!totalSec) return []
  return [
    { label: '绿灯', color: '#67c23a', duration: td.green?.duration || '', pct: (((td.green?.seconds || 0) / totalSec) * 100).toFixed(2) + '%' },
    { label: '黄灯', color: '#e6a23c', duration: td.yellow?.duration || '', pct: (((td.yellow?.seconds || 0) / totalSec) * 100).toFixed(2) + '%' },
    { label: '红灯', color: '#f56c6c', duration: td.red?.duration || '', pct: (((td.red?.seconds || 0) / totalSec) * 100).toFixed(2) + '%' },
    { label: '灭灯', color: '#909399', duration: td.off?.duration || '', pct: (((td.off?.seconds || 0) / totalSec) * 100).toFixed(2) + '%' }
  ]
})

const abnormalList = computed(() => {
  return (utilData.abnormalRanking || []).filter(item => (item.yellowSeconds || 0) + (item.redSeconds || 0) > 0)
})

const pieTotalRef = ref(null)
const pieRateRef = ref(null)
const pieStatusRef = ref(null)
const abnormalRef = ref(null)
const stackRef = ref(null)

const pieTotalWrapRef = ref(null)
const pieRateWrapRef = ref(null)
const pieStatusWrapRef = ref(null)
const abnormalWrapRef = ref(null)
const stackWrapRef = ref(null)

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

function drawPie(ctx, cx, cy, r, segments) {
  const total = segments.reduce((s, seg) => s + seg.value, 0)
  if (total <= 0) return
  let angle = -Math.PI / 2
  segments.forEach(seg => {
    const sweep = (seg.value / total) * Math.PI * 2
    ctx.beginPath()
    ctx.moveTo(cx, cy)
    ctx.arc(cx, cy, r, angle, angle + sweep)
    ctx.closePath()
    ctx.fillStyle = seg.color
    ctx.fill()
    ctx.strokeStyle = 'rgba(255,255,255,0.5)'
    ctx.lineWidth = 0.8
    ctx.stroke()

    if (seg.value > 0) {
      const midAngle = angle + sweep / 2
      const labelR = r * 0.62
      const lx = cx + Math.cos(midAngle) * labelR
      const ly = cy + Math.sin(midAngle) * labelR
      const pct = ((seg.value / total) * 100).toFixed(2) + '%'
      ctx.save()
      ctx.fillStyle = '#fff'
      ctx.textAlign = 'center'
      ctx.textBaseline = 'middle'
      ctx.font = 'bold 12px sans-serif'
      ctx.fillText(pct, lx, ly - 7)
      ctx.font = '10px sans-serif'
      ctx.fillText(seg.textLabel || '', lx, ly + 8)
      ctx.restore()
    }
    angle += sweep
  })
}

function drawTotalPie() {
  const canvas = pieTotalRef.value
  const wrap = pieTotalWrapRef.value
  if (!canvas || !wrap) return
  const cssSize = Math.max(240, Math.min(320, wrap.clientWidth || 0))
  const { ctx, W, H } = setupCanvas(canvas, cssSize, cssSize)
  ctx.clearRect(0, 0, W, H)
  const td = utilData.totalDuration
  const gSec = td.green?.seconds || 0
  const ySec = td.yellow?.seconds || 0
  const rSec = td.red?.seconds || 0
  const oSec = td.off?.seconds || 0
  const totalSec = gSec + ySec + rSec + oSec
  const cx = W / 2
  const cy = H / 2
  const r = Math.min(W, H) / 2 - 16
  if (totalSec <= 0) {
    ctx.fillStyle = '#999'
    ctx.font = '13px sans-serif'
    ctx.textAlign = 'center'
    ctx.fillText('暂无数据', cx, cy)
    return
  }
  drawPie(ctx, cx, cy, r, [
    { label: '绿灯', value: gSec, color: '#67c23a', textLabel: '绿灯' },
    { label: '黄灯', value: ySec, color: '#e6a23c', textLabel: `黄灯:${fmtSecHour(ySec)}` },
    { label: '红灯', value: rSec, color: '#f56c6c', textLabel: `红灯:${fmtSecHour(rSec)}` },
    { label: '灭灯', value: oSec, color: '#909399', textLabel: `灭灯:${fmtSecHour(oSec)}` }
  ])
}

function drawRatePie() {
  const canvas = pieRateRef.value
  const wrap = pieRateWrapRef.value
  if (!canvas || !wrap) return
  const cssSize = Math.max(240, Math.min(320, wrap.clientWidth || 0))
  const { ctx, W, H } = setupCanvas(canvas, cssSize, cssSize)
  ctx.clearRect(0, 0, W, H)
  const td = utilData.totalDuration
  const gSec = td.green?.seconds || 0
  const ySec = td.yellow?.seconds || 0
  const rSec = td.red?.seconds || 0
  const total = gSec + ySec + rSec
  const cx = W / 2
  const cy = H / 2
  const r = Math.min(W, H) / 2 - 16
  if (total <= 0) {
    ctx.fillStyle = '#999'
    ctx.font = '13px sans-serif'
    ctx.textAlign = 'center'
    ctx.fillText('暂无数据', cx, cy)
    return
  }
  drawPie(ctx, cx, cy, r, [
    { label: '绿灯', value: gSec, color: '#67c23a', textLabel: `绿灯:${fmtSecHour(gSec)}` },
    { label: '黄灯', value: ySec, color: '#e6a23c', textLabel: `黄灯:${fmtSecHour(ySec)}` },
    { label: '红灯', value: rSec, color: '#f56c6c', textLabel: `红灯:${fmtSecHour(rSec)}` }
  ])
}

function drawStatusPie() {
  const canvas = pieStatusRef.value
  const wrap = pieStatusWrapRef.value
  if (!canvas || !wrap) return
  const cssSize = Math.max(240, Math.min(320, wrap.clientWidth || 0))
  const { ctx, W, H } = setupCanvas(canvas, cssSize, cssSize)
  ctx.clearRect(0, 0, W, H)
  const cs = utilData.currentStatus
  const gN = cs.green || 0
  const yN = cs.yellow || 0
  const rN = cs.red || 0
  const oN = cs.off || 0
  const total = gN + yN + rN + oN
  const cx = W / 2
  const cy = H / 2
  const r = Math.min(W, H) / 2 - 16
  if (total <= 0) {
    ctx.fillStyle = '#999'
    ctx.font = '13px sans-serif'
    ctx.textAlign = 'center'
    ctx.fillText('暂无数据', cx, cy)
    return
  }
  drawPie(ctx, cx, cy, r, [
    { label: '绿灯', value: gN, color: '#67c23a', textLabel: `绿灯${gN}台` },
    { label: '黄灯', value: yN, color: '#e6a23c', textLabel: `黄灯${yN}台` },
    { label: '红灯', value: rN, color: '#f56c6c', textLabel: `红灯${rN}台` },
    { label: '灭灯', value: oN, color: '#909399', textLabel: `灭灯${oN}台` }
  ])
}

function drawAbnormal() {
  const canvas = abnormalRef.value
  const wrap = abnormalWrapRef.value
  if (!canvas || !wrap) return
  const list = abnormalList.value
  const cssW = Math.max(300, wrap.clientWidth)
  const cssH = Math.min(420, Math.max(220, list.length * 26 + 60))
  const { ctx, W, H } = setupCanvas(canvas, cssW, cssH)
  ctx.clearRect(0, 0, W, H)
  if (list.length === 0) return

  const PAD_L = 64
  const PAD_R = 14
  const PAD_T = 30
  const PAD_B = 10
  const plotW = W - PAD_L - PAD_R
  const plotH = H - PAD_T - PAD_B
  const rowH = Math.min(24, plotH / list.length)
  const barH = rowH - 6

  let maxVal = 1
  list.forEach(item => {
    maxVal = Math.max(maxVal, (item.yellowSeconds || 0) + (item.redSeconds || 0))
  })

  const tickCount = 4
  ctx.strokeStyle = '#eee'
  ctx.lineWidth = 1
  ctx.fillStyle = '#64748b'
  ctx.font = '10px sans-serif'
  ctx.textAlign = 'center'
  for (let i = 0; i <= tickCount; i++) {
    const val = (maxVal * i) / tickCount
    const x = PAD_L + (plotW * i) / tickCount
    ctx.fillText(fmtSec(Math.round(val)), x, 16)
    if (i > 0) {
      ctx.beginPath()
      ctx.moveTo(x, PAD_T)
      ctx.lineTo(x, H - PAD_B)
      ctx.stroke()
    }
  }

  ctx.strokeStyle = '#ddd'
  ctx.lineWidth = 1.5
  ctx.beginPath()
  ctx.moveTo(PAD_L, PAD_T)
  ctx.lineTo(W - PAD_R, PAD_T)
  ctx.stroke()

  list.slice(0, 12).forEach((item, idx) => {
    const y = PAD_T + idx * rowH
    ctx.fillStyle = '#0f172a'
    ctx.font = '11px sans-serif'
    ctx.textAlign = 'right'
    ctx.textBaseline = 'middle'
    const dn = (item.deviceName || item.dtuSn || '').slice(0, 8)
    ctx.fillText(dn, PAD_L - 8, y + rowH / 2)

    const yS = item.yellowSeconds || 0
    const rS = item.redSeconds || 0
    const yW = (yS / maxVal) * plotW
    const rW = (rS / maxVal) * plotW
    ctx.fillStyle = '#e6a23c'
    ctx.fillRect(PAD_L, y + 3, yW, barH)
    ctx.fillStyle = '#f56c6c'
    ctx.fillRect(PAD_L + yW, y + 3, rW, barH)
  })
}

function drawStackBar() {
  const canvas = stackRef.value
  const wrap = stackWrapRef.value
  if (!canvas || !wrap) return
  const list = utilData.deviceList || []
  if (list.length === 0) {
    const { ctx, W, H } = setupCanvas(canvas, Math.max(320, wrap.clientWidth), 260)
    ctx.clearRect(0, 0, W, H)
    ctx.fillStyle = '#999'
    ctx.font = '13px sans-serif'
    ctx.textAlign = 'center'
    ctx.fillText('暂无数据', W / 2, H / 2)
    return
  }

  const sorted = sortMode.value === 'rate'
    ? [...list].sort((a, b) => parseFloat(b.availabilityRatio || 0) - parseFloat(a.availabilityRatio || 0))
    : [...list].sort((a, b) => (b.greenSeconds || 0) - (a.greenSeconds || 0))

  const PAD_L = 36
  const PAD_R = 16
  const PAD_T = 18
  const PAD_B = 44
  const colW = 18
  const gap = 8
  const minW = Math.max(320, wrap.clientWidth)
  const cssW = Math.max(minW, PAD_L + PAD_R + sorted.length * (colW + gap) + gap)
  const cssH = 280
  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

  let maxVal = 1
  sorted.forEach(item => {
    const t = (item.greenSeconds || 0) + (item.yellowSeconds || 0) + (item.redSeconds || 0) + (item.offSeconds || 0)
    maxVal = Math.max(maxVal, t)
  })

  const maxHours = maxVal / 3600 || 1
  const yTicks = [Math.ceil(maxHours), Math.ceil(maxHours * 0.66), Math.ceil(maxHours * 0.33), 0]
  ctx.strokeStyle = '#f0f0f0'
  ctx.lineWidth = 1
  ctx.fillStyle = '#94a3b8'
  ctx.font = '10px sans-serif'
  ctx.textAlign = 'end'
  yTicks.forEach(val => {
    const py = PAD_T + plotH * (1 - val / maxHours)
    ctx.fillText(val + '时', PAD_L - 4, py + 3)
    ctx.beginPath()
    ctx.moveTo(PAD_L, py)
    ctx.lineTo(W - PAD_R, py)
    ctx.stroke()
  })

  ctx.strokeStyle = '#ddd'
  ctx.beginPath()
  ctx.moveTo(PAD_L, PAD_T + plotH)
  ctx.lineTo(W - PAD_R, PAD_T + plotH)
  ctx.stroke()

  const scale = plotH / maxVal
  sorted.forEach((item, idx) => {
    const px = PAD_L + gap + idx * (colW + gap)
    const gS = item.greenSeconds || 0
    const yS = item.yellowSeconds || 0
    const rS = item.redSeconds || 0
    const oS = item.offSeconds || 0
    const total = gS + yS + rS + oS
    if (total <= 0) return
    let curY = PAD_T + plotH
    const gH = gS * scale
    curY -= gH
    ctx.fillStyle = '#67c23a'
    ctx.fillRect(px, curY, colW, gH)
    const yH = yS * scale
    curY -= yH
    ctx.fillStyle = '#e6a23c'
    ctx.fillRect(px, curY, colW, yH)
    const rH = rS * scale
    curY -= rH
    ctx.fillStyle = '#f56c6c'
    ctx.fillRect(px, curY, colW, rH)
    const oH = oS * scale
    curY -= oH
    ctx.fillStyle = '#909399'
    ctx.fillRect(px, curY, colW, oH)

    ctx.fillStyle = '#64748b'
    ctx.font = '9px sans-serif'
    ctx.textAlign = 'center'
    ctx.save()
    ctx.translate(px + colW / 2, PAD_T + plotH + 12)
    ctx.rotate(-Math.PI / 6)
    const dn = (item.deviceName || item.dtuSn || '').replace(/中速|高速|号机/g, '').slice(0, 6)
    ctx.fillText(dn, 0, 0)
    ctx.restore()
  })
}

function drawAll() {
  drawTotalPie()
  drawRatePie()
  drawStatusPie()
  drawAbnormal()
  drawStackBar()
}

function redrawStackBar() {
  nextTick(drawStackBar)
}

async function fetchUtilData() {
  let startDate = ''
  let endDate = ''
  if (utilQueryMode.value === 'day') {
    if (!utilDate.value) { ElMessage.warning('请选择查询日期'); return }
    startDate = endDate = utilDate.value
  } else if (utilQueryMode.value === 'week') {
    if (!utilWeekDate.value) { ElMessage.warning('请选择查询周'); return }
    const range = getWeekRange(utilWeekDate.value)
    startDate = range.start
    endDate = range.end
  } else {
    if (!utilMonthDate.value) { ElMessage.warning('请选择查询月份'); return }
    const range = getMonthRange(utilMonthDate.value)
    startDate = range.start
    endDate = range.end
  }

  utilLoading.value = true
  try {
    const res = await apiFetch(`/api/device/lampStatistics?startDate=${encodeURIComponent(startDate)}&endDate=${encodeURIComponent(endDate)}`)
    const data = await res.json()
    if (data.totalDuration) Object.assign(utilData.totalDuration, data.totalDuration)
    if (data.availabilityRate) utilData.availabilityRate = data.availabilityRate
    if (data.currentStatus) Object.assign(utilData.currentStatus, data.currentStatus)
    utilData.abnormalRanking = data.abnormalRanking || []
    utilData.deviceList = data.deviceList || []
    await nextTick()
    drawAll()
  } catch (e) {
    ElMessage.error('获取数据失败')
    console.warn(e)
  } finally {
    utilLoading.value = false
  }
}

let ro = null
onMounted(() => {
  setDefaultDate()
  fetchUtilData()
  const target = pieTotalWrapRef.value || null
  if (target && 'ResizeObserver' in window) {
    ro = new ResizeObserver(() => { drawAll() })
    ro.observe(target)
  }
})

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

watch(() => utilData.totalDuration, () => nextTick(drawAll), { deep: true })
</script>

<style scoped>
.util-h5 {
  padding: 0;
}

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

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

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

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

.legend {
  display: grid;
  grid-template-columns: repeat(2, minmax(0, 1fr));
  gap: 8px;
  margin-bottom: 8px;
}

.legend-item {
  display: grid;
  grid-template-columns: 12px 1fr auto;
  align-items: center;
  gap: 6px;
  font-size: 12px;
  color: #475569;
}

.legend-item .val {
  justify-self: end;
  color: #0f172a;
  font-weight: 600;
}

.legend-item .pct {
  justify-self: end;
  color: #64748b;
  margin-left: 6px;
}

.legend-total {
  display: grid;
  grid-template-columns: repeat(2, minmax(0, 1fr));
  gap: 10px 12px;
  margin-bottom: 8px;
}

.legend-total-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 10px;
  min-width: 0;
}

.lt-left {
  display: inline-flex;
  align-items: center;
  gap: 8px;
  min-width: 0;
}

.lt-left .name {
  font-size: 12px;
  color: #0f172a;
  font-weight: 600;
  white-space: nowrap;
}

.lt-right {
  text-align: right;
  min-width: 0;
}

.legend-total-item .val {
  font-size: 12px;
  color: #0f172a;
  font-weight: 700;
  line-height: 1.15;
  white-space: nowrap;
}

.legend-total-item .pct {
  font-size: 12px;
  color: #64748b;
  line-height: 1.15;
  margin-top: 4px;
  white-space: nowrap;
}

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

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

.pie-canvas {
  width: 100%;
  max-width: 320px;
  aspect-ratio: 1 / 1;
  display: block;
}

.chart-wrap {
  width: 100%;
  overflow: hidden;
}

.chart-canvas {
  width: 100%;
  display: block;
}

.stack-toolbar {
  margin-bottom: 10px;
}

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

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

.stack-scroll {
  overflow-x: auto;
  -webkit-overflow-scrolling: touch;
}

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

.stack-canvas {
  height: 280px;
  display: block;
}
</style>