SafetyDialog.vue 30.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 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 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043
<template>
  <el-dialog
    :model-value="visible"
    @update:model-value="$emit('update:visible', $event)"
    title=""
    width="calc(100vw - 40px)"
    :style="{ maxWidth: '1400px' }"
    top="3vh"
    destroy-on-close
    class="safety-dialog"
  >
    <template #header>
      <div class="dialog-header">
        <span class="title-text">{{ device?.name || dtuSn }} 查询方式:</span>
        <el-radio-group v-model="queryMode" size="small" @change="onModeChange">
          <el-radio-button value="hour">时查询</el-radio-button>
          <el-radio-button value="day">日查询</el-radio-button>
          <el-radio-button value="month">月查询</el-radio-button>
        </el-radio-group>
        <el-date-picker v-if="queryMode === 'hour'" v-model="selectedDate"
          type="date" placeholder="" size="small" style="width:160px;margin-left:8px;" value-format="YYYY-MM-DD" @change="fetchData" />
        <el-date-picker v-if="queryMode === 'day'" v-model="dayRange" type="daterange" size="small"
          style="width:240px;margin-left:8px;" value-format="YYYY-MM-DD" start-placeholder="开始日期" end-placeholder="结束日期"
          :disabled-date="disabledDateFuture" @change="fetchData" />
        <el-date-picker v-if="queryMode === 'range'" v-model="dateRange" type="daterange" size="small"
          style="width:240px;margin-left:8px;" value-format="YYYY-MM-DD" start-placeholder="开始日期" end-placeholder="结束日期"
          :disabled-date="disabledDateFuture" @change="fetchData" />
        <el-button type="primary" size="small" style="margin-left:8px;" @click="fetchData">查询</el-button>
        <div style="flex:1"></div>
      </div>
    </template>

    <div class="safety-body" v-loading="loading">
      <!-- 主内容区:左组合图 + 右饼图 -->
      <div class="main-row">
        <!-- 左侧:运行时长明细(堆叠柱状图+折线双轴) -->
        <div class="combo-panel">
          <div class="panel-title-row">
            <span class="panel-title">运行时长明细</span>
            <div class="legend-right">
              <span class="leg"><i class="dot g"/>运行</span>
              <span class="leg"><i class="dot y"/>待机</span>
              <span class="leg"><i class="dot r"/>停机</span>
              <span class="leg"><i class="dot gy"/>离线</span>
              <span class="leg line-leg"><i class="line-dot"/>用电量</span>
            </div>
          </div>
          <div class="combo-canvas-wrap" ref="comboWrapRef" @mousemove="onComboMouseMove" @mouseleave="onComboMouseLeave">
            <canvas ref="comboCanvasRef"></canvas>
            <div v-if="comboHover.show" class="combo-tooltip" :style="{ left: comboHover.x + 'px', top: comboHover.y + 'px' }">
              <div class="ctt-row" v-for="(row, i) in comboTtRows" :key="i">
                <span class="ctt-label" :style="{ color: row.color }"><i v-if="row.dot" :class="['dot', row.dot]"></i><i v-if="row.isLine" class="line-dot-sm"></i>{{ row.label }}</span>
                <span class="ctt-val" :class="{ 'ctt-highlight': row.highlight }">{{ row.value }}</span>
              </div>
            </div>
          </div>
        </div>

        <!-- 右侧:运行时长统计(饼图+总数据) -->
        <div class="stat-panel">
          <div class="panel-title">运行时长统计</div>
          <div class="stat-duration">{{ apiData.summary.totalDurationFormatted }}</div>
          <div class="pie-canvas-wrap">
            <canvas ref="pieCanvasRef" @mousemove="onPieMouseMove" @mouseleave="onPieMouseLeave"></canvas>
            <div v-if="pieHover.show" class="pie-tooltip" :style="{ left: pieHover.x + 'px', top: pieHover.y + 'px' }">
              <div class="ptt-row"><span class="ptt-label">状态</span><span class="ptt-val" :style="{ color: STATUS_COLORS[pieTtData.status] }"><i :class="['dot', statusDotClass(pieTtData.status)]"></i>{{ statusLabel(pieTtData.status) }}</span></div>
              <div class="ptt-row"><span class="ptt-label">占比</span><span class="ptt-val ptt-highlight">{{ pieTtData.percent }}%</span></div>
            </div>
          </div>
          <div class="stat-kwh-area">
            <div class="sk-label">总用电量</div>
            <div class="sk-value">{{ formatKwh(apiData.summary.totalKwh) }}Kw.h</div>
          </div>
        </div>
      </div>
    </div>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, computed, watch, nextTick, onBeforeUnmount } from 'vue'
