<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">L3状态</span>
            <select v-model="query.l3_status" class="kv-input" style="width:110px;">
              <option value="">全部</option>
              <option value="pending">待下发</option>
              <option value="sent">已发送</option>
              <option value="confirmed">已确认</option>
              <option value="cancelled">已取消</option>
            </select>
          </div>
          <div class="flex-row">
            <span class="kv-label">L2状态</span>
            <select v-model="query.l2_status" class="kv-input" style="width:110px;">
              <option value="">全部</option>
              <option value="pending">待处理</option>
              <option value="processing">处理中</option>
              <option value="done">已完成</option>
            </select>
          </div>
          <div class="flex-row">
            <button class="btn btn-primary" @click="fetchData">查询</button>
            <button class="btn btn-outline" @click="openDialog()">＋ 新增PDI</button>
          </div>
        </div>
      </div>
    </div>

    <!-- ─── 统计卡片 ─── -->
    <div class="grid-4">
      <div class="metric-box">
        <div class="mb-label">PDI总数</div>
        <div class="mb-value">{{ stats.total }}</div>
        <div class="mb-unit">条记录</div>
      </div>
      <div class="metric-box">
        <div class="mb-label">待处理</div>
        <div class="mb-value" style="color:#f0a500;">{{ stats.pending }}</div>
        <div class="mb-unit">L2待确认</div>
      </div>
      <div class="metric-box">
        <div class="mb-label">已确认</div>
        <div class="mb-value" style="color:#28a745;">{{ stats.confirmed }}</div>
        <div class="mb-unit">L3已确认</div>
      </div>
      <div class="metric-box">
        <div class="mb-label">处理中</div>
        <div class="mb-value" style="color:#00c8ff;">{{ stats.processing }}</div>
        <div class="mb-unit">酸洗进行中</div>
      </div>
    </div>

    <!-- ─── 数据表 ─── -->
    <div class="card">
      <div class="card-header">
        PDI管理
        <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>钢种</th>
              <th>厚度(mm)</th>
              <th>宽度(mm)</th>
              <th>卷重(kg)</th>
              <th>屈服强度</th>
              <th>工艺路径</th>
              <th>优先级</th>
              <th>L3状态</th>
              <th>L2状态</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-muted">{{ row.order_no || '—' }}</td>
              <td>{{ row.customer || '—' }}</td>
              <td class="td-num">{{ row.steel_grade || '—' }}</td>
              <td class="td-num">{{ row.thickness || '—' }}</td>
              <td class="td-num">{{ row.width || '—' }}</td>
              <td class="td-num">{{ row.coil_weight || '—' }}</td>
              <td class="td-num">{{ row.yield_strength ? row.yield_strength + ' MPa' : '—' }}</td>
              <td class="td-muted" style="font-size:11px;">{{ row.process_route || '—' }}</td>
              <td>
                <span :class="['badge', priorityBadge(row.priority)]">P{{ row.priority || 3 }}</span>
              </td>
              <td>
                <span :class="['badge', l3Badge(row.l3_status)]">{{ l3Text(row.l3_status) }}</span>
              </td>
              <td>
                <span :class="['badge', l2Badge(row.l2_status)]">{{ l2Text(row.l2_status) }}</span>
              </td>
              <td>
                <span class="action-link" @click="openDialog(row)">编辑</span>
                <span
                  v-if="row.l2_status === 'pending'"
                  class="action-link"
                  style="color:#28a745;"
                  @click="confirmPdi(row)"
                >L2确认</span>
                <span class="action-link" style="color:#8b949e;" @click="simulateSend(row)">发送L3</span>
              </td>
            </tr>
            <tr v-if="!tableData.length && !loading">
              <td colspan="13" 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 v-if="dialogVisible" class="modal-mask" @click.self="dialogVisible=false">
      <div class="modal-box" style="width:760px;">
        <div class="modal-header">
          {{ editRow ? '编辑PDI #' + editRow.id : '新增PDI' }}
          <span class="modal-close" @click="dialogVisible=false">✕</span>
        </div>
        <div class="modal-body">
          <div class="sec-title">基本信息</div>
          <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">订单号</div>
              <input v-model="form.order_no" class="kv-input" />
            </div>
            <div class="form-field">
              <div class="kv-label">客户名称</div>
              <input v-model="form.customer" class="kv-input" />
            </div>
            <div class="form-field">
              <div class="kv-label">钢种</div>
              <select v-model="form.steel_grade" class="kv-input">
                <option v-for="g in steelGrades" :key="g" :value="g">{{ g }}</option>
              </select>
            </div>
            <div class="form-field">
              <div class="kv-label">优先级 (1-5)</div>
              <input v-model.number="form.priority" type="number" class="kv-input" min="1" max="5" />
            </div>
            <div class="form-field">
              <div class="kv-label">工艺路径</div>
              <input v-model="form.process_route" class="kv-input" />
            </div>
          </div>

          <div class="sec-title">规格尺寸</div>
          <div class="grid-3" style="gap:12px;margin-bottom:14px;">
            <div class="form-field">
              <div class="kv-label">来料厚度 (mm)</div>
              <input v-model.number="form.thickness" type="number" class="kv-input" step="0.1" />
            </div>
            <div class="form-field">
              <div class="kv-label">来料宽度 (mm)</div>
              <input v-model.number="form.width" type="number" class="kv-input" />
            </div>
            <div class="form-field">
              <div class="kv-label">目标厚度 (mm)</div>
              <input v-model.number="form.target_thickness" type="number" class="kv-input" step="0.1" />
            </div>
            <div class="form-field">
              <div class="kv-label">目标宽度 (mm)</div>
              <input v-model.number="form.target_width" type="number" class="kv-input" />
            </div>
            <div class="form-field">
              <div class="kv-label">卷重 (kg)</div>
              <input v-model.number="form.coil_weight" type="number" class="kv-input" />
            </div>
            <div class="form-field">
              <div class="kv-label">内径 (mm)</div>
              <input v-model.number="form.inner_diameter" type="number" class="kv-input" />
            </div>
            <div class="form-field">
              <div class="kv-label">外径 (mm)</div>
              <input v-model.number="form.outer_diameter" type="number" class="kv-input" />
            </div>
          </div>

          <div class="sec-title">力学性能</div>
          <div class="grid-3" style="gap:12px;margin-bottom:14px;">
            <div class="form-field">
              <div class="kv-label">屈服强度 (MPa)</div>
              <input v-model.number="form.yield_strength" type="number" class="kv-input" />
            </div>
            <div class="form-field">
              <div class="kv-label">抗拉强度 (MPa)</div>
              <input v-model.number="form.tensile_strength" type="number" class="kv-input" />
            </div>
            <div class="form-field">
              <div class="kv-label">延伸率 (%)</div>
              <input v-model.number="form.elongation" type="number" class="kv-input" step="0.1" />
            </div>
          </div>

          <div class="sec-title">状态 / 备注</div>
          <div class="grid-3" style="gap:12px;margin-bottom:14px;">
            <div class="form-field">
              <div class="kv-label">L3状态</div>
              <select v-model="form.l3_status" class="kv-input">
                <option value="pending">待下发</option>
                <option value="sent">已发送</option>
                <option value="confirmed">已确认</option>
                <option value="cancelled">已取消</option>
              </select>
            </div>
            <div class="form-field">
              <div class="kv-label">L2状态</div>
              <select v-model="form.l2_status" class="kv-input">
                <option value="pending">待处理</option>
                <option value="processing">处理中</option>
                <option value="done">已完成</option>
              </select>
            </div>
            <div class="form-field">
              <div class="kv-label">备注</div>
              <input v-model="form.remark" class="kv-input" />
            </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 { getPdiList, createPdi, updatePdi, confirmPdi as apiConfirmPdi, getPdiStats } from '@/api'

