<template>
  <div>
    <!-- ─── 过滤栏 ─── -->
    <div class="card">
      <div class="card-body" style="padding:10px 14px;">
        <div class="flex-row" style="flex-wrap:wrap;gap:12px;">
          <div class="flex-row">
            <span class="kv-label">卷号</span>
            <input v-model="query.coil_no" class="kv-input" style="width:140px;" @keyup.enter="fetchData" />
          </div>
          <div class="flex-row">
            <span class="kv-label">质量等级</span>
            <select v-model="query.overall_grade" class="kv-input" style="width:100px;">
              <option value="">全部</option>
              <option v-for="g in ['A1','A2','B1','B2','C']" :key="g" :value="g">{{ g }}</option>
            </select>
          </div>
          <div class="flex-row">
            <span class="kv-label">日期</span>
            <input v-model="query.start_date" type="date" class="kv-input" style="width:140px;" />
            <span class="kv-label">~</span>
            <input v-model="query.end_date" type="date" class="kv-input" style="width:140px;" />
          </div>
          <div class="flex-row">
            <button class="btn btn-primary" @click="fetchData">查询</button>
            <button class="btn btn-outline" @click="openDialog()">＋ 新增检验</button>
          </div>
        </div>
      </div>
    </div>

    <!-- ─── 统计卡片 ─── -->
    <div class="grid-4">
      <div class="metric-box">
        <div class="mb-label">合格率</div>
        <div class="mb-value" :style="{ color: summary.pass_rate >= 95 ? '#28a745' : '#f0a500' }">
          {{ summary.pass_rate }}
        </div>
        <div class="mb-unit">%</div>
      </div>
      <div class="metric-box">
        <div class="mb-label">平均PI评分</div>
        <div class="mb-value">{{ summary.avg_pi_score }}</div>
        <div class="mb-unit">/ 100</div>
      </div>
      <div class="metric-box">
        <div class="mb-label">平均表面评分</div>
        <div class="mb-value">{{ summary.avg_surface_score }}</div>
        <div class="mb-unit">/ 100</div>
      </div>
      <div class="metric-box">
        <div class="mb-label">记录总数</div>
        <div class="mb-value">{{ summary.total }}</div>
        <div class="mb-unit">条</div>
      </div>
    </div>

    <!-- ─── 主体区域 ─── -->
    <div class="section-row">
      <!-- 质量记录表 -->
      <div class="card" style="flex:2;">
        <div class="card-header">
          质量检验记录
          <span class="ch-badge">共 {{ total }} 条</span>
        </div>
        <div class="table-scroll" v-loading="loading">
          <table class="data-table">
            <thead>
              <tr>
                <th>卷号</th>
                <th>实测厚度</th>
                <th>实测宽度</th>
                <th>PI评分</th>
                <th>表面评分</th>
                <th>质量等级</th>
                <th>残酸(g/m²)</th>
                <th>粗糙度Ra</th>
                <th>是否合格</th>
                <th>检验员</th>
                <th>检验时间</th>
                <th>操作</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="row in tableData" :key="row.id">
                <td class="td-num">{{ row.coil_no }}</td>
                <td class="td-num">{{ row.thickness_actual || '—' }}</td>
                <td class="td-num">{{ row.width_actual || '—' }}</td>
                <td class="td-num">{{ row.pi_score != null ? row.pi_score.toFixed(1) : '—' }}</td>
                <td class="td-num">{{ row.surface_score != null ? row.surface_score.toFixed(1) : '—' }}</td>
                <td>
                  <span v-if="row.overall_grade" :class="['badge', gradeBadge(row.overall_grade)]">
                    {{ row.overall_grade }}
                  </span>
                  <span v-else class="td-muted">—</span>
                </td>
                <td class="td-num">{{ row.acid_residual || '—' }}</td>
                <td class="td-num">{{ row.roughness_ra || '—' }}</td>
                <td>
                  <span :class="['badge', row.is_passed ? 'badge-green' : 'badge-red']">
                    {{ row.is_passed ? '合格' : '不合格' }}
                  </span>
                </td>
                <td class="td-muted">{{ row.inspector || '—' }}</td>
                <td class="td-muted">{{ fmtTime(row.inspect_time) }}</td>
                <td><span class="action-link" @click="openDialog(row)">编辑</span></td>
              </tr>
              <tr v-if="!tableData.length && !loading">
                <td colspan="12" class="td-muted" style="text-align:center;padding:24px;">暂无数据</td>
              </tr>
            </tbody>
          </table>
        </div>
        <div class="card-body" style="padding:8px 14px;" v-if="total > query.page_size">
          <div class="flex-row">
            <button class="btn btn-outline" :disabled="query.page<=1" @click="query.page--;fetchData()">上一页</button>
            <span class="kv-label">第 {{ query.page }} / {{ Math.ceil(total/query.page_size) }} 页</span>
            <button class="btn btn-outline" :disabled="query.page>=Math.ceil(total/query.page_size)" @click="query.page++;fetchData()">下一页</button>
          </div>
        </div>
      </div>

      <!-- 右侧面板 -->
      <div style="flex:1;display:flex;flex-direction:column;gap:14px;min-width:0;">
        <!-- 快速预测面板 -->
        <div class="card">
          <div class="card-header">快速质量预测</div>
          <div class="card-body">
            <div class="flex-col">
              <div class="form-field">
                <div class="kv-label">厚度 (mm)</div>
                <input v-model.number="pred.thickness" type="number" class="kv-input" step="0.1" />
              </div>
              <div class="form-field">
                <div class="kv-label">平均速度 (m/min)</div>
                <input v-model.number="pred.avg_speed" type="number" class="kv-input" />
              </div>
              <div class="form-field">
                <div class="kv-label">平均HCl浓度 (g/L)</div>
                <input v-model.number="pred.acid_conc_avg" type="number" class="kv-input" />
              </div>
              <div class="form-field">
                <div class="kv-label">平均温度 (°C)</div>
                <input v-model.number="pred.acid_temp_avg" type="number" class="kv-input" />
              </div>
              <div class="form-field">
                <div class="kv-label">铁皮重量 (g/m²)</div>
                <input v-model.number="pred.scale_weight" type="number" class="kv-input" step="0.5" />
              </div>
              <button class="btn btn-primary fw" :disabled="predLoading" @click="doPred">
                {{ predLoading ? '预测中...' : '质量预测' }}
              </button>
            </div>

            <!-- 预测结果 -->
            <div v-if="predResult" class="mt8">
              <div class="kv-grid" style="margin-bottom:10px;">
                <span class="kv-label">PI评分</span>
                <span class="kv-value">{{ predResult.pi_score }}</span>
                <span class="kv-label">表面评分</span>
                <span class="kv-value">{{ predResult.surface_score }}</span>
                <span class="kv-label">综合等级</span>
                <span>
                  <span :class="['badge', gradeBadge(predResult.overall_grade)]" style="font-size:14px;padding:2px 12px;">
                    {{ predResult.overall_grade }}
                  </span>
                </span>
              </div>
              <div class="sec-title">工艺建议</div>
              <div v-for="(r, i) in predResult.recommendations" :key="i" class="rec-item">
                💡 {{ r }}
              </div>
            </div>
          </div>
        </div>

        <!-- 等级分布图 -->
        <div class="card">
          <div class="card-header">等级分布</div>
          <div class="card-body">
            <canvas ref="gradeChart" height="140"></canvas>
          </div>
        </div>
      </div>
    </div>

    <!-- ─── 新增/编辑弹窗 ─── -->
    <div v-if="dialogVisible" class="modal-mask" @click.self="dialogVisible=false">
      <div class="modal-box" style="width:680px;">
        <div class="modal-header">
          {{ editRow ? '编辑质量记录 #' + editRow.id : '新增质量记录' }}
          <span class="modal-close" @click="dialogVisible=false">✕</span>
        </div>
        <div class="modal-body">
          <div class="grid-3" style="gap:12px;margin-bottom:14px;">
            <div class="form-field">
              <div class="kv-label">卷号 *</div>
              <input v-model="form.coil_no" class="kv-input" />
            </div>
            <div class="form-field">
              <div class="kv-label">实测厚度 (mm)</div>
              <input v-model.number="form.thickness_actual" type="number" class="kv-input" step="0.01" />
            </div>
            <div class="form-field">
              <div class="kv-label">实测宽度 (mm)</div>
              <input v-model.number="form.width_actual" type="number" class="kv-input" />
            </div>
            <div class="form-field">
              <div class="kv-label">平直度 (IU)</div>
              <input v-model.number="form.flatness" type="number" class="kv-input" step="0.1" />
            </div>
            <div class="form-field">
              <div class="kv-label">凸度 (μm)</div>
              <input v-model.number="form.crown" type="number" class="kv-input" />
            </div>
            <div class="form-field">
              <div class="kv-label">表面缺陷类型</div>
              <select v-model="form.surface_defect_type" class="kv-input">
                <option value="">无缺陷</option>
                <option value="划伤">划伤</option>
                <option value="压印">压印</option>
                <option value="氧化色">氧化色</option>
                <option value="过酸洗">过酸洗</option>
                <option value="欠酸洗">欠酸洗</option>
                <option value="锈迹">锈迹</option>
              </select>
            </div>
            <div class="form-field">
              <div class="kv-label">缺陷长度 (m)</div>
              <input v-model.number="form.defect_length_m" type="number" class="kv-input" step="0.1" />
            </div>
            <div class="form-field">
              <div class="kv-label">缺陷位置</div>
              <input v-model="form.defect_position" class="kv-input" />
            </div>
            <div class="form-field">
              <div class="kv-label">PI评分</div>
              <input v-model.number="form.pi_score" type="number" class="kv-input" step="0.1" min="0" max="100" />
            </div>
            <div class="form-field">
              <div class="kv-label">表面评分</div>
              <input v-model.number="form.surface_score" type="number" class="kv-input" step="0.1" min="0" max="100" />
            </div>
            <div class="form-field">
              <div class="kv-label">综合等级</div>
              <select v-model="form.overall_grade" class="kv-input">
                <option v-for="g in ['A1','A2','B1','B2','C']" :key="g" :value="g">{{ g }}</option>
              </select>
            </div>
            <div class="form-field">
              <div class="kv-label">残酸量 (g/m²)</div>
              <input v-model.number="form.acid_residual" type="number" class="kv-input" step="0.01" />
            </div>
            <div class="form-field">
              <div class="kv-label">粗糙度 Ra (μm)</div>
              <input v-model.number="form.roughness_ra" type="number" class="kv-input" step="0.01" />
            </div>
            <div class="form-field">
              <div class="kv-label">检验员</div>
              <input v-model="form.inspector" class="kv-input" />
            </div>
            <div class="form-field">
              <div class="kv-label">是否合格</div>
              <select v-model="form.is_passed" class="kv-input">
                <option :value="true">合格</option>
                <option :value="false">不合格</option>
              </select>
            </div>
          </div>
        </div>
        <div class="modal-footer">
          <button class="btn btn-outline" @click="dialogVisible=false">取消</button>
          <button class="btn btn-primary" :disabled="saving" @click="save">
            {{ saving ? '保存中...' : '保存' }}
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { getQualityList, createQuality, getQualitySummary, predictQuality } from '@/api'

