<template>
  <div>
    <!-- ─── 标签页 ─── -->
    <div class="tab-bar">
      <span :class="['tab-item', { active: activeTab === 'tasks' }]" @click="activeTab = 'tasks'">检验任务</span>
      <span :class="['tab-item', { active: activeTab === 'defects' }]" @click="activeTab = 'defects'; fetchDefects()">缺陷记录</span>
    </div>

    <!-- ═══════════════════════════════════════ 检验任务 Tab ═══════════════════════════════════════ -->
    <template v-if="activeTab === 'tasks'">
      <!-- 过滤栏 -->
      <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="taskQuery.task_code" class="kv-input" style="width:130px;" @keyup.enter="fetchTasks" />
            </div>
            <div class="flex-row">
              <span class="kv-label">卷号</span>
              <input v-model="taskQuery.coil_no" class="kv-input" style="width:120px;" @keyup.enter="fetchTasks" />
            </div>
            <div class="flex-row">
              <span class="kv-label">状态</span>
              <select v-model="taskQuery.status" class="kv-input" style="width:100px;">
                <option value="">全部</option>
                <option value="0">待检验</option>
                <option value="1">检验中</option>
                <option value="2">待审核</option>
                <option value="3">完成</option>
              </select>
            </div>
            <div class="flex-row">
              <span class="kv-label">结果</span>
              <select v-model="taskQuery.result" class="kv-input" style="width:100px;">
                <option value="">全部</option>
                <option value="qualified">合格</option>
                <option value="unqualified">不合格</option>
              </select>
            </div>
            <div class="flex-row">
              <span class="kv-label">日期</span>
              <input v-model="taskQuery.start_date" type="date" class="kv-input" style="width:140px;" />
              <span class="kv-label">~</span>
              <input v-model="taskQuery.end_date" type="date" class="kv-input" style="width:140px;" />
            </div>
            <div class="flex-row">
              <button class="btn btn-primary" @click="fetchTasks">查询</button>
              <button class="btn btn-outline" @click="openTaskDialog()">＋ 新增任务</button>
            </div>
          </div>
        </div>
      </div>

      <!-- 主体区域：任务列表 + 检验项面板 -->
      <div class="section-row">
        <!-- 任务列表 -->
        <div class="card" style="flex:3;min-width:0;">
          <div class="card-header">
            检验任务列表
            <span class="ch-badge">共 {{ taskTotal }} 条</span>
          </div>
          <div class="table-scroll">
            <table class="data-table">
              <thead>
                <tr>
                  <th>任务编号</th>
                  <th>卷号</th>
                  <th>方案名称</th>
                  <th>检验人员</th>
                  <th>检验时间</th>
                  <th>状态</th>
                  <th>结果</th>
                  <th>创建时间</th>
                  <th>操作</th>
                </tr>
              </thead>
              <tbody>
                <tr
                  v-for="row in taskData"
                  :key="row.id"
                  :class="{ 'row-selected': selectedTask && selectedTask.id === row.id }"
                  style="cursor:pointer;"
                  @click="selectTask(row)"
                >
                  <td class="td-num">{{ row.task_code }}</td>
                  <td class="td-num">{{ row.coil_no || '—' }}</td>
                  <td>{{ row.scheme_name || '—' }}</td>
                  <td class="td-muted">{{ row.inspect_user || '—' }}</td>
                  <td class="td-muted">{{ fmtTime(row.inspect_time) }}</td>
                  <td><span :class="['badge', taskStatusBadge(row.status)]">{{ taskStatusLabel(row.status) }}</span></td>
                  <td>
                    <span v-if="row.result" :class="['badge', row.result === 'qualified' ? 'badge-green' : 'badge-red']">
                      {{ row.result === 'qualified' ? '合格' : '不合格' }}
                    </span>
                    <span v-else class="td-muted">—</span>
                  </td>
                  <td class="td-muted">{{ fmtTime(row.created_at) }}</td>
                  <td>
                    <span class="action-link" @click.stop="openTaskDialog(row)">编辑</span>
                    <span class="action-link" style="color:#da3633;" @click.stop="deleteTask(row)">删除</span>
                  </td>
                </tr>
                <tr v-if="!taskData.length">
                  <td colspan="9" class="td-muted" style="text-align:center;padding:24px;">暂无数据</td>
                </tr>
              </tbody>
            </table>
          </div>
          <div class="card-body" style="padding:8px 14px;" v-if="taskTotal > taskQuery.page_size">
            <div class="flex-row">
              <button class="btn btn-outline" :disabled="taskQuery.page <= 1" @click="taskQuery.page--; fetchTasks()">上一页</button>
              <span class="kv-label">第 {{ taskQuery.page }} / {{ Math.ceil(taskTotal / taskQuery.page_size) }} 页</span>
              <button class="btn btn-outline" :disabled="taskQuery.page >= Math.ceil(taskTotal / taskQuery.page_size)" @click="taskQuery.page++; fetchTasks()">下一页</button>
            </div>
          </div>
        </div>

        <!-- 检验项面板 -->
        <div class="card" style="flex:2;min-width:0;">
          <div class="card-header">
            <span v-if="selectedTask">
              检验项 &nbsp;<span class="td-muted" style="font-weight:400;font-size:11px;">{{ selectedTask.task_code }}</span>
            </span>
            <span v-else>检验项（请点击任务行）</span>
            <button v-if="selectedTask" class="btn btn-outline" style="padding:2px 10px;font-size:11px;" @click="openItemDialog()">＋ 添加项目</button>
          </div>
          <div class="table-scroll">
            <table class="data-table">
              <thead>
                <tr>
                  <th>检验项名称</th>
                  <th>类型</th>
                  <th>标准值</th>
                  <th>上限</th>
                  <th>下限</th>
                  <th>单位</th>
                  <th>实测值</th>
                  <th>是否合格</th>
                  <th>判定结果</th>
                  <th>检验人</th>
                  <th>检验时间</th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="item in taskItems" :key="item.id">
                  <td>{{ item.item_name }}</td>
                  <td class="td-muted">{{ item.item_type || '—' }}</td>
                  <td class="td-num">{{ item.standard_value != null ? item.standard_value : '—' }}</td>
                  <td class="td-num">{{ item.upper_limit != null ? item.upper_limit : '—' }}</td>
                  <td class="td-num">{{ item.lower_limit != null ? item.lower_limit : '—' }}</td>
                  <td class="td-muted">{{ item.unit || '—' }}</td>
                  <td class="td-num">{{ item.inspect_value || '—' }}</td>
                  <td>
                    <span v-if="item.is_qualified != null" :class="['badge', item.is_qualified ? 'badge-green' : 'badge-red']">
                      {{ item.is_qualified ? '合格' : '不合格' }}
                    </span>
                    <span v-else class="td-muted">—</span>
                  </td>
                  <td class="td-muted">{{ item.judge_result || '—' }}</td>
                  <td class="td-muted">{{ item.inspect_user || '—' }}</td>
                  <td class="td-muted">{{ fmtTime(item.inspect_time) }}</td>
                </tr>
                <tr v-if="!taskItems.length">
                  <td colspan="11" class="td-muted" style="text-align:center;padding:20px;">
                    {{ selectedTask ? '暂无检验项' : '请先选择任务' }}
                  </td>
                </tr>
              </tbody>
            </table>
          </div>
        </div>
      </div>
    </template>

    <!-- ═══════════════════════════════════════ 缺陷记录 Tab ═══════════════════════════════════════ -->
    <template v-if="activeTab === 'defects'">
      <!-- 过滤栏 -->
      <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="defectQuery.coil_no" class="kv-input" style="width:130px;" @keyup.enter="fetchDefects" />
            </div>
            <div class="flex-row">
              <span class="kv-label">缺陷类型</span>
              <input v-model="defectQuery.defect_type" class="kv-input" style="width:120px;" @keyup.enter="fetchDefects" />
            </div>
            <div class="flex-row">
              <span class="kv-label">严重程度</span>
              <select v-model="defectQuery.degree" class="kv-input" style="width:100px;">
                <option value="">全部</option>
                <option value="light">轻微</option>
                <option value="normal">一般</option>
                <option value="serious">严重</option>
              </select>
            </div>
            <div class="flex-row">
              <span class="kv-label">日期</span>
              <input v-model="defectQuery.start_date" type="date" class="kv-input" style="width:140px;" />
              <span class="kv-label">~</span>
              <input v-model="defectQuery.end_date" type="date" class="kv-input" style="width:140px;" />
            </div>
            <div class="flex-row">
              <button class="btn btn-primary" @click="fetchDefects">查询</button>
              <button class="btn btn-outline" @click="openDefectDialog()">＋ 新增缺陷</button>
            </div>
          </div>
        </div>
      </div>

      <!-- 缺陷列表 -->
      <div class="card">
        <div class="card-header">
          缺陷记录列表
          <span class="ch-badge">共 {{ defectTotal }} 条</span>
        </div>
        <div class="table-scroll">
          <table class="data-table">
            <thead>
              <tr>
                <th>卷号</th>
                <th>产线</th>
                <th>位置</th>
                <th>板面</th>
                <th>缺陷代码</th>
                <th>缺陷类型</th>
                <th>缺陷率(%)</th>
                <th>缺陷重量</th>
                <th>严重程度</th>
                <th>判定等级</th>
                <th>判定人</th>
                <th>判定时间</th>
                <th>操作</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="row in defectData" :key="row.id">
                <td class="td-num">{{ row.coil_no || '—' }}</td>
                <td class="td-muted">{{ row.production_line || '—' }}</td>
                <td class="td-muted">{{ row.position || '—' }}</td>
                <td class="td-muted">{{ row.plate_surface || '—' }}</td>
                <td class="td-num">{{ row.defect_code || '—' }}</td>
                <td>{{ row.defect_type || '—' }}</td>
                <td class="td-num">{{ row.defect_rate != null ? row.defect_rate : '—' }}</td>
                <td class="td-num">{{ row.defect_weight != null ? row.defect_weight : '—' }}</td>
                <td>
                  <span v-if="row.degree" :class="['badge', degreeBadge(row.degree)]">{{ degreeLabel(row.degree) }}</span>
                  <span v-else class="td-muted">—</span>
                </td>
                <td class="td-muted">{{ row.judge_level || '—' }}</td>
                <td class="td-muted">{{ row.judge_by || '—' }}</td>
                <td class="td-muted">{{ fmtTime(row.judge_time) }}</td>
                <td>
                  <span class="action-link" @click="openDefectDialog(row)">编辑</span>
                  <span class="action-link" style="color:#da3633;" @click="deleteDefect(row)">删除</span>
                </td>
              </tr>
              <tr v-if="!defectData.length">
                <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="defectTotal > defectQuery.page_size">
          <div class="flex-row">
            <button class="btn btn-outline" :disabled="defectQuery.page <= 1" @click="defectQuery.page--; fetchDefects()">上一页</button>
            <span class="kv-label">第 {{ defectQuery.page }} / {{ Math.ceil(defectTotal / defectQuery.page_size) }} 页</span>
            <button class="btn btn-outline" :disabled="defectQuery.page >= Math.ceil(defectTotal / defectQuery.page_size)" @click="defectQuery.page++; fetchDefects()">下一页</button>
          </div>
        </div>
      </div>
    </template>

    <!-- ─── 新增/编辑任务弹窗 ─── -->
    <div v-if="taskDialogVisible" class="modal-mask" @click.self="taskDialogVisible = false">
      <div class="modal-box" style="width:560px;">
        <div class="modal-header">
          {{ editTask ? '编辑任务 #' + editTask.id : '新增检验任务' }}
          <span class="modal-close" @click="taskDialogVisible = false">✕</span>
        </div>
        <div class="modal-body">
          <div class="grid-2" style="gap:12px;">
            <div class="form-field">
              <div class="kv-label">任务编号 *</div>
              <input v-model="taskForm.task_code" class="kv-input" :disabled="!!editTask" />
            </div>
            <div class="form-field">
              <div class="kv-label">卷号</div>
              <input v-model="taskForm.coil_no" class="kv-input" />
            </div>
            <div class="form-field">
              <div class="kv-label">任务类型</div>
              <select v-model="taskForm.task_type" class="kv-input">
                <option value="">请选择</option>
                <option value="incoming">来料检验</option>
                <option value="process">过程检验</option>
                <option value="final">成品检验</option>
              </select>
            </div>
            <div class="form-field">
              <div class="kv-label">方案名称</div>
              <input v-model="taskForm.scheme_name" class="kv-input" />
            </div>
            <div class="form-field">
              <div class="kv-label">检验人员</div>
              <input v-model="taskForm.inspect_user" class="kv-input" />
            </div>
            <div v-if="editTask" class="form-field">
              <div class="kv-label">状态</div>
              <select v-model="taskForm.status" class="kv-input">
                <option :value="0">待检验</option>
                <option :value="1">检验中</option>
                <option :value="2">待审核</option>
                <option :value="3">完成</option>
              </select>
            </div>
            <div v-if="editTask" class="form-field">
              <div class="kv-label">检验结果</div>
              <select v-model="taskForm.result" class="kv-input">
                <option value="">待定</option>
                <option value="qualified">合格</option>
                <option value="unqualified">不合格</option>
              </select>
            </div>
            <div class="form-field" style="grid-column:1/-1;">
              <div class="kv-label">备注</div>
              <textarea v-model="taskForm.remark" class="kv-input" rows="2"></textarea>
            </div>
          </div>
        </div>
        <div class="modal-footer">
          <button class="btn btn-outline" @click="taskDialogVisible = false">取消</button>
          <button class="btn btn-primary" :disabled="saving" @click="saveTask">{{ saving ? '保存中...' : '保存' }}</button>
        </div>
      </div>
    </div>

    <!-- ─── 添加检验项弹窗 ─── -->
    <div v-if="itemDialogVisible" class="modal-mask" @click.self="itemDialogVisible = false">
      <div class="modal-box" style="width:500px;">
        <div class="modal-header">
          添加检验项
          <span class="modal-close" @click="itemDialogVisible = false">✕</span>
        </div>
        <div class="modal-body">
          <div class="grid-2" style="gap:12px;">
            <div class="form-field" style="grid-column:1/-1;">
              <div class="kv-label">检验项名称 *</div>
              <input v-model="itemForm.item_name" class="kv-input" />
            </div>
            <div class="form-field">
              <div class="kv-label">类型</div>
              <select v-model="itemForm.item_type" class="kv-input">
                <option value="">请选择</option>
                <option value="quantitative">定量</option>
                <option value="qualitative">定性</option>
              </select>
            </div>
            <div class="form-field">
              <div class="kv-label">单位</div>
              <input v-model="itemForm.unit" class="kv-input" />
            </div>
            <div class="form-field">
              <div class="kv-label">标准值</div>
              <input v-model.number="itemForm.standard_value" type="number" class="kv-input" />
            </div>
            <div class="form-field">
              <div class="kv-label">上限</div>
              <input v-model.number="itemForm.upper_limit" type="number" class="kv-input" />
            </div>
            <div class="form-field">
              <div class="kv-label">下限</div>
              <input v-model.number="itemForm.lower_limit" type="number" class="kv-input" />
            </div>
            <div class="form-field">
              <div class="kv-label">实测值</div>
              <input v-model="itemForm.inspect_value" class="kv-input" />
            </div>
            <div class="form-field">
              <div class="kv-label">是否合格</div>
              <select v-model="itemForm.is_qualified" class="kv-input">
                <option :value="null">待判定</option>
                <option :value="1">合格</option>
                <option :value="0">不合格</option>
              </select>
            </div>
            <div class="form-field">
              <div class="kv-label">检验人</div>
              <input v-model="itemForm.inspect_user" class="kv-input" />
            </div>
            <div class="form-field" style="grid-column:1/-1;">
              <div class="kv-label">判定结果说明</div>
              <input v-model="itemForm.judge_result" class="kv-input" />
            </div>
          </div>
        </div>
        <div class="modal-footer">
          <button class="btn btn-outline" @click="itemDialogVisible = false">取消</button>
          <button class="btn btn-primary" :disabled="saving" @click="saveItem">{{ saving ? '保存中...' : '保存' }}</button>
        </div>
      </div>
    </div>

    <!-- ─── 新增/编辑缺陷弹窗 ─── -->
    <div v-if="defectDialogVisible" class="modal-mask" @click.self="defectDialogVisible = false">
      <div class="modal-box" style="width:580px;">
        <div class="modal-header">
          {{ editDefect ? '编辑缺陷记录 #' + editDefect.id : '新增缺陷记录' }}
          <span class="modal-close" @click="defectDialogVisible = false">✕</span>
        </div>
        <div class="modal-body">
          <div class="grid-2" style="gap:12px;">
            <div class="form-field">
              <div class="kv-label">卷号</div>
              <input v-model="defectForm.coil_no" class="kv-input" />
            </div>
            <div class="form-field">
              <div class="kv-label">产线</div>
              <input v-model="defectForm.production_line" class="kv-input" />
            </div>
            <div class="form-field">
              <div class="kv-label">位置</div>
              <input v-model="defectForm.position" class="kv-input" />
            </div>
            <div class="form-field">
              <div class="kv-label">板面</div>
              <select v-model="defectForm.plate_surface" class="kv-input">
                <option value="">请选择</option>
                <option value="上表面">上表面</option>
                <option value="下表面">下表面</option>
                <option value="双面">双面</option>
              </select>
            </div>
            <div class="form-field">
              <div class="kv-label">缺陷代码</div>
              <input v-model="defectForm.defect_code" class="kv-input" />
            </div>
            <div class="form-field">
              <div class="kv-label">缺陷类型</div>
              <input v-model="defectForm.defect_type" class="kv-input" />
            </div>
            <div class="form-field">
              <div class="kv-label">缺陷率(%)</div>
              <input v-model.number="defectForm.defect_rate" type="number" step="0.01" class="kv-input" />
            </div>
            <div class="form-field">
              <div class="kv-label">缺陷重量(kg)</div>
              <input v-model.number="defectForm.defect_weight" type="number" step="0.1" class="kv-input" />
            </div>
            <div class="form-field">
              <div class="kv-label">严重程度</div>
              <select v-model="defectForm.degree" class="kv-input">
                <option value="">请选择</option>
                <option value="light">轻微</option>
                <option value="normal">一般</option>
                <option value="serious">严重</option>
              </select>
            </div>
            <div class="form-field">
              <div class="kv-label">判定等级</div>
              <input v-model="defectForm.judge_level" class="kv-input" />
            </div>
            <div class="form-field">
              <div class="kv-label">判定人</div>
              <input v-model="defectForm.judge_by" class="kv-input" />
            </div>
            <div class="form-field">
              <div class="kv-label">判定时间</div>
              <input v-model="defectForm.judge_time" type="datetime-local" class="kv-input" />
            </div>
            <div class="form-field" style="grid-column:1/-1;">
              <div class="kv-label">备注</div>
              <textarea v-model="defectForm.remark" class="kv-input" rows="2"></textarea>
            </div>
          </div>
        </div>
        <div class="modal-footer">
          <button class="btn btn-outline" @click="defectDialogVisible = false">取消</button>
          <button class="btn btn-primary" :disabled="saving" @click="saveDefect">{{ saving ? '保存中...' : '保存' }}</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import {
  getQcTasks, createQcTask, updateQcTask, deleteQcTask,
  getQcTaskItems, createQcTaskItem,
  getQcDefects, createQcDefect, updateQcDefect, deleteQcDefect,
} from '@/api'