import { Download, Close } from '@element-plus/icons-vue'

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

// ==================== 查询模式 ====================
// 近一周默认范围
const today = new Date().toISOString().slice(0, 10)
const weekAgo = new Date(Date.now() - 6 * 86400000).toISOString().slice(0, 10)
const queryMode = ref('hour')
const selectedDate = ref(today)
const dayRange = ref([weekAgo, today])
const dateRange = ref(null)

// 禁用未来日期
function disabledDateFuture(time) {
  return time.getTime() > Date.now()
}

function onModeChange() {
  if (queryMode.value === 'day' || queryMode.value === 'range') {
    // 切到日/范围模式,使用默认日期范围立即查询
    nextTick(() => fetchData())
  } else {
    fetchData()
  }
}

const dtuSn = computed(() => props.device?._raw?.dtuSn || props.device?.name || '')

// ==================== API 数据 ====================
const loading = ref(false)
const apiData = reactive({
  summary: { totalKwh: 0, totalDurationSeconds: 0, statusStats: [], totalDurationFormatted: '0秒' },
  detailList: []
})

// ==================== 工具函数 ====================
const STATUS_MAP = { 0: '离线', 1: '停机', 2: '运行', 3: '待机' }
function statusLabel(s) { return STATUS_MAP[s] || '未知' }
function statusDotClass(s) { return { 0: 'gy', 1: 'r', 2: 'g', 3: 'y' }[s] || 'gy' }

const STATUS_COLORS = { 0: '#909399', 1: '#e74c3c', 2: '#67c23a', 3: '#c5d94e' }
const STATUS_COLORS_HOVER = { 0: '#7a7d82', 1: '#d63a3a', 2: '#4cae4c', 3: '#b8cc38' }

function formatKwh(v) {
  if (!v && v !== 0) return '0'
  return Number(v).toFixed(v % 1 === 0 ? 0 : 2)
}
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 = seconds % 60
  let str = ''
  if (h > 0) str += h + '时'
  if (m > 0) str += m + '分'
  if (s > 0 || !str) str += s + '秒'
  return str
}
function formatHours(seconds) {
  if (!seconds && seconds !== 0) return '0'
  const h = seconds / 3600
  return h.toFixed(2).replace(/\.?0+$/, '') + '时'
}

// ==================== 获取当前 kwhList(扁平化) ====================
const flatKwhList = computed(() => {
  const dl = apiData.detailList
  if (!dl || !dl.length) return []
  // type=1: detailList[0].kwhList 每项已有 0/1/2/3 秒数 + value 用电量
  if (dl[0] && dl[0].kwhList) return dl[0].kwhList
  // type=2/3: detailList 每项只有 statusStats[{status,durationSeconds}] + totalKwh,需要转换
  return dl.map(item => {
    const row = { date: item.date || '', value: item.totalKwh || 0 }
    ;(item.statusStats || []).forEach(s => {
      row[s.status] = s.durationSeconds || 0
    })
    // 确保 0/1/2/3 都存在
    for (let k = 0; k <= 3; k++) row[k] = row[k] ?? 0
    return row
  })
})

// ==================== 获取 X轴 标签 ====================
function getXLabel(item, idx) {
  if (queryMode.value === 'hour') {
    return item.date || (idx + 1) + '时'
  }
  // day / range / month 都按日期显示
  return item.date || (idx + 1).toString()
}

// ==================== Canvas refs ====================
const comboCanvasRef = ref(null)
const comboWrapRef = ref(null)
const pieCanvasRef = ref(null)

let resizeObserver = null
let canvasRAF = null

// ==================== 组合图 Hover ====================
const comboHover = reactive({ show: false, x: 0, y: 0, index: -1 })
let comboBarRects = []

