<template>
  <div class="screen-page">
    <!-- 顶部栏 -->
    <header class="screen-header">
      <div class="header-left">CNC机床数据采集系统</div>
      <div class="header-right">
        <span class="auto-refresh" style="color:#aaa; font-size:12px; margin-left:8px;">自动刷新: {{ refreshSecDisplay }} 秒</span>
        <span class="refresh-gear" @click="openRefreshDialog" style="cursor:pointer; margin-left:6px">⚙</span>
        <el-select v-model="filterWorkshop" placeholder="车间" size="small" style="width:120px;margin-right:8px" @change="refreshAll">
          <el-option label="全部" value="" />
          <el-option v-for="w in workshopOptions" :key="w" :label="w" :value="w" />
        </el-select>
        <el-select v-model="filterBrand" placeholder="品牌" size="small" style="width:120px;margin-right:16px" @change="refreshAll">
          <el-option label="全部" value="" />
          <el-option v-for="b in brandOptions" :key="b" :label="b" :value="b" />
        </el-select>
        <span class="header-time">{{ currentTime }}</span>
      </div>
    </header>

    <!-- 第一行：统计数字卡片 -->
    <div class="stat-row">
      <div class="stat-card" v-for="s in statCards" :key="s.key">
        <div class="stat-label">{{ s.label }}</div>
        <div class="stat-value" :style="{ color: s.color }">{{ s.value }}</div>
        <div class="stat-sub" v-if="s.sub">{{ s.sub }}</div>
      </div>
    </div>

    <!-- 第二行：图表区 -->
    <div class="chart-row">
      <div class="chart-card">
        <div class="chart-title">各车间产量</div>
        <div ref="barChartRef" class="chart-container"></div>
      </div>
      <div class="chart-card">
        <div class="chart-title">产量趋势(7天)</div>
        <div ref="lineChartRef" class="chart-container"></div>
      </div>
    </div>

    <!-- 第三行：排行+状态 -->
    <div class="bottom-row">
      <div class="rank-card">
        <div class="chart-title">机床产量排行</div>
        <div class="rank-list">
          <div v-if="machineRank.length === 0" class="no-data">暂无数据</div>
          <div v-for="item in machineRank" :key="item.rank ?? item.id" class="rank-item">
            <span class="rank-num" :class="{ 'rank-top': (item.rank ?? 99) <= 3 }">{{ item.rank ?? '-' }}</span>
            <span class="rank-name">{{ item.machineName }}</span>
            <span class="rank-value">{{ item.quantity }}</span>
          </div>
        </div>
      </div>
      <div class="rank-card">
        <div class="chart-title">工人产量排行</div>
        <div class="rank-list">
          <div v-if="workerRank.length === 0" class="no-data">暂无数据</div>
          <div v-for="item in workerRank" :key="item.rank ?? item.id" class="rank-item">
            <span class="rank-num" :class="{ 'rank-top': (item.rank ?? 99) <= 3 }">{{ item.rank ?? '-' }}</span>
            <span class="rank-name">{{ item.workerName }}</span>
            <span class="rank-value">{{ item.totalQuantity ?? item.machineCount ?? '-' }}</span>
          </div>
        </div>
      </div>
      <div class="status-card">
        <div class="chart-title">机床状态总览</div>
        <div class="status-grid">
          <div v-if="machineStatus.length === 0" class="no-data">暂无机床</div>
          <div v-for="m in machineStatus" :key="m.machineId" class="status-block" :class="m.isOnline ? 'online' : 'offline'" :title="m.machineName"></div>
        </div>
        <div class="status-legend">
          <span class="legend-item"><span class="legend-block online"></span> 在线</span>
          <span class="legend-item"><span class="legend-block offline"></span> 离线</span>
        </div>
      </div>
    </div>
  </div>

  <!-- 刷新间隔设置对话框 -->
  <el-dialog v-model="refreshDialogVisible" title="刷新间隔设置" width="320px" >
    <el-form label-width="90px">
      <el-form-item label="间隔(秒)">
        <el-input-number v-model="refreshSecondsInput" :min="1" :step="1" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="refreshDialogVisible = false">取消</el-button>
      <el-button type="primary" @click="applyRefreshInterval">确定</el-button>
    </template>
  </el-dialog>
