<template>
  <div class="screen-wrapper">
    <div class="screen-content">
      <header class="screen-header">
        <h1 class="title">OEE综合监控大屏</h1>
        <div class="header-right">
          <span class="current-shift">当前班组：{{ currentShift }}</span>
          <span class="time">{{ currentTime }}</span>
        </div>
      </header>

      <main class="screen-body">
        <div class="kpi-grid">
          <div class="kpi-card">
            <div class="kpi-title">OEE</div>
            <div class="kpi-value oee">{{ oeeData.oee.toFixed(1) }}%</div>
            <div class="kpi-trend" :class="oeeData.oeeTrend">
              <span>{{ oeeData.oeeTrend > 0 ? '↑' : '↓' }}</span>
              {{ Math.abs(oeeData.oeeTrend).toFixed(1) }}%
            </div>
          </div>
          <div class="kpi-card">
            <div class="kpi-title">时间稼动率</div>
            <div class="kpi-value availability">{{ oeeData.availability.toFixed(1) }}%</div>
            <div class="kpi-trend" :class="oeeData.availabilityTrend">
              <span>{{ oeeData.availabilityTrend > 0 ? '↑' : '↓' }}</span>
              {{ Math.abs(oeeData.availabilityTrend).toFixed(1) }}%
            </div>
          </div>
          <div class="kpi-card">
            <div class="kpi-title">性能稼动率</div>
            <div class="kpi-value performance">{{ oeeData.performance.toFixed(1) }}%</div>
            <div class="kpi-trend" :class="oeeData.performanceTrend">
              <span>{{ oeeData.performanceTrend > 0 ? '↑' : '↓' }}</span>
              {{ Math.abs(oeeData.performanceTrend).toFixed(1) }}%
            </div>
          </div>
          <div class="kpi-card">
            <div class="kpi-title">良品率</div>
            <div class="kpi-value quality">{{ oeeData.quality.toFixed(1) }}%</div>
            <div class="kpi-trend" :class="oeeData.qualityTrend">
              <span>{{ oeeData.qualityTrend > 0 ? '↑' : '↓' }}</span>
              {{ Math.abs(oeeData.qualityTrend).toFixed(1) }}%
            </div>
          </div>
        </div>

        <div class="chart-row">
          <div class="chart-box flex-2">
            <div class="box-title">OEE趋势分析</div>
            <div ref="trendChartRef" class="chart"></div>
          </div>
          <div class="chart-box flex-1">
            <div class="box-title">7大损失分布</div>
            <div ref="lossChartRef" class="chart"></div>
          </div>
        </div>

        <div class="chart-row">
          <div class="chart-box flex-1">
            <div class="box-title">设备状态监控</div>
            <div ref="statusChartRef" class="chart"></div>
          </div>
          <div class="chart-box flex-2">
            <div class="box-title">停机事件明细</div>
            <div class="event-table">
              <el-table :data="stoppageList" border size="small" max-height="280">
                <el-table-column prop="startDate" label="停机时间" width="160" />
                <el-table-column prop="duration" label="时长(分钟)" width="100" align="center" />
                <el-table-column prop="stopType" label="停机类型" width="120" />
                <el-table-column prop="unit" label="设备单元" width="100" />
                <el-table-column prop="shift" label="班组" width="80" />
                <el-table-column prop="remark" label="原因说明" />
              </el-table>
            </div>
          </div>
        </div>
      </main>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount, onUnmounted, nextTick } from 'vue'
import * as echarts from 'echarts'
import { getOeeDailySummary, getOeeLossSummary, getOeeStoppageEvents } from '@/api/acidOee'

const currentTime = ref('')
const currentShift = ref('甲班')
const trendChartRef = ref(null)
const lossChartRef = ref(null)
const statusChartRef = ref(null)
let trendChart = null
let lossChart = null
let statusChart = null
let timeInterval = null
let dataInterval = null
let resizeObserver = null

const oeeData = ref({
  oee: 0,
  availability: 0,
  performance: 0,
  quality: 0,
  oeeTrend: 0,
  availabilityTrend: 0,
  performanceTrend: 0,
  qualityTrend: 0
})

