SmartLightH5Utilization.vue 15.9 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
<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>

      <div class="query">
        <el-radio-group v-model="queryMode" size="small">
          <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>
        <el-date-picker
          v-if="queryMode === 'day'"
          v-model="queryDateRange"
          type="daterange"
          start-placeholder="开始"
          end-placeholder="结束"
          value-format="YYYY-MM-DD"
          size="small"
          class="range"
        />
        <el-button type="primary" size="small" :loading="loading" @click="fetchOeeData">查询</el-button>
      </div>

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

      <template v-else>
        <div class="section">
          <div class="section-title">颜色时长明细</div>
          <div class="legend-inline">
            <span class="leg"><i class="dot green"></i>绿灯</span>
            <span class="leg"><i class="dot yellow"></i>黄灯</span>
            <span class="leg"><i class="dot red"></i>红灯</span>
            <span class="leg"><i class="dot gray"></i>离线</span>
          </div>
          <div class="canvas-scroll">
            <div class="canvas-wrap">
              <canvas ref="durCanvas" :width="durCanvasW" :height="240"></canvas>
            </div>
          </div>
        </div>

        <div class="section">
          <div class="section-title">颜色时长总计</div>
          <div class="pie-wrap">
            <canvas ref="durPieCanvas" width="200" height="200"></canvas>
          </div>
          <div class="pie-legend">
            <div class="pleg"><span class="pdot green"></span>绿灯</div>
            <div class="pleg"><span class="pdot yellow"></span>黄灯</div>
            <div class="pleg"><span class="pdot red"></span>红灯</div>
            <div class="pleg"><span class="pdot gray"></span>离线</div>
          </div>
        </div>

        <div class="section">
          <div class="section-title">颜色次数明细</div>
          <div class="legend-inline">
            <span class="leg"><i class="dot green"></i>绿灯</span>
            <span class="leg"><i class="dot yellow"></i>黄灯</span>
            <span class="leg"><i class="dot red"></i>红灯</span>
            <span class="leg"><i class="dot gray"></i>离线</span>
          </div>
          <div class="canvas-scroll">
            <div class="canvas-wrap">
              <canvas ref="freqCanvas" :width="freqCanvasW" :height="260"></canvas>
            </div>
          </div>
        </div>

        <div class="section">
          <div class="section-title">颜色次数总计</div>
          <div class="pie-wrap">
            <canvas ref="freqPieCanvas" width="200" height="200"></canvas>
          </div>
          <div class="pie-legend">
            <div class="pleg"><span class="pdot green"></span>绿灯</div>
            <div class="pleg"><span class="pdot yellow"></span>黄灯</div>
            <div class="pleg"><span class="pdot red"></span>红灯</div>
            <div class="pleg"><span class="pdot gray"></span>离线</div>
          </div>
        </div>
      </template>
    </div>
  </div>
</template>