</template>
﻿
<script setup lang="ts">
import { ref, reactive, onMounted, onUnmounted, nextTick, computed } from 'vue'
import echarts from '@/utils/echarts'
// 引入 ECharts 的类型定义，便于 TS 断言
import type { ECharts } from 'echarts/core'
import { ElMessage } from 'element-plus'
import request from '@/utils/request'
import { watch } from 'vue'
import type { MachineRankRow, WorkerRankRow } from '@/types'

const filterWorkshop = ref('')
const filterBrand = ref('')
const workshopOptions = ref<string[]>([])
const brandOptions = ref<string[]>([])
const currentTime = ref('')
let timeTimer: ReturnType<typeof setInterval> | null = null

const statCards = reactive([
  { key: 'online', label: '在线机床', value: '--', sub: '', color: '#00e5ff' },
  { key: 'production', label: '今日总产量', value: '--', sub: '', color: '#76ff03' },
  { key: 'collector', label: '采集服务', value: '--', sub: '', color: '#69f0ae' },
  { key: 'alerts', label: '活跃告警', value: '--', sub: '', color: '#ffd740' },
  { key: 'avg', label: '平均产量/台', value: '--', sub: '', color: '#e0e0e0' },
])

const barChartRef = ref<HTMLElement>()
const lineChartRef = ref<HTMLElement>()
let barChart: ECharts | null = null
let lineChart: ECharts | null = null

const machineRank = ref<MachineRankRow[]>([])
const workerRank = ref<WorkerRankRow[]>([])
const machineStatus = ref<any[]>([])

let refreshTimer: ReturnType<typeof setInterval> | null = null
const refreshIntervalMs = ref<number>(10000)
const refreshSecondsInput = ref<number>(10)
const refreshDialogVisible = ref(false)
const refreshSecDisplay = computed(() => Math.max(1, Math.floor(refreshIntervalMs.value / 1000)))

function updateTime() {
  const now = new Date()
  currentTime.value = now.toLocaleString('zh-CN', {
    year: 'numeric', month: '2-digit', day: '2-digit',
    hour: '2-digit', minute: '2-digit', second: '2-digit', hour12: false,
  })
}

function filterParams(): Record<string, string> {
  const p: Record<string, string> = {}
  if (filterWorkshop.value) p.workshop = filterWorkshop.value
  if (filterBrand.value) p.brand = filterBrand.value
  return p
}

async function loadFilters() {
  try {
    const r = await request.get('/screen/filters') as any
    const items = r.data?.items || []
    workshopOptions.value = items.filter((i: Record<string,unknown>) => i.filterType === 'workshop').map((i: Record<string,unknown>) => i.filterValue)
    brandOptions.value = items.filter((i: Record<string,unknown>) => i.filterType === 'brand').map((i: Record<string,unknown>) => i.filterValue)
    const defW = items.find((i: Record<string,unknown>) => i.filterType === 'workshop' && i.isDefault === 1)
    if (defW) filterWorkshop.value = defW.filterValue
    const defB = items.find((i: Record<string,unknown>) => i.filterType === 'brand' && i.isDefault === 1)
    if (defB) filterBrand.value = defB.filterValue
  } catch { /* 静默 */ }
}

async function loadSummary() {
  try {
    const r = await request.get('/screen/summary', { params: filterParams() }) as any
    const d = r.data || {}
    statCards[0].value = d.onlineCount != null ? String(d.onlineCount) : '--'
    statCards[0].sub = d.totalMachines ? '/ ' + d.totalMachines : ''
    statCards[1].value = d.todayProduction != null ? d.todayProduction.toLocaleString() : '--'
    statCards[3].value = d.activeAlerts != null ? String(d.activeAlerts) : '--'
    statCards[4].value = d.avgQuantityPerMachine != null ? String(d.avgQuantityPerMachine) : '--'
  } catch { /* 静默 */ }
}

async function loadCollectorStatus() {
  try {
    const r = await request.get('/screen/collector-status') as any
    const d = r.data || {}
    if (d.status === 'running') {
      statCards[2].value = '运行中'
      statCards[2].sub = d.uptime || ''
      statCards[2].color = '#69f0ae'
    } else {
      statCards[2].value = '已停止'
      statCards[2].sub = ''
      statCards[2].color = '#ff5252'
    }
  } catch { /* 静默 */ }
}

