<template>
  <div>
    <div class="sec-title">产能分析</div>

    <!-- ─── KPI摘要 ─── -->
    <div class="grid-5">
      <div class="metric-box">
        <div class="mb-label">年产量目标</div>
        <div class="mb-value">70</div>
        <div class="mb-unit">万吨</div>
      </div>
      <div class="metric-box">
        <div class="mb-label">本年实际完成</div>
        <div class="mb-value" style="color:#28a745;">{{ kpi.actual_yt }}</div>
        <div class="mb-unit">万吨</div>
      </div>
      <div class="metric-box">
        <div class="mb-label">完成率</div>
        <div class="mb-value" :style="{ color: kpi.completion_rate >= 85 ? '#28a745' : '#f0a500' }">
          {{ kpi.completion_rate }}
        </div>
        <div class="mb-unit">%</div>
      </div>
      <div class="metric-box">
        <div class="mb-label">日均产量</div>
        <div class="mb-value">{{ kpi.daily_avg }}</div>
        <div class="mb-unit">吨/天</div>
      </div>
      <div class="metric-box">
        <div class="mb-label">OEE</div>
        <div class="mb-value" :style="{ color: kpi.oee >= 85 ? '#28a745' : '#f0a500' }">
          {{ kpi.oee }}
        </div>
        <div class="mb-unit">%</div>
      </div>
    </div>

    <!-- ─── 图表区 ─── -->
    <div class="section-row">
      <!-- 月产量柱状图 -->
      <div class="card" style="flex:3;">
        <div class="card-header">月度产量趋势（万吨）</div>
        <div class="card-body">
          <canvas ref="monthChart" height="180"></canvas>
        </div>
      </div>
      <!-- 速度分布直方图 -->
      <div class="card" style="flex:2;">
        <div class="card-header">运行速度分布 (m/min)</div>
        <div class="card-body">
          <canvas ref="speedChart" height="180"></canvas>
        </div>
      </div>
    </div>

    <!-- ─── 消耗预测面板 + 班次对比 ─── -->
    <div class="section-row">
      <!-- 消耗预测 -->
      <div class="card" style="flex:1;">
        <div class="card-header">消耗量预测</div>
        <div class="card-body">
          <div class="flex-col" style="margin-bottom:12px;">
            <div class="form-field">
              <div class="kv-label">计划产量 (t)</div>
              <input v-model.number="cons.planned_weight" type="number" class="kv-input" step="100" min="100" />
            </div>
            <div class="form-field">
              <div class="kv-label">再生装置</div>
              <select v-model="cons.has_regen" class="kv-input">
                <option :value="true">有再生装置</option>
                <option :value="false">无再生装置</option>
              </select>
            </div>
            <button class="btn btn-primary fw" :disabled="consLoading" @click="doCons">
              {{ consLoading ? '计算中...' : '预测消耗' }}
            </button>
          </div>

          <div v-if="consResult">
            <div class="sec-title">预测结果</div>
            <div class="kv-grid">
              <span class="kv-label">盐酸消耗</span>
              <span class="kv-value">{{ consResult.acid_consumption_kg }} <span class="kv-unit">kg ({{ consResult.acid_unit_kg_per_t }} kg/t)</span></span>
              <span class="kv-label">蒸汽消耗</span>
              <span class="kv-value">{{ consResult.steam_consumption_kg }} <span class="kv-unit">kg ({{ consResult.steam_unit_kg_per_t }} kg/t)</span></span>
              <span class="kv-label">电力消耗</span>
              <span class="kv-value">{{ consResult.power_consumption_kwh }} <span class="kv-unit">kWh ({{ consResult.power_unit_kwh_per_t }} kWh/t)</span></span>
              <span class="kv-label">冷却水</span>
              <span class="kv-value">{{ consResult.cooling_water_m3 }} <span class="kv-unit">m³ ({{ consResult.cooling_water_unit_m3_per_t }} m³/t)</span></span>
              <span class="kv-label">计划产量</span>
              <span class="kv-value">{{ consResult.coil_weight_t }} <span class="kv-unit">t</span></span>
            </div>

            <!-- 单耗对比条 -->
            <div class="mt8 sec-title">单耗指标对比</div>
            <div class="unit-bar-row" v-for="item in unitItems" :key="item.label">
              <span class="unit-bar-label">{{ item.label }}</span>
              <div class="prog-bar-wrap" style="flex:1;margin:0 8px;">
                <div class="prog-bar-fill" :style="{ width: item.pct + '%', background: item.color }"></div>
              </div>
              <span class="unit-bar-val">{{ item.val }} {{ item.unit }}</span>
            </div>
          </div>
        </div>
      </div>

      <!-- 班次对比表 -->
      <div class="card" style="flex:2;">
        <div class="card-header">班次产能对比</div>
        <div class="table-scroll">
          <table class="data-table">
            <thead>
              <tr>
                <th>班次</th>
                <th>日期</th>
                <th>产量(t)</th>
                <th>平均速度</th>
                <th>卷数</th>
                <th>停机时长(h)</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="row in shiftData" :key="row.id">
                <td>
                  <span :class="['badge', shiftBadge(row.shift)]">{{ row.shift }}</span>
                </td>
                <td class="td-muted">{{ row.date }}</td>
                <td class="td-num" style="color:#00c8ff;">{{ row.production }}</td>
                <td class="td-num">{{ row.avg_speed }} m/min</td>
                <td class="td-num">{{ row.coil_count }}</td>
                <td :class="row.stop_h > 1.5 ? 'td-warn' : 'td-num'">{{ row.stop_h }}</td>
              </tr>
              <tr v-if="!shiftData.length">
                <td colspan="6" class="td-muted" style="text-align:center;padding:20px;">暂无班次数据</td>
              </tr>
            </tbody>
          </table>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { predictConsumption, getProductionRecords, getDowntimeRecords } from '@/api'