<script setup>
import { computed, nextTick, onMounted, 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 queryMode = ref('day')
const now = new Date()
const weekAgo = new Date(now)
weekAgo.setDate(weekAgo.getDate() - 6)
const queryDateRange = ref([formatDate(weekAgo), formatDate(now)])

const loading = ref(false)
const oeeData = ref(null)

const summary = computed(() => oeeData.value?.summary || {})
const displayList = computed(() => oeeData.value?.list || [])

const padL = 50
const padB = 24
const COLORS = { green: '#67c23a', yellow: '#e6a23c', red: '#f56c6c', off: '#909399' }
const COLOR_NAMES = { green: '绿灯', yellow: '黄灯', red: '红灯', off: '离线' }

const durCanvas = ref(null)
const freqCanvas = ref(null)
const durPieCanvas = ref(null)
const freqPieCanvas = ref(null)

const durCanvasW = computed(() => {
  const n = Math.max(displayList.value.length, 1)
  return Math.max(360, padL + n * 64 + 20)
})
const freqCanvasW = computed(() => {
  const n = Math.max(displayList.value.length, 1)
  return Math.max(360, padL + n * 64 + 20)
})

const maxDurSec = computed(() => {
  const list = displayList.value
  if (!list.length) return 86400
  let max = 1
  list.forEach(item => {
    const total = (item.off?.seconds || 0) + (item.red?.seconds || 0) + (item.yellow?.seconds || 0) + (item.green?.seconds || 0)
    max = Math.max(max, total)
  })
  return max
})

const maxFreqCount = computed(() => {
  const list = displayList.value
  if (!list.length) return 100
  let max = 1
  list.forEach(item => {
    const total = (item.off?.count || 0) + (item.red?.count || 0) + (item.yellow?.count || 0) + (item.green?.count || 0)
    max = Math.max(max, total)
  })
  return max
})

const durPieSegs = computed(() => {
  const s = summary.value
  const items = [
    { key: 'green', name: '绿灯', val: s.green?.seconds || 0, color: COLORS.green },
    { key: 'yellow', name: '黄灯', val: s.yellow?.seconds || 0, color: COLORS.yellow },
    { key: 'red', name: '红灯', val: s.red?.seconds || 0, color: COLORS.red },
    { key: 'off', name: '离线', val: s.off?.seconds || 0, color: COLORS.off }
  ].filter(x => x.val > 0).sort((a, b) => b.val - a.val)
  const total = items.reduce((sum, x) => sum + x.val, 0) || 1
  let angle = -Math.PI / 2
  return items.map(item => {
    const sweep = (item.val / total) * Math.PI * 2
    const seg = { ...item, startAngle: angle, endAngle: angle + sweep, pct: ((item.val / total) * 100).toFixed(2) }
    angle += sweep
    return seg
  })
})

const freqPieSegs = computed(() => {
  const s = summary.value
  const items = [
    { key: 'green', name: '绿灯', val: s.green?.count || 0, color: COLORS.green },
    { key: 'yellow', name: '黄灯', val: s.yellow?.count || 0, color: COLORS.yellow },
    { key: 'red', name: '红灯', val: s.red?.count || 0, color: COLORS.red },
    { key: 'off', name: '离线', val: s.off?.count || 0, color: COLORS.off }
  ].filter(x => x.val > 0).sort((a, b) => b.val - a.val)
  const total = items.reduce((sum, x) => sum + x.val, 0) || 1
  let angle = -Math.PI / 2
  return items.map(item => {
    const sweep = (item.val / total) * Math.PI * 2
    const seg = { ...item, startAngle: angle, endAngle: angle + sweep, pct: ((item.val / total) * 100).toFixed(2) }
    angle += sweep
    return seg
  })
})

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

function formatDateShort(s) {
  if (!s) return ''
  return String(s).slice(5)
}

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

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

function drawDurBar() {
  const cvs = durCanvas.value
  if (!cvs) return
  const wrap = cvs.parentElement
  const cssH = 240
  const cssW = Math.max(wrap ? wrap.clientWidth : durCanvasW.value, durCanvasW.value)
  const { ctx, W, H } = setupCanvas(cvs, cssW, cssH)
  ctx.clearRect(0, 0, W, H)

  const plotTop = 18
  const plotBottom = H - padB
  const plotH = plotBottom - plotTop
  const n = displayList.value.length
  const groupW = n ? (W - padL - 10) / n : 1
  const maxSec = maxDurSec.value || 1

  ctx.font = '10px sans-serif'
  ctx.fillStyle = '#999'
  ctx.textAlign = 'right'
  const tickCount = 5
  for (let i = 0; i <= tickCount; i++) {
    const sec = (maxSec * i) / tickCount
    const y = plotBottom - (i / tickCount) * plotH + 3
    const h = Math.floor(sec / 3600)
    const m = Math.floor((sec % 3600) / 60)
    ctx.fillText(h > 0 ? `${h}时` : `${m}分`, 32, y)
  }

  ctx.font = '9px sans-serif'
  ctx.fillStyle = '#666'
  ctx.textAlign = 'center'
  displayList.value.forEach((item, i) => {
    ctx.fillText(item.label || formatDateShort(item.startDate), padL + (i + 0.5) * groupW, H - 4)
  })

  ctx.strokeStyle = '#f0f0f0'
  ctx.lineWidth = 1
  for (let i = 0; i <= tickCount; i++) {
    const y = plotBottom - (i / tickCount) * plotH
    ctx.beginPath()
    ctx.moveTo(padL, y)
    ctx.lineTo(W - 10, y)
    ctx.stroke()
  }

  displayList.value.forEach((item, idx) => {
    const bx = padL + idx * groupW + (groupW - Math.min(groupW - 8, 44)) / 2
    const bw = Math.min(groupW - 8, 44)
    const scale = plotH / maxSec
    let curY = plotBottom
    const stack = [
      { k: 'off', sec: item.off?.seconds || 0 },
      { k: 'red', sec: item.red?.seconds || 0 },
      { k: 'yellow', sec: item.yellow?.seconds || 0 },
      { k: 'green', sec: item.green?.seconds || 0 }
    ]
    stack.forEach(seg => {
      if (!seg.sec) return
      const h = seg.sec * scale
      curY -= h
      ctx.fillStyle = COLORS[seg.k]
      ctx.fillRect(bx, curY, bw, h)
    })
  })
}

function drawFreqBar() {
  const cvs = freqCanvas.value
  if (!cvs) return
  const wrap = cvs.parentElement
  const cssH = 260
  const cssW = Math.max(wrap ? wrap.clientWidth : freqCanvasW.value, freqCanvasW.value)
  const { ctx, W, H } = setupCanvas(cvs, cssW, cssH)
  ctx.clearRect(0, 0, W, H)

  const plotTop = 22
  const plotBottom = H - padB
  const plotH = plotBottom - plotTop
  const n = displayList.value.length
  const groupW = n ? (W - padL - 10) / n : 1
  const maxCnt = maxFreqCount.value || 1

  ctx.font = '10px sans-serif'
  ctx.fillStyle = '#999'
  ctx.textAlign = 'right'
  const tickCount = 6
  const step = Math.ceil(maxCnt / tickCount / 10) * 10 || 10
  for (let i = 0; i <= tickCount; i++) {
    const y = plotBottom - (i / tickCount) * plotH + 3
    ctx.fillText(i * step + '次', 32, y)
  }

  ctx.font = '9px sans-serif'
  ctx.fillStyle = '#666'
  ctx.textAlign = 'center'
  displayList.value.forEach((item, i) => {
    ctx.fillText(item.label || formatDateShort(item.startDate), padL + (i + 0.5) * groupW, H - 4)
  })

  ctx.strokeStyle = '#f0f0f0'
  ctx.lineWidth = 1
  for (let i = 0; i <= tickCount; i++) {
    const y = plotBottom - (i / tickCount) * plotH
    ctx.beginPath()
    ctx.moveTo(padL, y)
    ctx.lineTo(W - 10, y)
    ctx.stroke()
  }

  displayList.value.forEach((item, idx) => {
    const bx = padL + idx * groupW + (groupW - Math.min(groupW - 8, 44)) / 2
    const bw = Math.min(groupW - 8, 44)
    const scale = plotH / (step * tickCount)
    let curY = plotBottom
    const stack = [
      { k: 'off', cnt: item.off?.count || 0 },
      { k: 'red', cnt: item.red?.count || 0 },
      { k: 'yellow', cnt: item.yellow?.count || 0 },
      { k: 'green', cnt: item.green?.count || 0 }
    ]
    stack.forEach(seg => {
      if (!seg.cnt) return
      const h = seg.cnt * scale
      curY -= h
      ctx.fillStyle = COLORS[seg.k]
      ctx.fillRect(bx, curY, bw, h)
    })
  })
}

function drawPie(cvsRef, segs) {
  const cvs = cvsRef.value
  if (!cvs) return
  const { ctx } = setupCanvas(cvs, 200, 200)
  ctx.clearRect(0, 0, 200, 200)
  const cx = 100
  const cy = 100
  const R = 74

  if (!segs.length) {
    ctx.beginPath()
    ctx.arc(cx, cy, R, 0, Math.PI * 2)
    ctx.fillStyle = '#eee'
    ctx.fill()
    ctx.fillStyle = '#999'
    ctx.font = '12px sans-serif'
    ctx.textAlign = 'center'
    ctx.textBaseline = 'middle'
    ctx.fillText('暂无数据', cx, cy)
    return
  }

  segs.forEach(seg => {
    ctx.beginPath()
    ctx.moveTo(cx, cy)
    ctx.arc(cx, cy, R, seg.startAngle, seg.endAngle)
    ctx.closePath()
    ctx.fillStyle = seg.color
    ctx.fill()
  })

  ctx.fillStyle = '#fff'
  ctx.textAlign = 'center'
  ctx.textBaseline = 'middle'
  segs.forEach(seg => {
    const midAngle = (seg.startAngle + seg.endAngle) / 2
    const tx = cx + Math.cos(midAngle) * R * 0.58
    const ty = cy + Math.sin(midAngle) * R * 0.58
    ctx.font = 'bold 12px sans-serif'
    ctx.fillText(seg.pct + '%', tx, ty - 6)
    ctx.font = '10px sans-serif'
    ctx.fillText(seg.name, tx, ty + 7)
  })
}

function redrawAll() {
  nextTick(() => {
    drawDurBar()
    drawFreqBar()
    drawPie(durPieCanvas, durPieSegs.value)
    drawPie(freqPieCanvas, freqPieSegs.value)
  })
}

async function fetchOeeData() {
  if (!dtuSn.value) return
  let params = `dtuSn=${encodeURIComponent(dtuSn.value)}&type=${encodeURIComponent(queryMode.value)}`
  if (queryMode.value === 'day') {
    const [start, end] = queryDateRange.value || []
    if (!start || !end) return
    params += `&startDate=${encodeURIComponent(start)}&endDate=${encodeURIComponent(end)}`
  }
  loading.value = true
  try {
    const res = await apiFetch(`/api/device/oeeStats?${params}`)
    oeeData.value = await res.json()
  } catch (e) {
    ElMessage.error('获取稼动率数据失败')
    console.warn(e)
  } finally {
    loading.value = false
  }
}

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

watch([durCanvasW, freqCanvasW], () => redrawAll())
watch(oeeData, () => redrawAll(), { deep: true })
watch(queryMode, () => fetchOeeData())
watch(queryDateRange, () => {
  if (queryMode.value === 'day') fetchOeeData()
})

onMounted(() => {
  if (dtuSn.value) fetchOeeData()
})
</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;
  flex-wrap: wrap;
  gap: 8px;
  margin-bottom: 10px;
}

.range {
  width: 100%;
}

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

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

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

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

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

.dot.yellow {
  background: #e6a23c;
}

.dot.red {
  background: #f56c6c;
}

.dot.gray {
  background: #909399;
}

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

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

.pie-wrap {
  display: flex;
  justify-content: center;
  padding-top: 6px;
}

.pie-legend {
  display: grid;
  grid-template-columns: repeat(2, minmax(0, 1fr));
  gap: 8px;
  margin-top: 10px;
  color: #475569;
  font-size: 12px;
}

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

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

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

.pdot.yellow {
  background: #e6a23c;
}

.pdot.red {
  background: #f56c6c;
}

.pdot.gray {
  background: #909399;
}
</style>