async function loadWorkshopProduction() {
  try {
    const r = await request.get('/screen/workshop-production', { params: filterParams() }) as any
    const items = r.data?.items || []
    if (!barChart) return
    barChart.setOption({
      tooltip: { trigger: 'axis' },
      grid: { left: 60, right: 20, top: 20, bottom: 30 },
      xAxis: { type: 'category', data: items.map((i: Record<string,unknown>) => i.name), axisLabel: { color: '#aaa' }, axisLine: { lineStyle: { color: '#333' } } },
      yAxis: { type: 'value', axisLabel: { color: '#aaa' }, splitLine: { lineStyle: { color: '#222' } } },
      series: [{ type: 'bar', data: items.map((i: Record<string,unknown>) => i.quantity), itemStyle: { color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{ offset: 0, color: '#00e5ff' }, { offset: 1, color: '#006064' }]) }, barWidth: 30 }],
    })
  } catch { /* 静默 */ }
}

async function loadProductionTrend() {
  try {
    const r = await request.get('/screen/production-trend', { params: filterParams() }) as any
    const items = r.data?.items || []
    if (!lineChart) return
    lineChart.setOption({
      tooltip: { trigger: 'axis' },
      grid: { left: 60, right: 20, top: 20, bottom: 30 },
      xAxis: { type: 'category', data: items.map((i: Record<string,unknown>) => i.date), axisLabel: { color: '#aaa' }, axisLine: { lineStyle: { color: '#333' } } },
      yAxis: { type: 'value', axisLabel: { color: '#aaa' }, splitLine: { lineStyle: { color: '#222' } } },
      series: [{
        type: 'line', data: items.map((i: Record<string,unknown>) => i.quantity), smooth: true,
        lineStyle: { color: '#76ff03', width: 2 }, itemStyle: { color: '#76ff03' },
        areaStyle: { color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{ offset: 0, color: 'rgba(118,255,3,0.3)' }, { offset: 1, color: 'rgba(118,255,3,0)' }]) },
      }],
    })
  } catch { /* 静默 */ }
}

async function loadMachineRank() {
  try {
    const r = await request.get('/screen/machine-rank', { params: filterParams() }) as any
    machineRank.value = r.data?.items || []
  } catch { /* 静默 */ }
}

async function loadWorkerRank() {
  try {
    const r = await request.get('/screen/worker-rank', { params: filterParams() }) as any
    workerRank.value = r.data?.items || []
  } catch { /* 静默 */ }
}

async function loadMachineStatus() {
  try {
    const r = await request.get('/screen/machine-status', { params: filterParams() }) as any
    machineStatus.value = r.data?.items || []
  } catch { /* 静默 */ }
}

function refreshAll() {
  loadSummary()
  loadCollectorStatus()
  loadWorkshopProduction()
  loadProductionTrend()
  loadMachineRank()
  loadWorkerRank()
  loadMachineStatus()
}

function initCharts() {
  if (barChartRef.value) {
    barChart = echarts.init(barChartRef.value)
    barChart.setOption({ backgroundColor: 'transparent' })
  }
  if (lineChartRef.value) {
    lineChart = echarts.init(lineChartRef.value)
    lineChart.setOption({ backgroundColor: 'transparent' })
  }
}

function handleResize() {
  barChart?.resize()
  lineChart?.resize()
}

onMounted(async () => {
  updateTime()
  timeTimer = setInterval(updateTime, 1000)
  ElMessage({ message: '按F11进入全屏模式', type: 'info', duration: 5000 })
  await loadFilters()
  await nextTick()
  initCharts()
  await fetchRefreshInterval()
  refreshAll()
  // 初始化刷新间隔与定时器
  refreshTimer = setInterval(refreshAll, refreshIntervalMs.value)
  window.addEventListener('resize', handleResize)
})

onUnmounted(() => {
  if (timeTimer) clearInterval(timeTimer)
  if (refreshTimer) clearInterval(refreshTimer)
  barChart?.dispose()
  lineChart?.dispose()
  window.removeEventListener('resize', handleResize)
})

// 读取配置中的刷新间隔
async function fetchRefreshInterval() {
  try {
    const r = await request.get('/screen/refresh-interval') as any
    const v = r?.data?.interval ?? 10000
    refreshIntervalMs.value = v
  } catch {
    // 若请求失败，保持默认值
  }
}

watch(refreshIntervalMs, (newVal) => {
  if (refreshTimer) clearInterval(refreshTimer)
  refreshTimer = setInterval(refreshAll, newVal)
})

function openRefreshDialog() {
  refreshSecondsInput.value = Math.max(1, Math.floor(refreshIntervalMs.value / 1000))
  refreshDialogVisible.value = true
}