const comboTtRows = computed(() => {
  if (!comboHover.show || comboHover.index < 0) return []
  const list = flatKwhList.value
  const item = list[comboHover.index]
  if (!item) return []
  const rows = []
  // X轴标签
  rows.push({ label: getXLabel(item, comboHover.index), value: '', color: '#333', highlight: true })
  // 各状态时长 - 时查询优先使用接口返回的 Formatted
  const isHourMode = queryMode.value === 'hour'
  const statuses = [
    { key: 2, dot: 'g', label: '运行' },
    { key: 3, dot: 'y', label: '待机' },
    { key: 1, dot: 'r', label: '停机' },
    { key: 0, dot: 'gy', label: '离线' }
  ]
  statuses.forEach(s => {
    const sec = item[s.key] ?? 0
    if (sec > 0) {
      const totalSec = (item['0']||0)+(item['1']||0)+(item['2']||0)+(item['3']||0)
      const pctStr = totalSec > 0 ? ` (${(sec/totalSec*100).toFixed(1)}%)` : ''
      if (isHourMode && item[s.key + 'Formatted']) {
        rows.push({ label: s.label, value: item[s.key + 'Formatted'] + pctStr, color: STATUS_COLORS[s.key], dot: s.dot })
      } else {
        rows.push({ label: s.label, value: formatHours(sec) + pctStr, color: STATUS_COLORS[s.key], dot: s.dot })
      }
    }
  })
  // 用电量
  const kwhVal = item.value ?? 0
  rows.push({ label: '用电量', value: kwhVal + ' Kw.h', color: '#409eff', isLine: true, highlight: true })
  return rows
})

function onComboMouseMove(e) {
  const canvas = comboCanvasRef.value
  if (!canvas) return
  const rect = canvas.getBoundingClientRect()
  const mx = e.clientX - rect.left
  const my = e.clientY - rect.top

  let hoveredIdx = -1
  for (let i = 0; i < comboBarRects.length; i++) {
    const br = comboBarRects[i]
    if (mx >= br.x && mx <= br.x + br.w && my >= br.y && my <= br.y + br.h) {
      hoveredIdx = i
      break
    }
  }

  if (hoveredIdx !== comboHover.index) {
    comboHover.index = hoveredIdx
    comboHover.show = hoveredIdx >= 0
    if (hoveredIdx >= 0) {
      const ttW = 160
      const ttH = comboTtRows.value.length * 28 + 12
      let tx = mx + 10
      let ty = my - ttH - 8
      if (tx + ttW > rect.width - 6) tx = mx - ttW - 8
      if (ty < 6) ty = my + 14
      comboHover.x = Math.max(4, tx)
      comboHover.y = Math.max(4, ty)
    }
    drawComboChart()
  }
}

function onComboMouseLeave() {
  comboHover.show = false
  comboHover.index = -1
  drawComboChart()
}

// ==================== 饼图 Hover ====================
const pieHover = reactive({ show: false, x: 0, y: 0, index: -1 })
const pieTtData = computed(() => {
  if (!pieHover.show || pieHover.index < 0) return { status: '-', percent: '-' }
  const stats = apiData.summary.statusStats || []
  const item = stats[pieHover.index]
  if (!item) return { status: '-', percent: '-' }
  return { status: item.status, percent: (item.percent || 0).toFixed(2) }
})
let pieAngleRanges = []

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 hoveredIdx = -1
  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)
    if (dist > seg.radius) continue
    let mouseAngle = Math.atan2(dy, dx)
    function inRange(a, sa, ea) {
      let na = a - sa, nea = ea - sa
      if (nea < 0) nea += Math.PI * 2
      if (na < 0) na += Math.PI * 2
      return na >= 0 && na <= nea
    }
    if (inRange(mouseAngle, seg.startAngle, seg.endAngle)) {
      hoveredIdx = i
      break
    }
  }

  if (hoveredIdx !== pieHover.index) {
    pieHover.index = hoveredIdx
    pieHover.show = hoveredIdx >= 0
    if (hoveredIdx >= 0) {
      const ttW = 120
      let tx = mx + 10, ty = my - 54
      if (tx + ttW > rect.width - 4) tx = mx - ttW - 8
      if (ty < 4) ty = my + 14
      pieHover.x = Math.max(4, tx)
      pieHover.y = Math.max(4, ty)
    }
    drawPieChart()
  }
}

function onPieMouseLeave() {
  pieHover.show = false
  pieHover.index = -1
  drawPieChart()
}