const STEEL_GRADES = ['Q195','Q215','Q235','SPHC','SPHD','SPHE','SS400','SAPH440','QSTE420TM']

export default {
  name: 'PDI',
  data() {
    return {
      loading: false, saving: false,
      tableData: [], total: 0,
      stats: { total: 0, pending: 0, confirmed: 0, processing: 0 },
      query: { page: 1, page_size: 20, coil_no: '', l3_status: '', l2_status: '' },
      dialogVisible: false, editRow: null, form: {},
      steelGrades: STEEL_GRADES,
    }
  },
  created() {
    this.fetchData()
    this.fetchStats()
  },
  methods: {
    async fetchData() {
      this.loading = true
      const params = { ...this.query }
      if (!params.coil_no) delete params.coil_no
      if (!params.l3_status) delete params.l3_status
      if (!params.l2_status) delete params.l2_status
      try {
        const res = await getPdiList(params)
        this.tableData = res.data.items
        this.total = res.data.total
      } finally { this.loading = false }
    },
    async fetchStats() {
      try {
        const res = await getPdiStats()
        this.stats = res.data
      } catch (e) { /* ignore */ }
    },
    l3Badge(s) {
      const m = { pending: 'badge-gray', sent: 'badge-blue', confirmed: 'badge-green', cancelled: 'badge-red' }
      return m[s] || 'badge-gray'
    },
    l3Text(s) {
      const m = { pending: '待下发', sent: '已发送', confirmed: '已确认', cancelled: '已取消' }
      return m[s] || s
    },
    l2Badge(s) {
      const m = { pending: 'badge-yellow', processing: 'badge-blue', done: 'badge-green' }
      return m[s] || 'badge-gray'
    },
    l2Text(s) {
      const m = { pending: '待处理', processing: '处理中', done: '已完成' }
      return m[s] || s
    },
    priorityBadge(p) {
      if (p <= 1) return 'badge-red'
      if (p <= 2) return 'badge-yellow'
      return 'badge-blue'
    },
    openDialog(row = null) {
      this.editRow = row
      this.form = row ? { ...row } : { priority: 3, l3_status: 'pending', l2_status: 'pending', process_route: 'P1+P2+P3+P4+P5+P6' }
      this.dialogVisible = true
    },
    async save() {
      if (!this.form.coil_no) { this.$message.error('卷号不能为空'); return }
      this.saving = true
      try {
        if (this.editRow) await updatePdi(this.editRow.id, this.form)
        else await createPdi(this.form)
        this.$message.success('保存成功')
        this.dialogVisible = false
        this.fetchData()
        this.fetchStats()
      } finally { this.saving = false }
    },
    async confirmPdi(row) {
      try {
        await this.$confirm(`确认L2接收卷号 ${row.coil_no} 的PDI？`, '提示', { type: 'warning' })
        await apiConfirmPdi(row.id)
        this.$message.success('L2确认成功')
        this.fetchData()
        this.fetchStats()
      } catch (e) {
        if (e !== 'cancel') this.$message.error('操作失败：' + (e.response?.data?.detail || e.message))
      }
    },
    simulateSend(row) {
      this.$message.info(`已模拟发送卷号 ${row.coil_no} PDI至L3`)
    },
  }
}
</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; }
.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: 760px; 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>