export default {
  name: 'Quality',
  data() {
    return {
      loading: false, saving: false, predLoading: false,
      tableData: [], total: 0,
      summary: { pass_rate: 0, avg_pi_score: 0, avg_surface_score: 0, total: 0, grade_distribution: {} },
      query: { page: 1, page_size: 20, coil_no: '', overall_grade: '', start_date: '', end_date: '' },
      dialogVisible: false, editRow: null, form: {},
      pred: { thickness: 3.0, avg_speed: 100, acid_conc_avg: 160, acid_temp_avg: 75, scale_weight: 8.5 },
      predResult: null,
    }
  },
  created() {
    this.fetchData()
    this.fetchSummary()
  },
  methods: {
    async fetchData() {
      this.loading = true
      const params = { ...this.query }
      if (!params.coil_no) delete params.coil_no
      if (!params.overall_grade) delete params.overall_grade
      if (params.start_date) params.start_date = params.start_date + 'T00:00:00'
      else delete params.start_date
      if (params.end_date) params.end_date = params.end_date + 'T23:59:59'
      else delete params.end_date
      try {
        const res = await getQualityList(params)
        this.tableData = res.data.items
        this.total = res.data.total
      } finally { this.loading = false }
    },
    async fetchSummary() {
      try {
        const res = await getQualitySummary()
        this.summary = res.data
        this.$nextTick(() => this.drawChart())
      } catch (e) { /* ignore */ }
    },
    drawChart() {
      const canvas = this.$refs.gradeChart
      if (!canvas) return
      const ctx = canvas.getContext('2d')
      const grades = ['A1','A2','B1','B2','C']
      const dist = this.summary.grade_distribution || {}
      const counts = grades.map(g => dist[g] || 0)
      const maxCount = Math.max(...counts, 1)
      const colors = ['#28a745','#00c8ff','#0078d4','#f0a500','#da3633']
      const W = canvas.offsetWidth || 300
      const H = 140
      canvas.width = W
      canvas.height = H
      ctx.clearRect(0, 0, W, H)
      const barW = Math.floor(W / grades.length) - 8
      const pad = 4
      grades.forEach((g, i) => {
        const barH = Math.floor((counts[i] / maxCount) * (H - 36))
        const x = i * (barW + 8) + pad
        const y = H - barH - 20
        ctx.fillStyle = colors[i]
        ctx.globalAlpha = 0.85
        ctx.fillRect(x, y, barW, barH)
        ctx.globalAlpha = 1
        ctx.fillStyle = '#e6edf3'
        ctx.font = '11px Consolas'
        ctx.textAlign = 'center'
        ctx.fillText(counts[i], x + barW / 2, y - 4)
        ctx.fillStyle = '#8b949e'
        ctx.font = '11px "Microsoft YaHei"'
        ctx.fillText(g, x + barW / 2, H - 4)
      })
    },
    fmtTime(t) { return t ? t.replace('T', ' ').slice(0, 16) : '—' },
    gradeBadge(g) {
      if (g === 'A1') return 'badge-green'
      if (g === 'A2') return 'badge-blue'
      if (g === 'B1') return 'badge-blue'
      if (g === 'B2') return 'badge-yellow'
      return 'badge-red'
    },
    openDialog(row = null) {
      this.editRow = row
      this.form = row ? { ...row } : { is_passed: true }
      this.dialogVisible = true
    },
    async save() {
      if (!this.form.coil_no) { this.$message.error('卷号不能为空'); return }
      this.saving = true
      try {
        if (this.editRow) await createQuality({ ...this.form })  // use PUT when available
        else await createQuality(this.form)
        this.$message.success('保存成功')
        this.dialogVisible = false
        this.fetchData()
        this.fetchSummary()
      } finally { this.saving = false }
    },
    async doPred() {
      this.predLoading = true
      try {
        const res = await predictQuality(this.pred)
        this.predResult = res.data
      } catch (e) {
        this.$message.error('预测失败：' + (e.response?.data?.detail || e.message))
      } finally { this.predLoading = false }
    },
  }
}
</script>