// ==================== 接口调用 ====================
async function fetchData() {
  if (!dtuSn.value) return
  loading.value = true
  try {
    let type = 1
    let sd = selectedDate.value
    let ed = ''

    if (queryMode.value === 'hour') {
      type = 1; sd = selectedDate.value
    } else if (queryMode.value === 'day') {
      type = 2
      if (!dayRange.value || !dayRange.value.length) return
      sd = dayRange.value[0]; ed = dayRange.value[1]
    } else if (queryMode.value === 'range') {
      if (!dateRange.value || !dateRange.value.length) return
      type = 2; sd = dateRange.value[0]; ed = dateRange.value[1]
    } else if (queryMode.value === 'month') {
      type = 3
      const now = new Date()
      sd = now.getFullYear() + '-01-01'
    }

    let url = `/api/energy/runtimeDetail?dtuSn=${dtuSn.value}&startDate=${sd}&type=${type}`
    if (ed) url += '&endDate=' + ed

    const res = await fetch(url)
    const data = await res.json()
    if (data.code === 200) {
      Object.assign(apiData.summary, data.summary || {})
      apiData.detailList = data.detailList || []
      await nextTick()
      drawAllCharts()
    }
  } catch (err) {
    console.error('获取能耗详情失败:', err)
  } finally {
    loading.value = false
  }
}

function exportData() {
  alert('导出功能开发中')
}

// ==================== 生命周期 & Observer ====================
watch(() => props.visible, async (val) => {
  if (val) {
    await nextTick()
    initCanvasObserver()
    fetchData()
  } else {
    destroyCanvasObserver()
  }
})

onBeforeUnmount(() => destroyCanvasObserver())

function initCanvasObserver() {
  destroyCanvasObserver()
  const dialogBody = document.querySelector('.safety-dialog .el-dialog__body')
  if (!dialogBody) return
  resizeObserver = new ResizeObserver(() => {
    if (canvasRAF) cancelAnimationFrame(canvasRAF)
    canvasRAF = requestAnimationFrame(drawAllCharts)
  })
  resizeObserver.observe(dialogBody)
}

function destroyCanvasObserver() {
  if (resizeObserver) { resizeObserver.disconnect(); resizeObserver = null }
  if (canvasRAF) { cancelAnimationFrame(canvasRAF); canvasRAF = null }
}

// ==================== Canvas 基础工具 ====================
function getDpr() { return window.devicePixelRatio || 1 }

function setupCanvas(canvas, w, h) {
  const dpr = getDpr()
  canvas.width = w * dpr
  canvas.height = h * dpr
  canvas.style.width = w + 'px'
  canvas.style.height = h + 'px'
  const ctx = canvas.getContext('2d')
  ctx.scale(dpr, dpr)
  return ctx
}

function drawAllCharts() {
  drawComboChart()
  drawPieChart()
}