const TASK_STATUS = {
  0: { label: '待检验', badge: 'badge-gray' },
  1: { label: '检验中', badge: 'badge-yellow' },
  2: { label: '待审核', badge: 'badge' },
  3: { label: '完成',   badge: 'badge-green' },
}

const DEGREE_MAP = {
  light:   { label: '轻微', badge: 'badge-blue' },
  normal:  { label: '一般', badge: 'badge-yellow' },
  serious: { label: '严重', badge: 'badge-red' },
}

export default {
  name: 'Quality',
  data() {
    return {
      activeTab: 'tasks',
      saving: false,

      // 任务
      taskData: [], taskTotal: 0,
      taskQuery: { page: 1, page_size: 20, task_code: '', coil_no: '', status: '', result: '', start_date: '', end_date: '' },
      selectedTask: null,
      taskItems: [],
      taskDialogVisible: false, editTask: null, taskForm: {},
      itemDialogVisible: false, itemForm: {},

      // 缺陷
      defectData: [], defectTotal: 0,
      defectQuery: { page: 1, page_size: 20, coil_no: '', defect_type: '', degree: '', start_date: '', end_date: '' },
      defectDialogVisible: false, editDefect: null, defectForm: {},
    }
  },
  created() {
    this.fetchTasks()
  },
  methods: {
    // ── 任务 ──────────────────────────────────────
    async fetchTasks() {
      const params = {}
      if (this.taskQuery.task_code) params.task_code = this.taskQuery.task_code
      if (this.taskQuery.coil_no) params.coil_no = this.taskQuery.coil_no
      if (this.taskQuery.status !== '') params.status = this.taskQuery.status
      if (this.taskQuery.result) params.result = this.taskQuery.result
      if (this.taskQuery.start_date) params.start_date = this.taskQuery.start_date
      if (this.taskQuery.end_date) params.end_date = this.taskQuery.end_date
      params.page = this.taskQuery.page
      params.page_size = this.taskQuery.page_size
      try {
        const res = await getQcTasks(params)
        this.taskData = res.data.items
        this.taskTotal = res.data.total
      } catch (e) { /* ignore */ }
    },
    async selectTask(row) {
      this.selectedTask = row
      try {
        const res = await getQcTaskItems(row.id)
        this.taskItems = res.data || []
      } catch (e) { this.taskItems = [] }
    },
    openTaskDialog(row = null) {
      this.editTask = row
      this.taskForm = row ? { ...row } : { task_code: '', status: 0 }
      this.taskDialogVisible = true
    },
    async saveTask() {
      if (!this.taskForm.task_code) { this.$message.error('任务编号不能为空'); return }
      this.saving = true
      try {
        if (this.editTask) {
          await updateQcTask(this.editTask.id, this.taskForm)
        } else {
          await createQcTask(this.taskForm)
        }
        this.$message.success('保存成功')
        this.taskDialogVisible = false
        this.fetchTasks()
      } finally { this.saving = false }
    },
    async deleteTask(row) {
      if (!confirm(`确认删除任务 ${row.task_code}？`)) return
      try {
        await deleteQcTask(row.id)
        this.$message.success('已删除')
        if (this.selectedTask && this.selectedTask.id === row.id) {
          this.selectedTask = null
          this.taskItems = []
        }
        this.fetchTasks()
      } catch (e) { this.$message.error('删除失败') }
    },

    // ── 检验项 ────────────────────────────────────
    openItemDialog() {
      this.itemForm = { task_id: this.selectedTask.id, item_name: '', is_qualified: null }
      this.itemDialogVisible = true
    },
    async saveItem() {
      if (!this.itemForm.item_name) { this.$message.error('检验项名称不能为空'); return }
      this.saving = true
      try {
        await createQcTaskItem({ ...this.itemForm, task_id: this.selectedTask.id })
        this.$message.success('添加成功')
        this.itemDialogVisible = false
        await this.selectTask(this.selectedTask)
      } finally { this.saving = false }
    },

    // ── 缺陷 ──────────────────────────────────────
    async fetchDefects() {
      const params = {}
      if (this.defectQuery.coil_no) params.coil_no = this.defectQuery.coil_no
      if (this.defectQuery.defect_type) params.defect_type = this.defectQuery.defect_type
      if (this.defectQuery.degree) params.degree = this.defectQuery.degree
      if (this.defectQuery.start_date) params.start_date = this.defectQuery.start_date
      if (this.defectQuery.end_date) params.end_date = this.defectQuery.end_date
      params.page = this.defectQuery.page
      params.page_size = this.defectQuery.page_size
      try {
        const res = await getQcDefects(params)
        this.defectData = res.data.items
        this.defectTotal = res.data.total
      } catch (e) { /* ignore */ }
    },
    openDefectDialog(row = null) {
      this.editDefect = row
      this.defectForm = row ? { ...row } : {}
      this.defectDialogVisible = true
    },
    async saveDefect() {
      this.saving = true
      try {
        if (this.editDefect) {
          await updateQcDefect(this.editDefect.id, this.defectForm)
        } else {
          await createQcDefect(this.defectForm)
        }
        this.$message.success('保存成功')
        this.defectDialogVisible = false
        this.fetchDefects()
      } finally { this.saving = false }
    },
    async deleteDefect(row) {
      if (!confirm('确认删除该缺陷记录？')) return
      try {
        await deleteQcDefect(row.id)
        this.$message.success('已删除')
        this.fetchDefects()
      } catch (e) { this.$message.error('删除失败') }
    },

    // ── 工具方法 ──────────────────────────────────
    fmtTime(t) { return t ? t.slice(0, 16).replace('T', ' ') : '—' },
    taskStatusLabel(s) { return TASK_STATUS[s]?.label || s },
    taskStatusBadge(s) { return TASK_STATUS[s]?.badge || 'badge-gray' },
    degreeLabel(d) { return DEGREE_MAP[d]?.label || d },
    degreeBadge(d) { return DEGREE_MAP[d]?.badge || 'badge-gray' },
  },
}
</script>

<style lang="scss" scoped>
@import '@/assets/styles/variables';

.tab-bar {
  display: flex;
  gap: 0;
  margin-bottom: 14px;
  border-bottom: 2px solid $border;
}
.tab-item {
  padding: 8px 20px;
  font-size: 13px;
  cursor: pointer;
  color: $text-muted;
  border-bottom: 2px solid transparent;
  margin-bottom: -2px;
  transition: all .15s;
  &:hover { color: $text-primary; }
  &.active { color: $sms-highlight; border-bottom-color: $sms-highlight; font-weight: 600; }
}
.section-row { display: flex; gap: 14px; align-items: flex-start; }
.grid-2 { display: grid; grid-template-columns: 1fr 1fr; }
.row-selected { background: rgba(0,200,255,.08) !important; }
.form-field { display: flex; flex-direction: column; gap: 5px; }
.action-link { color: $sms-highlight; cursor: pointer; font-size: 12px; margin-right: 10px; &:hover { text-decoration: underline; } }
.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; 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>