async function applyRefreshInterval() {
  const seconds = Number(refreshSecondsInput.value)
  if (!Number.isFinite(seconds) || seconds <= 0) {
    ElMessage.error('请输入有效秒数')
    return
  }
  refreshIntervalMs.value = seconds * 1000
  refreshDialogVisible.value = false
}
</script>
﻿
<style scoped>
.screen-page {
  background: #0f0f1a;
  color: #e0e0e0;
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  font-family: 'Microsoft YaHei', sans-serif;
  overflow: hidden;
}
.screen-header {
  height: 50px;
  background: #1a1a2e;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 24px;
  border-bottom: 1px solid #2a2a3e;
  flex-shrink: 0;
}
.header-left {
  font-size: 20px;
  font-weight: bold;
  color: #00e5ff;
  letter-spacing: 2px;
}
.header-right {
  display: flex;
  align-items: center;
}
.header-time {
  color: #aaa;
  font-size: 14px;
  font-family: 'Consolas', monospace;
}
.stat-row {
  display: flex;
  gap: 16px;
  padding: 16px 24px;
  flex-shrink: 0;
}
.stat-card {
  flex: 1;
  background: #1a1a2e;
  border-radius: 8px;
  padding: 12px 16px;
  text-align: center;
  border: 1px solid #2a2a3e;
  transition: box-shadow 0.3s;
}
.stat-card:hover {
  box-shadow: 0 0 12px rgba(0, 229, 255, 0.15);
}
.stat-label {
  font-size: 13px;
  color: #909399;
  margin-bottom: 4px;
}
.stat-value {
  font-size: 28px;
  font-weight: bold;
  letter-spacing: 1px;
}
.stat-sub {
  font-size: 12px;
  color: #606266;
  margin-top: 2px;
}
.chart-row {
  display: flex;
  gap: 16px;
  padding: 0 24px 16px;
  flex-shrink: 0;
}
.chart-card {
  flex: 1;
  background: #1a1a2e;
  border-radius: 8px;
  padding: 12px;
  border: 1px solid #2a2a3e;
  height: 300px;
}
.chart-title {
  font-size: 14px;
  color: #bbb;
  margin-bottom: 8px;
}
.chart-container {
  width: 100%;
  height: calc(100% - 30px);
}
.bottom-row {
  display: flex;
  gap: 16px;
  padding: 0 24px 16px;
  flex: 1;
  min-height: 0;
}
.rank-card {
  flex: 1;
  background: #1a1a2e;
  border-radius: 8px;
  padding: 12px;
  border: 1px solid #2a2a3e;
  display: flex;
  flex-direction: column;
}
.rank-list {
  flex: 1;
  overflow-y: auto;
}
.rank-item {
  display: flex;
  align-items: center;
  padding: 6px 0;
  border-bottom: 1px solid #2a2a3e;
}
.rank-item:last-child { border-bottom: none; }
.rank-num {
  width: 24px;
  height: 24px;
  border-radius: 4px;
  background: #2a2a3e;
  color: #909399;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  font-size: 12px;
  margin-right: 10px;
  flex-shrink: 0;
}
.rank-num.rank-top {
  background: #00e5ff;
  color: #0f0f1a;
  font-weight: bold;
}
.rank-name {
  flex: 1;
  font-size: 13px;
}
.rank-value {
  font-size: 14px;
  font-weight: bold;
  color: #76ff03;
}
.status-card {
  flex: 1;
  background: #1a1a2e;
  border-radius: 8px;
  padding: 12px;
  border: 1px solid #2a2a3e;
  display: flex;
  flex-direction: column;
}
.status-grid {
  flex: 1;
  display: flex;
  flex-wrap: wrap;
  gap: 6px;
  align-content: flex-start;
  overflow-y: auto;
}
.status-block {
  width: 18px;
  height: 18px;
  border-radius: 3px;
  cursor: default;
}
.status-block.online {
  background: #4caf50;
  box-shadow: 0 0 4px rgba(76, 175, 80, 0.5);
}
.status-block.offline {
  background: #555;
}
.status-legend {
  display: flex;
  gap: 16px;
  margin-top: 8px;
  font-size: 12px;
  color: #999;
}
.legend-item {
  display: flex;
  align-items: center;
  gap: 4px;
}
.legend-block {
  width: 12px;
  height: 12px;
  border-radius: 2px;
  display: inline-block;
}
.legend-block.online {
  background: #4caf50;
}
.legend-block.offline {
  background: #555;
}
.no-data {
  color: #666;
  text-align: center;
  padding: 20px;
  font-size: 13px;
}
</style>