// ==================== 1. 组合图:堆叠柱状图 + 折线双轴 ====================
function drawComboChart() {
  const canvas = comboCanvasRef.value
  if (!canvas) return
  const wrap = comboWrapRef.value
  const w = wrap ? wrap.clientWidth : 800
  const h = 652
  const ctx = setupCanvas(canvas, w, h)

  ctx.fillStyle = '#fff'
  ctx.fillRect(0, 0, w, h)

  const list = flatKwhList.value
  comboBarRects = []

  if (!list.length) {
    ctx.fillStyle = '#999'
    ctx.font = '14px sans-serif'
    ctx.textAlign = 'center'
    ctx.fillText('暂无数据', w / 2, h / 2)
    return
  }

  // 布局参数
  const padLeft = 48
  const padRight = 58   // 右侧 Y 轴(用电量)
  const padTop = 32
  const padBottom = 36
  const chartW = w - padLeft - padRight
  const chartH = h - padTop - padBottom

  // 计算左侧Y轴最大值(时长,秒 -> 小时)
  const isHourQuery = queryMode.value === 'hour'
  const defaultMaxSec = isHourQuery ? 7200 : 3600  // 时查询默认2小时,其他默认1小时
  const maxSec = Math.max(...list.map(item => {
    return (item['0']||0) + (item['1']||0) + (item['2']||0) + (item['3']||0)
  }), defaultMaxSec)
  const maxHours = maxSec / 3600
  const niceMaxHours = calcNiceMax(maxHours)

  // 计算右侧Y轴最大值(用电量)
  const maxKwh = Math.max(...list.map(d => d.value || 0), 10)
  const niceMaxKwh = calcNiceMax(maxKwh)

  // ========== 左侧Y轴标签(时长) ==========
  ctx.fillStyle = '#666'
  ctx.font = '11px sans-serif'
  ctx.textAlign = 'right'
  const leftSteps = 5
  for (let i = 0; i <= leftSteps; i++) {
    const val = (niceMaxHours / leftSteps) * i
    const y = padTop + chartH - (val / niceMaxHours) * chartH
    ctx.fillText(val.toFixed(2).replace(/\.?0+$/, '') + '时', padLeft - 6, y + 4)
    // 网格线
    ctx.strokeStyle = '#f0f0f0'
    ctx.lineWidth = 0.5
    ctx.beginPath()
    ctx.moveTo(padLeft, y)
    ctx.lineTo(w - padRight, y)
    ctx.stroke()
  }

  // ========== 右侧Y轴标签(用电量) ==========
  ctx.textAlign = 'left'
  const rightSteps = 5
  for (let i = 0; i <= rightSteps; i++) {
    const val = (niceMaxKwh / rightSteps) * i
    const y = padTop + chartH - (val / niceMaxKwh) * chartH
    ctx.fillText(val.toFixed(val % 1 === 0 ? 0 : 1) + 'Kw/h', w - padRight + 6, y + 4)
  }

  // ========== X轴线 ==========
  ctx.strokeStyle = '#ddd'
  ctx.lineWidth = 1
  ctx.beginPath()
  ctx.moveTo(padLeft, padTop + chartH)
  ctx.lineTo(w - padRight, padTop + chartH)
  ctx.stroke()

  // ========== 柱状图参数 ==========
  const barCount = list.length
  const gapRatio = 0.25
  const barW = Math.min(60, Math.max(6, (chartW / barCount) * (1 - gapRatio)))
  const gap = (chartW / barCount) * gapRatio
  const hoverIdx = comboHover.index

  // 折线数据点缓存
  const linePoints = []

  list.forEach((item, i) => {
    const x = padLeft + (i * (chartW / barCount)) + gap / 2

    // --- 堆叠柱 ---
    const stackOrder = [2, 3, 1, 0]  // 运行、待机、停机、离线
    let curY = padTop + chartH
    let totalSec = 0

    stackOrder.forEach(statusKey => {
      const sec = item[statusKey] || 0
      if (sec <= 0) return
      totalSec += sec
      const barH = (sec / 3600 / niceMaxHours) * chartH
      curY -= barH

      const isHover = (i === hoverIdx)

      if (isHover) {
        const hw = barW + 4
        const hx = x - 2
        ctx.save()
        ctx.shadowColor = 'rgba(0,0,0,0.15)'
        ctx.shadowBlur = 8
        ctx.shadowOffsetY = 2
        ctx.fillStyle = STATUS_COLORS_HOVER[statusKey] || STATUS_COLORS[statusKey]
        ctx.beginPath()
        ctx.roundRect(hx, curY, hw, barH, 2)
        ctx.fill()
        ctx.restore()
      } else {
        ctx.fillStyle = STATUS_COLORS[statusKey]
        ctx.globalAlpha = 0.85
        ctx.fillRect(x, curY, barW, barH)
        ctx.globalAlpha = 1
      }
    })

    // 存储碰撞矩形(整个堆叠柱区域)
    const fullH = (totalSec / 3600 / niceMaxHours) * chartH
    comboBarRects.push({
      x, y: padTop + chartH - fullH, w: barW, h: fullH,
      totalSec, kwh: item.value || 0
    })

    // --- X轴标签 ---
    const lbl = getXLabel(item, i)
    ctx.fillStyle = i === hoverIdx ? '#409eff' : '#666'
    ctx.font = `${i === hoverIdx ? 'bold ' : ''}10px sans-serif`
    ctx.textAlign = 'center'
    // 旋转或截断长标签
    const maxLblW = barW + gap - 2
    ctx.save()
    const txtW = ctx.measureText(lbl).width
    if (txtW > maxLblW && maxLblW > 20) {
      // 截断显示
      let shortLbl = lbl
      while (ctx.measureText(shortLbl + '...').width > maxLblW && shortLbl.length > 2) {
        shortLbl = shortLbl.slice(0, -1)
      }
      ctx.fillText(shortLbl + '...', x + barW / 2, padTop + chartH + 16)
    } else {
      ctx.fillText(lbl, x + barW / 2, padTop + chartH + 16)
    }
    ctx.restore()

    // --- 折线数据点 ---
    const kwhVal = item.value || 0
    const ly = padTop + chartH - (kwhVal / niceMaxKwh) * chartH
    linePoints.push({ x: x + barW / 2, y: ly, val: kwhVal })
  })

  // ========== 绘制折线(用电量) ==========
  if (linePoints.length > 0) {
    // 折线
    ctx.strokeStyle = '#409eff'
    ctx.lineWidth = 1.8
    ctx.beginPath()
    linePoints.forEach((pt, i) => {
      if (i === 0) ctx.moveTo(pt.x, pt.y)
      else ctx.lineTo(pt.x, pt.y)
    })
    ctx.stroke()

    // 数据点圆圈
    linePoints.forEach((pt, i) => {
      const isHoverPt = (i === hoverIdx)
      ctx.beginPath()
      ctx.arc(pt.x, pt.y, isHoverPt ? 4.5 : 3, 0, Math.PI * 2)
      ctx.fillStyle = '#fff'
      ctx.fill()
      ctx.strokeStyle = '#409eff'
      ctx.lineWidth = isHoverPt ? 2 : 1.5
      ctx.stroke()

      // hover 时显示数值
      if (isHoverPt) {
        ctx.fillStyle = '#409eff'
        ctx.font = 'bold 11px sans-serif'
        ctx.textAlign = 'center'
        ctx.fillText(pt.val + '', pt.x, pt.y - 8)
      }
    })
  }

  // "Duration" 提示文字
  ctx.fillStyle = '#bbb'
  ctx.font = '10px sans-serif'
  ctx.textAlign = 'left'
  ctx.fillText('Duration', padLeft, 20)
  ctx.textAlign = 'right'
  ctx.fillText('用电量', w - padRight, 20)
}