const MONTHS = ['1月','2月','3月','4月','5月','6月','7月','8月','9月','10月','11月','12月']
const SPEED_BINS = ['20-40','40-60','60-80','80-100','100-120','120-140','140-160','160-180']
const SPEED_BIN_COLORS = ['#30363d','#1f6feb','#0078d4','#28a745','#28a745','#00c8ff','#f0a500','#da3633']

export default {
  name: 'Capacity',
  data() {
    return {
      kpi: {
        actual_yt: '—',
        completion_rate: '—',
        daily_avg: '—',
        oee: '—',
      },
      cons: { planned_weight: 1000, has_regen: true },
      consLoading: false,
      consResult: null,
      shiftData: [],
      monthData: Array(12).fill(0),
      speedFreq: Array(8).fill(0),
    }
  },
  computed: {
    unitItems() {
      if (!this.consResult) return []
      return [
        { label: '酸耗', val: this.consResult.acid_unit_kg_per_t, unit: 'kg/t', pct: Math.min(this.consResult.acid_unit_kg_per_t / 5 * 100, 100), color: '#0078d4' },
        { label: '蒸汽', val: this.consResult.steam_unit_kg_per_t, unit: 'kg/t', pct: Math.min(this.consResult.steam_unit_kg_per_t / 60 * 100, 100), color: '#00c8ff' },
        { label: '电力', val: this.consResult.power_unit_kwh_per_t, unit: 'kWh/t', pct: Math.min(this.consResult.power_unit_kwh_per_t / 20 * 100, 100), color: '#f0a500' },
        { label: '冷却水', val: this.consResult.cooling_water_unit_m3_per_t, unit: 'm³/t', pct: Math.min(this.consResult.cooling_water_unit_m3_per_t / 2 * 100, 100), color: '#28a745' },
      ]
    }
  },
  async mounted() {
    await this.fetchData()
  },
  methods: {
    async fetchData() {
      try {
        const [prodRes, dtRes] = await Promise.all([
          getProductionRecords({ page_size: 500 }),
          getDowntimeRecords({ page_size: 500 }),
        ])
        const prods = prodRes.data?.items || []
        const dts = dtRes.data?.items || []

        // ── KPI ──
        const totalWeightT = prods.reduce((s, p) => s + (p.coil_weight_t || 0), 0)
        const actualYt = (totalWeightT / 10000).toFixed(2)
        const TARGET_YT = 70
        const completionRate = totalWeightT > 0 ? ((totalWeightT / 10000) / TARGET_YT * 100).toFixed(1) : '—'

        // Daily average: group by date
        const dayMap = {}
        prods.forEach(p => {
          const d = (p.start_time || '').slice(0, 10)
          if (!d) return
          if (!dayMap[d]) dayMap[d] = 0
          dayMap[d] += (p.coil_weight_t || 0)
        })
        const days = Object.values(dayMap)
        const dailyAvg = days.length ? (days.reduce((a, b) => a + b, 0) / days.length).toFixed(0) : '—'

        // OEE: runtime / (runtime + downtime) × 100 — simplified as production hours / shift hours
        const totalDtMin = dts.reduce((s, d) => s + (d.duration_min || 0), 0)
        const SHIFT_H = 8
        const shifts = new Set(prods.map(p => (p.start_time || '').slice(0, 13))).size || 1
        const totalShiftMin = shifts * SHIFT_H * 60
        const oee = totalShiftMin > 0 ? Math.min(((totalShiftMin - totalDtMin) / totalShiftMin * 100).toFixed(1), 100) : '—'

        this.kpi = {
          actual_yt: actualYt,
          completion_rate: completionRate,
          daily_avg: dailyAvg,
          oee,
        }

        // ── 月度产量 ──
        const monthMap = Array(12).fill(0)
        prods.forEach(p => {
          if (p.start_time) {
            const m = new Date(p.start_time).getMonth()
            monthMap[m] += (p.coil_weight_t || 0)
          }
        })
        this.monthData = monthMap.map(v => +(v / 10000).toFixed(2))

        // ── 速度分布 ──
        const speedBins = [0, 0, 0, 0, 0, 0, 0, 0]
        const edges = [20, 40, 60, 80, 100, 120, 140, 160, 180]
        prods.forEach(p => {
          const v = p.avg_speed
          if (!v) return
          for (let i = 0; i < edges.length - 1; i++) {
            if (v >= edges[i] && v < edges[i + 1]) { speedBins[i]++; break }
          }
        })
        this.speedFreq = speedBins

        // ── 班次对比 ──
        const shiftKey = p => `${(p.start_time || '').slice(0, 10)}_${p.shift || '—'}`
        const sMap = {}
        prods.forEach(p => {
          const k = shiftKey(p)
          if (!sMap[k]) sMap[k] = { shift: p.shift || '—', date: (p.start_time || '').slice(0, 10), weight: 0, speeds: [], count: 0 }
          sMap[k].weight += (p.coil_weight_t || 0)
          sMap[k].count++
          if (p.avg_speed) sMap[k].speeds.push(p.avg_speed)
        })

        // Attach downtime per shift-date
        const dtDayMap = {}
        dts.forEach(d => {
          const day = (d.start_time || '').slice(0, 10)
          if (!day) return
          dtDayMap[day] = (dtDayMap[day] || 0) + (d.duration_min || 0)
        })

        this.shiftData = Object.values(sMap)
          .sort((a, b) => b.date.localeCompare(a.date))
          .slice(0, 12)
          .map((s, i) => ({
            id: i,
            shift: s.shift,
            date: s.date,
            production: s.weight.toFixed(1),
            avg_speed: s.speeds.length ? (s.speeds.reduce((a, b) => a + b, 0) / s.speeds.length).toFixed(1) : '—',
            coil_count: s.count,
            stop_h: s.date && dtDayMap[s.date] ? (dtDayMap[s.date] / 60 / 3).toFixed(1) : '0.0',
          }))
      } catch (e) {
        // leave defaults
      }
      this.$nextTick(() => {
        this.drawMonthChart()
        this.drawSpeedChart()
      })
    },
    shiftBadge(s) {
      const m = { '甲班': 'badge-blue', '乙班': 'badge-green', '丙班': 'badge-yellow', '丁班': 'badge-gray' }
      return m[s] || 'badge-gray'
    },
    async doCons() {
      this.consLoading = true
      try {
        const res = await predictConsumption({
          thickness: 3.0,
          width: 1000,
          coil_weight_kg: this.cons.planned_weight * 1000,
          has_regen_station: this.cons.has_regen,
        })
        this.consResult = res.data
      } catch (e) {
        this.$message.error('预测失败：' + (e.response?.data?.detail || e.message))
      } finally {
        this.consLoading = false
      }
    },
    drawMonthChart() {
      const canvas = this.$refs.monthChart
      if (!canvas) return
      const W = canvas.offsetWidth || 500
      const H = 180
      canvas.width = W
      canvas.height = H
      const ctx = canvas.getContext('2d')
      ctx.clearRect(0, 0, W, H)
      const data = this.monthData
      const maxVal = Math.max(...data, 1)
      const barW = Math.floor((W - 40) / 12) - 4
      const xOff = 20
      const barArea = H - 40

      data.forEach((v, i) => {
        const x = xOff + i * (barW + 4)
        const bh = Math.floor(v / maxVal * barArea)
        const y = H - 24 - bh
        ctx.fillStyle = v > 0 ? '#0078d4' : '#30363d'
        ctx.globalAlpha = 0.85
        ctx.fillRect(x, y, barW, bh)
        ctx.globalAlpha = 1
        if (v > 0) {
          ctx.fillStyle = '#e6edf3'
          ctx.font = '10px Consolas'
          ctx.textAlign = 'center'
          ctx.fillText(v, x + barW / 2, y - 4)
        }
        ctx.fillStyle = '#8b949e'
        ctx.font = '10px "Microsoft YaHei"'
        ctx.fillText(MONTHS[i], x + barW / 2, H - 6)
      })

      const TARGET_PER_MONTH = 5.83
      const targetY = H - 24 - Math.floor(TARGET_PER_MONTH / maxVal * barArea)
      ctx.strokeStyle = '#f0a500'
      ctx.lineWidth = 1.5
      ctx.setLineDash([4, 4])
      ctx.beginPath()
      ctx.moveTo(xOff, targetY)
      ctx.lineTo(W - xOff, targetY)
      ctx.stroke()
      ctx.setLineDash([])
      ctx.fillStyle = '#f0a500'
      ctx.font = '10px Consolas'
      ctx.textAlign = 'left'
      ctx.fillText('目标 5.83', W - 58, targetY - 4)
    },
    drawSpeedChart() {
      const canvas = this.$refs.speedChart
      if (!canvas) return
      const W = canvas.offsetWidth || 320
      const H = 180
      canvas.width = W
      canvas.height = H
      const ctx = canvas.getContext('2d')
      ctx.clearRect(0, 0, W, H)
      const data = this.speedFreq
      const maxVal = Math.max(...data, 1)
      const barW = Math.floor((W - 20) / data.length) - 2
      const xOff = 10

      data.forEach((v, i) => {
        const x = xOff + i * (barW + 2)
        const bh = Math.floor(v / maxVal * (H - 40))
        const y = H - 24 - bh
        ctx.fillStyle = SPEED_BIN_COLORS[i]
        ctx.globalAlpha = 0.85
        ctx.fillRect(x, y, barW, bh)
        ctx.globalAlpha = 1
        ctx.fillStyle = '#8b949e'
        ctx.font = '9px Consolas'
        ctx.textAlign = 'center'
        ctx.fillText(SPEED_BINS[i], x + barW / 2, H - 6)
        if (v > 0) {
          ctx.fillStyle = '#e6edf3'
          ctx.font = '9px Consolas'
          ctx.fillText(v, x + barW / 2, y - 3)
        }
      })
    },
  }
}
</script>

<style lang="scss" scoped>
@import '@/assets/styles/variables';
.form-field { display: flex; flex-direction: column; gap: 5px; }
.mt8 { margin-top: 8px; }
.unit-bar-row {
  display: flex;
  align-items: center;
  margin-top: 6px;
  gap: 4px;
}
.unit-bar-label {
  font-size: 11px;
  color: $text-secondary;
  width: 44px;
  flex-shrink: 0;
}
.unit-bar-val {
  font-size: 11px;
  color: $sms-highlight;
  font-family: $font-mono;
  white-space: nowrap;
}
</style>