<style lang="scss" scoped>
@import '@/assets/styles/variables';
.action-link { color: $sms-highlight; cursor: pointer; font-size: 12px; margin-right: 10px; &:hover { text-decoration: underline; } }
.form-field { display: flex; flex-direction: column; gap: 5px; }
.rec-item { padding: 5px 8px; margin-top: 4px; background: rgba(0,200,255,.05); border-left: 2px solid $sms-highlight; font-size: 12px; color: $text-secondary; border-radius: 0 3px 3px 0; }
.mt8 { margin-top: 8px; }
.modal-mask { position: fixed; inset: 0; background: rgba(0,0,0,.6); display: flex; align-items: center; justify-content: center; z-index: 9999; }
.modal-box { background: $bg-card; border: 1px solid $border; border-radius: 6px; width: 680px; max-width: 96vw; max-height: 92vh; display: flex; flex-direction: column; }
.modal-header { display: flex; align-items: center; justify-content: space-between; padding: 12px 16px; background: $bg-panel; border-bottom: 1px solid $border; font-size: 13px; font-weight: 600; color: $sms-highlight; .modal-close { cursor: pointer; color: $text-muted; &:hover { color: $text-primary; } } }
.modal-body { padding: 16px; overflow-y: auto; }
.modal-footer { padding: 10px 16px; background: $bg-panel; border-top: 1px solid $border; display: flex; justify-content: flex-end; gap: 10px; }
</style>