function calcNiceMax(val) {
  if (val <= 0) return 10
  const mag = Math.pow(10, Math.floor(Math.log10(val)))
  const norm = val / mag
  let nice
  if (norm <= 1) nice = 1
  else if (norm <= 2) nice = 2
  else if (norm <= 5) nice = 5
  else nice = 10
  return nice * mag
}

// ==================== 2. 实心饼图 + 外部标签 ====================
function drawPieChart() {
  const canvas = pieCanvasRef.value
  if (!canvas) return
  const wrap = canvas.parentElement
  const w = wrap.clientWidth
  const h = 435
  const ctx = setupCanvas(canvas, w, h)

  ctx.clearRect(0, 0, w, h)

  const stats = apiData.summary.statusStats || []
  pieAngleRanges = []

  if (!stats.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.46
  const cy = h * 0.50
  const radius = Math.min(cx, cy) - 22
  const MIN_SLICE_DEG = 2

  // 计算角度
  const totalPct = stats.reduce((sum, s) => sum + (s.percent || 0), 0)
  const sliceInfos = stats.map((si, i) => {
    const pct = si.percent || 0
    const deg = pct > 0 ? (pct / totalPct) * 360 : MIN_SLICE_DEG
    return { index: i, status: si.status, percent: pct, deg }
  })

  const hasNonZero = sliceInfos.some(si => si.percent > 0)
  if (!hasNonZero && sliceInfos.length > 0) {
    const eqDeg = 360 / sliceInfos.length
    sliceInfos.forEach(si => si.deg = eqDeg)
  } 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 => {
    si.startAngle = startAngle
    si.sliceAngle = (si.deg / 180) * Math.PI
    si.endAngle = startAngle + si.sliceAngle
    si.midAngle = startAngle + si.sliceAngle / 2
    startAngle = si.endAngle
  })

  // 碰撞信息
  sliceInfos.forEach(si => {
    pieAngleRanges.push({
      index: si.index, status: si.status,
      cx, cy, radius, innerR: 0,
      startAngle: si.startAngle, endAngle: si.endAngle
    })
  })

  // 第一遍:画扇区
  sliceInfos.forEach(si => {
    if (si.index === pieHover.index) 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
  })

  // 第二遍:hover 扇区放大
  if (pieHover.index >= 0) {
    const si = sliceInfos.find(s => s.index === pieHover.index)
    if (si && si.percent >= 0) {
      const expandR = radius + 5
      const offsetDist = 6
      const ox = cx + Math.cos(si.midAngle) * offsetDist
      const oy = cy + Math.sin(si.midAngle) * offsetDist
      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, si.startAngle, si.endAngle)
      ctx.closePath()
      ctx.fillStyle = STATUS_COLORS_HOVER[si.status] || STATUS_COLORS[si.status] || '#ccc'
      ctx.fill()
      ctx.restore()
    }
  }

  // 第三遍:引导线 + 标签
  sliceInfos.forEach(si => {
    const isHover = (si.index === pieHover.index)
    const { midAngle, status: s, percent: pct } = si

    const lsX = cx + Math.cos(midAngle) * radius
    const lsY = cy + Math.sin(midAngle) * radius
    const elbowLen = 14
    const elbX = cx + Math.cos(midAngle) * (radius + elbowLen)
    const elbY = cy + Math.sin(midAngle) * (radius + elbowLen)
    const textDir = midAngle > Math.PI / 2 && midAngle <= Math.PI * 1.5 ? -1 : 1
    const textLen = 34
    const leX = elbX + textDir * textLen
    const leY = elbY

    ctx.strokeStyle = isHover ? '#666' : '#aaa'
    ctx.lineWidth = isHover ? 1.2 : 0.8
    ctx.beginPath()
    ctx.moveTo(lsX, lsY)
    ctx.lineTo(elbX, elbY)
    ctx.lineTo(leX, leY)
    ctx.stroke()

    // 扇区内小标签(如 57.11% 运行:7:59时)
    const innerLabelRadius = radius * 0.62
    const ilx = cx + Math.cos(midAngle) * innerLabelRadius
    const ily = cy + Math.sin(midAngle) * innerLabelRadius

    // 百分比大字
    ctx.fillStyle = '#fff'
    ctx.font = `bold ${Math.min(13, radius * 0.12)}px sans-serif`
    ctx.textAlign = 'center'
    ctx.textBaseline = 'middle'
    ctx.fillText(pct.toFixed(pct % 1 === 0 ? 0 : 1) + '%', ilx, ily - 6)

    // 状态+时长小字(在百分比下方)
    const statItem = stats.find(st => st.status === s)
    const durText = statItem ? statusLabel(s) + ':' + statItem.durationFormatted : statusLabel(s)
    ctx.font = `${Math.min(9, radius * 0.08)}px sans-serif`
    ctx.fillStyle = 'rgba(255,255,255,0.88)'
    ctx.fillText(durText, ilx, ily + 8)

    // 外部引导线末端标签(图例)
    const labelText = statusLabel(s)
    const tx = leX + textDir * 4
    const ty = leY + (isHover ? -2 : 4)

    // 图例色块
    ctx.fillStyle = STATUS_COLORS[s] || '#ccc'
    const boxSize = 8
    const boxTy = ty - boxSize / 2
    if (textDir > 0) {
      ctx.fillRect(tx, boxTy, boxSize, boxSize)
    } else {
      ctx.fillRect(tx - boxSize, boxTy, boxSize, boxSize)
    }

    ctx.fillStyle = isHover ? '#333' : '#555'
    ctx.font = `${isHover ? 'bold ' : ''}11px sans-serif`
    ctx.textAlign = textDir > 0 ? 'left' : 'right'
    ctx.textBaseline = 'middle'
    const labelTx = textDir > 0 ? tx + boxSize + 4 : tx - boxSize - 4
    ctx.fillText(labelText, labelTx, ty)
  })
}
</script>