const summaryList = ref([])
const lossList = ref([])
const stoppageList = ref([])

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

const loadData = async () => {
  try {
    const today = new Date().toISOString().split('T')[0]
    const monthStart = today.substring(0, 7) + '-01'

    const [summaryRes, lossRes, eventsRes] = await Promise.all([
      getOeeDailySummary({ startDate: monthStart, endDate: today }),
      getOeeLossSummary({ topN: 7 }),
      getOeeStoppageEvents({ pageSize: 10 })
    ])

    if (summaryRes?.data && summaryRes.data.length > 0) {
      summaryList.value = summaryRes.data
      const latest = summaryRes.data[0]
      const previous = summaryRes.data[1] || latest

      oeeData.value = {
        oee: latest.oee || 0,
        availability: latest.availability || 0,
        performance: latest.performanceTon || 0,
        quality: latest.quality || 0,
        oeeTrend: (latest.oee || 0) - (previous.oee || 0),
        availabilityTrend: (latest.availability || 0) - (previous.availability || 0),
        performanceTrend: (latest.performanceTon || 0) - (previous.performanceTon || 0),
        qualityTrend: (latest.quality || 0) - (previous.quality || 0)
      }
    }

    if (lossRes?.data) {
      lossList.value = lossRes.data
    }

    if (eventsRes?.rows) {
      stoppageList.value = eventsRes.rows
    }

    updateCharts()
  } catch (error) {
    console.error('加载OEE数据失败:', error)
    loadMockData()
  }
}

const loadMockData = () => {
  summaryList.value = [
    { statDate: '05-11', oee: 85.2, availability: 91.5, performanceTon: 88.7, quality: 97.2 },
    { statDate: '05-12', oee: 86.8, availability: 92.8, performanceTon: 89.5, quality: 97.8 },
    { statDate: '05-13', oee: 85.9, availability: 91.2, performanceTon: 89.2, quality: 97.5 },
    { statDate: '05-14', oee: 87.2, availability: 93.5, performanceTon: 90.1, quality: 98.0 },
    { statDate: '05-15', oee: 86.5, availability: 92.1, performanceTon: 89.8, quality: 97.5 }
  ]

  lossList.value = [
    { lossCategoryName: '设备故障', lossTimeMin: 350, lossTimeRate: 31.8 },
    { lossCategoryName: '换模换线', lossTimeMin: 85, lossTimeRate: 24.5 },
    { lossCategoryName: '空转停机', lossTimeMin: 55, lossTimeRate: 15.8 },
    { lossCategoryName: '速度损失', lossTimeMin: 45, lossTimeRate: 12.9 },
    { lossCategoryName: '质量损失', lossTimeMin: 25, lossTimeRate: 7.2 },
    { lossCategoryName: '启动损失', lossTimeMin: 15, lossTimeRate: 4.3 },
    { lossCategoryName: '管理损失', lossTimeMin: 6, lossTimeRate: 1.7 }
  ]

  stoppageList.value = [
    { startDate: '2024-05-15 14:25:00', duration: 120, stopType: '设备故障', unit: '1#轧机', shift: '甲班', remark: '电机故障' },
    { startDate: '2024-05-15 13:15:00', duration: 45, stopType: '换模换线', unit: '2#轧机', shift: '乙班', remark: '更换模具' },
    { startDate: '2024-05-15 11:30:00', duration: 15, stopType: '计划停机', unit: '1#轧机', shift: '甲班', remark: '例行检查' }
  ]

  oeeData.value = {
    oee: 86.5,
    availability: 92.1,
    performance: 89.8,
    quality: 97.5,
    oeeTrend: 0.5,
    availabilityTrend: 0.3,
    performanceTrend: 0.2,
    qualityTrend: 0.1
  }

  updateCharts()
}

const updateCharts = () => {
  updateTrendChart()
  updateLossChart()
  updateStatusChart()
}