<style scoped>
.safety-dialog :deep(.el-dialog) {
  max-height: 94vh;
  display: flex;
  flex-direction: column;
}
.safety-dialog :deep(.el-dialog__header) {
  padding: 10px 18px;
  border-bottom: 1px solid #e8e8e8;
  margin: 0;
  flex-shrink: 0;
}
.safety-dialog :deep(.el-dialog__body) {
  overflow: hidden;
  flex: 1;
  padding: 12px 14px;
}
.dialog-header {
  display: flex;
  align-items: center;
}
.title-text {
  font-size: 14px;
  font-weight: bold;
  color: #333;
  margin-right: 6px;
  white-space: nowrap;
}

.safety-body {
  height: 100%;
  display: flex;
  flex-direction: column;
}

/* ===== 主布局:左组合图 + 右统计 ===== */
.main-row {
  display: grid;
  grid-template-columns: 1fr 300px;
  gap: 14px;
  flex: 1;
  min-height: 0;
}

/* ===== 左侧组合图面板 ===== */
.combo-panel {
  background: #fff;
  border: 1px solid #e8e8e8;
  border-radius: 6px;
  padding: 12px 16px;
  display: flex;
  flex-direction: column;
  min-height: 0;
}
.panel-title-row {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 6px;
  flex-shrink: 0;
}
.panel-title {
  font-size: 14px;
  font-weight: bold;
  color: #333;
}
.duration-hint {
  font-size: 12px;
  color: #999;
}
.legend-right {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-left: auto;
  flex-wrap: wrap;
}
.leg {
  display: inline-flex;
  align-items: center;
  gap: 3px;
  font-size: 11px;
  color: #666;
}
.line-leg { gap: 2px; }

.combo-canvas-wrap {
  position: relative;
  flex: 1;
  min-height: 0;
}
.combo-canvas-wrap canvas {
  display: block;
  width: 100%;
  height: 100%;
}

/* ===== 右侧统计面板 ===== */
.stat-panel {
  background: #fff;
  border: 1px solid #e8e8e8;
  border-radius: 6px;
  padding: 12px 14px;
  display: flex;
  flex-direction: column;
  align-items: center;
}
.stat-duration {
  font-size: 12px;
  color: #999;
  margin-bottom: 4px;
}
.pie-canvas-wrap {
  width: 100%;
  position: relative;
  flex: 1;
  min-height: 0;
}
.pie-canvas-wrap canvas {
  display: block;
  width: 100%;
  height: 100%;
}
.stat-kwh-area {
  position: relative;
  top: -150px;
  text-align: center;
  flex-shrink: 0;
}
.sk-label {
  font-size: 12px;
  color: #888;
  margin-bottom: 2px;
}
.sk-value {
  font-size: 18px;
  font-weight: bold;
  color: #333;
}

/* ===== 图例圆点 & 线点 ===== */
.dot {
  display: inline-block;
  width: 10px;
  height: 10px;
  border-radius: 2px;
  flex-shrink: 0;
}
.dot.g { background: #67c23a; }
.dot.r { background: #e74c3c; }
.dot.y { background: #c5d94e; }
.dot.gy { background: #909399; }
.line-dot {
  display: inline-block;
  width: 12px;
  height: 2px;
  background: #409eff;
  vertical-align: middle;
  border-radius: 1px;
}
.line-dot-sm {
  display: inline-block;
  width: 8px;
  height: 2px;
  background: #409eff;
  vertical-align: middle;
  border-radius: 1px;
  margin-right: 3px;
}

/* ===== Tooltip: 组合图 ===== */
.combo-tooltip {
  position: absolute;
  background: rgba(30, 40, 55, 0.95);
  border-radius: 6px;
  padding: 8px 14px;
  min-width: 150px;
  z-index: 200;
  pointer-events: none;
  box-shadow: 0 6px 20px rgba(0,0,0,0.3);
}
.combo-tooltip::after {
  content: '';
  position: absolute;
  bottom: -7px;
  left: 20px;
  border-left: 7px solid transparent;
  border-right: 7px solid transparent;
  border-top: 7px solid rgba(30, 40, 55, 0.95);
}
.ctt-row {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 12px;
  line-height: 1.9;
  font-size: 12px;
}
.ctt-label {
  color: #aab2c0;
  flex-shrink: 0;
  display: flex;
  align-items: center;
  gap: 3px;
}
.ctt-val { color: #eef1f7; font-weight: 500; }
.ctt-highlight { font-weight: bold; }

/* ===== Tooltip: 饼图 ===== */
.pie-tooltip {
  position: absolute;
  background: rgba(30, 40, 55, 0.95);
  border-radius: 6px;
  padding: 8px 14px;
  min-width: 120px;
  z-index: 200;
  pointer-events: none;
  box-shadow: 0 4px 16px rgba(0,0,0,0.25);
}
.pie-tooltip::after {
  content: '';
  position: absolute;
  bottom: -7px;
  left: 18px;
  border-left: 7px solid transparent;
  border-right: 7px solid transparent;
  border-top: 7px solid rgba(30, 40, 55, 0.95);
}
.ptt-row {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 12px;
  line-height: 1.9;
  font-size: 12px;
}
.ptt-label { color: #aab2c0; flex-shrink: 0; }
.ptt-val { color: #eef1f7; font-weight: 500; display: flex; align-items: center; gap: 4px; }
.ptt-highlight { font-weight: bold; }
</style>