const updateTrendChart = () => {
  if (!trendChart) return

  const dates = summaryList.value.map(item => item.statDate)
  const oeeValues = summaryList.value.map(item => item.oee)
  const avalValues = summaryList.value.map(item => item.availability)
  const perfValues = summaryList.value.map(item => item.performanceTon)
  const qualValues = summaryList.value.map(item => item.quality)

  trendChart.setOption({
    backgroundColor: '#ffffff',
    grid: { top: 40, right: 20, bottom: 30, left: 50 },
    tooltip: { trigger: 'axis' },
    legend: {
      data: ['OEE', '时间稼动率', '性能稼动率', '良品率'],
      bottom: 0,
      textStyle: { color: '#666' }
    },
    xAxis: {
      type: 'category',
      data: dates,
      axisLine: { lineStyle: { color: '#ddd' } },
      axisTick: { show: false },
      axisLabel: { color: '#666' }
    },
    yAxis: {
      type: 'value',
      min: 70,
      max: 100,
      axisLine: { show: false },
      splitLine: { lineStyle: { color: '#eee' } },
      axisLabel: { color: '#666' }
    },
    series: [
      {
        name: 'OEE',
        type: 'line',
        smooth: true,
        data: oeeValues,
        lineStyle: { color: '#4a90d9', width: 3 },
        itemStyle: { color: '#4a90d9' },
        symbol: 'circle',
        symbolSize: 8
      },
      {
        name: '时间稼动率',
        type: 'line',
        smooth: true,
        data: avalValues,
        lineStyle: { color: '#52c41a', width: 2 },
        itemStyle: { color: '#52c41a' }
      },
      {
        name: '性能稼动率',
        type: 'line',
        smooth: true,
        data: perfValues,
        lineStyle: { color: '#5cd9e8', width: 2 },
        itemStyle: { color: '#5cd9e8' }
      },
      {
        name: '良品率',
        type: 'line',
        smooth: true,
        data: qualValues,
        lineStyle: { color: '#ff9800', width: 2 },
        itemStyle: { color: '#ff9800' }
      }
    ]
  })
}

const updateLossChart = () => {
  if (!lossChart) return

  lossChart.setOption({
    backgroundColor: '#ffffff',
    tooltip: { trigger: 'item', formatter: '{b}: {c}分钟 ({d}%)' },
    legend: { bottom: 0, textStyle: { color: '#666' } },
    series: [{
      type: 'pie',
      radius: ['40%', '70%'],
      center: ['50%', '45%'],
      data: lossList.value.map((item, index) => ({
        value: item.lossTimeMin || 0,
        name: item.lossCategoryName || '损失' + (index + 1),
        itemStyle: {
          color: ['#4a90d9', '#5cd9e8', '#52c41a', '#ff9800', '#ff5722', '#9c27b0', '#673ab7'][index]
        }
      })),
      label: { show: false }
    }]
  })
}

const updateStatusChart = () => {
  if (!statusChart) return

  statusChart.setOption({
    backgroundColor: '#ffffff',
    tooltip: { trigger: 'item' },
    legend: { bottom: 0, textStyle: { color: '#666' } },
    series: [{
      type: 'pie',
      radius: ['40%', '70%'],
      center: ['50%', '45%'],
      data: [
        { value: 65, name: '运行中', itemStyle: { color: '#52c41a' } },
        { value: 15, name: '待机', itemStyle: { color: '#ff9800' } },
        { value: 12, name: '故障', itemStyle: { color: '#f56c6c' } },
        { value: 8, name: '维护', itemStyle: { color: '#5cd9e8' } }
      ],
      label: { show: false }
    }]
  })
}

const handleResize = () => {
  nextTick(() => {
    trendChart?.resize()
    lossChart?.resize()
    statusChart?.resize()
  })
}

onMounted(() => {
  updateTime()
  timeInterval = setInterval(updateTime, 1000)

  nextTick(() => {
    if (trendChartRef.value) {
      trendChart = echarts.init(trendChartRef.value)
    }
    if (lossChartRef.value) {
      lossChart = echarts.init(lossChartRef.value)
    }
    if (statusChartRef.value) {
      statusChart = echarts.init(statusChartRef.value)
    }
    loadData()

    window.addEventListener('resize', handleResize)

    if (window.ResizeObserver) {
      resizeObserver = new ResizeObserver(() => {
        handleResize()
      })
      const container = document.querySelector('.screen-wrapper')
      if (container) {
        resizeObserver.observe(container)
      }
    }

    dataInterval = setInterval(loadData, 30000)
  })
})

onBeforeUnmount(() => {
  if (timeInterval) {
    clearInterval(timeInterval)
    timeInterval = null
  }
  if (dataInterval) {
    clearInterval(dataInterval)
    dataInterval = null
  }
  window.removeEventListener('resize', handleResize)
  if (resizeObserver) {
    resizeObserver.disconnect()
    resizeObserver = null
  }
  if (trendChart) {
    trendChart.dispose()
    trendChart = null
  }
  if (lossChart) {
    lossChart.dispose()
    lossChart = null
  }
  if (statusChart) {
    statusChart.dispose()
    statusChart = null
  }
})

onUnmounted(() => {
  // 确保清理完成
})
</script>

<style lang="scss" scoped>
.screen-wrapper {
  width: 100%;
  min-height: 100%;
  background: #f5f5f5;
  overflow-y: auto;
  overflow-x: hidden;
}

.screen-content {
  background: #ffffff;
  color: #333333;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  width: 100%;
  padding-bottom: 20px;
}

.screen-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 30px;
  border-bottom: 1px solid #eee;

  .title {
    font-size: 24px;
    font-weight: bold;
    color: #333333;
    letter-spacing: 2px;
    margin: 0;
  }

  .header-right {
    display: flex;
    gap: 20px;
    align-items: center;

    .current-shift {
      font-size: 14px;
      color: #4a90d9;
      font-weight: 600;
    }

    .time {
      font-size: 16px;
      color: #666666;
      font-family: 'Courier New', monospace;
    }
  }
}

.screen-body {
  padding: 15px;
}

.kpi-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 16px;
  margin-bottom: 16px;

  .kpi-card {
    background: #fafafa;
    border: 1px solid #e0e0e0;
    border-radius: 8px;
    padding: 20px;
    text-align: center;

    .kpi-title {
      font-size: 14px;
      color: #666666;
      margin-bottom: 10px;
    }

    .kpi-value {
      font-size: 32px;
      font-weight: bold;
      margin-bottom: 8px;

      &.oee { color: #4a90d9; }
      &.availability { color: #52c41a; }
      &.performance { color: #5cd9e8; }
      &.quality { color: #ff9800; }
    }

    .kpi-trend {
      font-size: 12px;
      padding: 2px 8px;
      border-radius: 10px;
      display: inline-block;

      &.positive {
        background: #f0f9eb;
        color: #52c41a;
      }

      &.negative {
        background: #fef0f0;
        color: #f56c6c;
      }

      &.zero {
        background: #fafafa;
        color: #999999;
      }
    }
  }
}

.chart-row {
  display: flex;
  gap: 16px;
  margin-bottom: 16px;

  .chart-box {
    background: #fafafa;
    border: 1px solid #e0e0e0;
    border-radius: 8px;
    padding: 15px;
    display: flex;
    flex-direction: column;

    &.flex-1 {
      flex: 1;
    }

    &.flex-2 {
      flex: 2;
    }

    .box-title {
      font-size: 14px;
      font-weight: 600;
      color: #333333;
      margin-bottom: 12px;
      padding-left: 10px;
      border-left: 3px solid #4a90d9;
    }

    .chart {
      height: 300px;
      width: 100%;
    }

    .event-table {
      flex: 1;
    }
  }
}

@media screen and (max-width: 1200px) {
  .kpi-grid {
    grid-template-columns: repeat(2, 1fr);
  }

  .chart-row {
    flex-direction: column;
  }
}

@media screen and (max-width: 768px) {
  .kpi-grid {
    grid-template-columns: 1fr;
  }
}
</style>