<template>
  <div class="min-h-screen bg-gray-100 dark:bg-gray-900">
    <!-- 顶部导航 -->
    <div class="bg-white dark:bg-gray-800 shadow">
      <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-4">
        <div class="flex justify-between items-center">
          <h1 class="text-2xl font-bold text-gray-900 dark:text-white">质量管理</h1>
          <div class="flex space-x-4">
            <button @click="showAddInspectionModal = true" class="bg-blue-600 text-white px-4 py-2 rounded-md hover:bg-blue-700">
              新增检验
            </button>
            <button @click="showAddIssueModal = true" class="bg-red-600 text-white px-4 py-2 rounded-md hover:bg-red-700">
              报告问题
            </button>
          </div>
        </div>
      </div>
    </div>

    <!-- 主要内容区域 -->
    <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
      <!-- 质量统计卡片 -->
      <div class="grid grid-cols-1 md:grid-cols-4 gap-6 mb-6">
        <div class="bg-white dark:bg-gray-800 rounded-lg shadow p-6">
          <div class="text-sm font-medium text-gray-500 dark:text-gray-400">本月检验</div>
          <div class="mt-2 text-3xl font-bold text-blue-600 dark:text-blue-400">{{ monthlyInspections }}</div>
          <div class="mt-2 text-sm text-gray-500 dark:text-gray-400">
            合格率 <span :class="passRate >= 95 ? 'text-green-600' : 'text-yellow-600'">{{ passRate }}%</span>
          </div>
        </div>
        <div class="bg-white dark:bg-gray-800 rounded-lg shadow p-6">
          <div class="text-sm font-medium text-gray-500 dark:text-gray-400">待处理问题</div>
          <div class="mt-2 text-3xl font-bold text-yellow-600 dark:text-yellow-400">{{ pendingIssues }}</div>
          <div class="mt-2 text-sm text-gray-500 dark:text-gray-400">
            平均处理时间 <span class="text-blue-600">{{ averageResolutionTime }}天</span>
          </div>
        </div>
        <div class="bg-white dark:bg-gray-800 rounded-lg shadow p-6">
          <div class="text-sm font-medium text-gray-500 dark:text-gray-400">已解决问题</div>
          <div class="mt-2 text-3xl font-bold text-green-600 dark:text-green-400">{{ resolvedIssues }}</div>
          <div class="mt-2 text-sm text-gray-500 dark:text-gray-400">
            解决率 <span class="text-green-600">{{ resolutionRate }}%</span>
          </div>
        </div>
        <div class="bg-white dark:bg-gray-800 rounded-lg shadow p-6">
          <div class="text-sm font-medium text-gray-500 dark:text-gray-400">质量成本</div>
          <div class="mt-2 text-3xl font-bold text-red-600 dark:text-red-400">{{ formatNumber(qualityCost) }}</div>
          <div class="mt-2 text-sm text-gray-500 dark:text-gray-400">
            环比变化 <span :class="costChange >= 0 ? 'text-green-600' : 'text-red-600'">{{ costChange }}%</span>
          </div>
        </div>
      </div>

      <!-- 搜索和筛选 -->
      <div class="bg-white dark:bg-gray-800 rounded-lg shadow p-6 mb-6">
        <div class="grid grid-cols-1 md:grid-cols-4 gap-4">
          <div>
            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">搜索</label>
            <input type="text" v-model="searchText" placeholder="检验编号/问题描述" class="w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 dark:bg-gray-700 dark:border-gray-600 dark:text-white">
          </div>
          <div>
            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">类型</label>
            <select v-model="filters.type" class="w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 dark:bg-gray-700 dark:border-gray-600 dark:text-white">
              <option value="">所有类型</option>
              <option v-for="type in inspectionTypes" :key="type.id" :value="type.id">{{ type.name }}</option>
            </select>
          </div>
          <div>
            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">状态</label>
            <select v-model="filters.status" class="w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 dark:bg-gray-700 dark:border-gray-600 dark:text-white">
              <option value="">所有状态</option>
              <option v-for="status in statusTypes" :key="status.id" :value="status.id">{{ status.name }}</option>
            </select>
          </div>
          <div>
            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">时间范围</label>
            <select v-model="filters.timeRange" class="w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 dark:bg-gray-700 dark:border-gray-600 dark:text-white">
              <option value="">所有时间</option>
              <option v-for="range in timeRanges" :key="range.id" :value="range.id">{{ range.name }}</option>
            </select>
          </div>
        </div>
      </div>

      <!-- 质量检验列表 -->
      <div class="bg-white dark:bg-gray-800 rounded-lg shadow overflow-hidden mb-6">
        <div class="px-6 py-4 border-b border-gray-200 dark:border-gray-700">
          <h2 class="text-lg font-medium text-gray-900 dark:text-white">质量检验列表</h2>
        </div>
        <table class="min-w-full divide-y divide-gray-200 dark:divide-gray-700">
          <thead class="bg-gray-50 dark:bg-gray-700">
            <tr>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">检验信息</th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">产品信息</th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">检验结果</th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">操作</th>
            </tr>
          </thead>
          <tbody class="bg-white dark:bg-gray-800 divide-y divide-gray-200 dark:divide-gray-700">
            <tr v-for="inspection in filteredInspections" :key="inspection.id">
              <td class="px-6 py-4 whitespace-nowrap">
                <div class="text-sm font-medium text-gray-900 dark:text-white">{{ inspection.inspectionNo }}</div>
                <div class="text-sm text-gray-500 dark:text-gray-400">{{ formatDate(inspection.date) }}</div>
                <div class="text-sm text-gray-500 dark:text-gray-400">{{ inspection.typeName }}</div>
              </td>
              <td class="px-6 py-4 whitespace-nowrap">
                <div class="text-sm text-gray-900 dark:text-white">{{ inspection.productName }}</div>
                <div class="text-sm text-gray-500 dark:text-gray-400">{{ inspection.productCode }}</div>
                <div class="text-sm text-gray-500 dark:text-gray-400">批次: {{ inspection.batchNo }}</div>
              </td>
              <td class="px-6 py-4 whitespace-nowrap">
                <span :class="getResultClass(inspection.result)" class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full">
                  {{ getResultName(inspection.result) }}
                </span>
                <div v-if="inspection.defects" class="mt-1 text-sm text-red-600 dark:text-red-400">
                  缺陷: {{ inspection.defects }}
                </div>
              </td>
              <td class="px-6 py-4 whitespace-nowrap text-sm font-medium">
                <button @click="viewInspection(inspection)" class="text-blue-600 hover:text-blue-900 dark:text-blue-400 dark:hover:text-blue-300 mr-3">查看</button>
                <button @click="editInspection(inspection)" class="text-yellow-600 hover:text-yellow-900 dark:text-yellow-400 dark:hover:text-yellow-300 mr-3">编辑</button>
                <button @click="deleteInspection(inspection)" class="text-red-600 hover:text-red-900 dark:text-red-400 dark:hover:text-red-300">删除</button>
              </td>
            </tr>
          </tbody>
        </table>
      </div>

      <!-- 质量问题列表 -->
      <div class="bg-white dark:bg-gray-800 rounded-lg shadow overflow-hidden">
        <div class="px-6 py-4 border-b border-gray-200 dark:border-gray-700">
          <h2 class="text-lg font-medium text-gray-900 dark:text-white">质量问题列表</h2>
        </div>
        <table class="min-w-full divide-y divide-gray-200 dark:divide-gray-700">
          <thead class="bg-gray-50 dark:bg-gray-700">
            <tr>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">问题信息</th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">产品信息</th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">状态</th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">操作</th>
            </tr>
          </thead>
          <tbody class="bg-white dark:bg-gray-800 divide-y divide-gray-200 dark:divide-gray-700">
            <tr v-for="issue in filteredIssues" :key="issue.id">
              <td class="px-6 py-4 whitespace-nowrap">
                <div class="text-sm font-medium text-gray-900 dark:text-white">{{ issue.issueNo }}</div>
                <div class="text-sm text-gray-500 dark:text-gray-400">{{ formatDate(issue.date) }}</div>
                <div class="text-sm text-gray-500 dark:text-gray-400">{{ issue.description }}</div>
              </td>
              <td class="px-6 py-4 whitespace-nowrap">
                <div class="text-sm text-gray-900 dark:text-white">{{ issue.productName }}</div>
                <div class="text-sm text-gray-500 dark:text-gray-400">{{ issue.productCode }}</div>
                <div class="text-sm text-gray-500 dark:text-gray-400">批次: {{ issue.batchNo }}</div>
              </td>
              <td class="px-6 py-4 whitespace-nowrap">
                <span :class="getStatusClass(issue.status)" class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full">
                  {{ getStatusName(issue.status) }}
                </span>
                <div v-if="issue.resolutionDate" class="mt-1 text-sm text-gray-500 dark:text-gray-400">
                  解决日期: {{ formatDate(issue.resolutionDate) }}
                </div>
              </td>
              <td class="px-6 py-4 whitespace-nowrap text-sm font-medium">
                <button @click="viewIssue(issue)" class="text-blue-600 hover:text-blue-900 dark:text-blue-400 dark:hover:text-blue-300 mr-3">查看</button>
                <button @click="editIssue(issue)" class="text-yellow-600 hover:text-yellow-900 dark:text-yellow-400 dark:hover:text-yellow-300 mr-3">编辑</button>
                <button @click="deleteIssue(issue)" class="text-red-600 hover:text-red-900 dark:text-red-400 dark:hover:text-red-300">删除</button>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>

    <!-- 新增检验模态框 -->
    <div v-if="showAddInspectionModal" class="fixed inset-0 bg-gray-500 bg-opacity-75 flex items-center justify-center">
      <div class="bg-white dark:bg-gray-800 rounded-lg shadow-xl max-w-md w-full p-6">
        <h2 class="text-xl font-bold mb-4 text-gray-900 dark:text-white">新增质量检验</h2>
        <form @submit.prevent="addInspection">
          <div class="mb-4">
            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">检验类型</label>
            <select v-model="newInspection.typeId" required class="w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 dark:bg-gray-700 dark:border-gray-600 dark:text-white">
              <option v-for="type in inspectionTypes" :key="type.id" :value="type.id">{{ type.name }}</option>
            </select>
          </div>
          <div class="mb-4">
            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">产品</label>
            <select v-model="newInspection.productId" required class="w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 dark:bg-gray-700 dark:border-gray-600 dark:text-white">
              <option v-for="product in products" :key="product.id" :value="product.id">{{ product.name }}</option>
            </select>
          </div>
          <div class="mb-4">
            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">批次号</label>
            <input type="text" v-model="newInspection.batchNo" required class="w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 dark:bg-gray-700 dark:border-gray-600 dark:text-white">
          </div>
          <div class="mb-4">
            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">检验日期</label>
            <input type="date" v-model="newInspection.date" required class="w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 dark:bg-gray-700 dark:border-gray-600 dark:text-white">
          </div>
          <div class="mb-4">
            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">检验结果</label>
            <select v-model="newInspection.result" required class="w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 dark:bg-gray-700 dark:border-gray-600 dark:text-white">
              <option v-for="result in resultTypes" :key="result.id" :value="result.id">{{ result.name }}</option>
            </select>
          </div>
          <div class="mb-4">
            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">缺陷描述</label>
            <textarea v-model="newInspection.defects" class="w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 dark:bg-gray-700 dark:border-gray-600 dark:text-white"></textarea>
          </div>
          <div class="mb-4">
            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">检验员</label>
            <select v-model="newInspection.inspectorId" required class="w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 dark:bg-gray-700 dark:border-gray-600 dark:text-white">
              <option v-for="inspector in inspectors" :key="inspector.id" :value="inspector.id">{{ inspector.name }}</option>
            </select>
          </div>
          <div class="mb-4">
            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">备注</label>
            <textarea v-model="newInspection.remark" class="w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 dark:bg-gray-700 dark:border-gray-600 dark:text-white"></textarea>
          </div>
          <div class="flex justify-end space-x-3">
            <button type="button" @click="showAddInspectionModal = false" class="px-4 py-2 border border-gray-300 rounded-md text-gray-700 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-700">
              取消
            </button>
            <button type="submit" class="px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700">
              添加
            </button>
          </div>
        </form>
      </div>
    </div>

    <!-- 报告问题模态框 -->
    <div v-if="showAddIssueModal" class="fixed inset-0 bg-gray-500 bg-opacity-75 flex items-center justify-center">
      <div class="bg-white dark:bg-gray-800 rounded-lg shadow-xl max-w-md w-full p-6">
        <h2 class="text-xl font-bold mb-4 text-gray-900 dark:text-white">报告质量问题</h2>
        <form @submit.prevent="addIssue">
          <div class="mb-4">
            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">问题类型</label>
            <select v-model="newIssue.typeId" required class="w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 dark:bg-gray-700 dark:border-gray-600 dark:text-white">
              <option v-for="type in issueTypes" :key="type.id" :value="type.id">{{ type.name }}</option>
            </select>
          </div>
          <div class="mb-4">
            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">产品</label>
            <select v-model="newIssue.productId" required class="w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 dark:bg-gray-700 dark:border-gray-600 dark:text-white">
              <option v-for="product in products" :key="product.id" :value="product.id">{{ product.name }}</option>
            </select>
          </div>
          <div class="mb-4">
            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">批次号</label>
            <input type="text" v-model="newIssue.batchNo" required class="w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 dark:bg-gray-700 dark:border-gray-600 dark:text-white">
          </div>
          <div class="mb-4">
            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">问题描述</label>
            <textarea v-model="newIssue.description" required class="w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 dark:bg-gray-700 dark:border-gray-600 dark:text-white"></textarea>
          </div>
          <div class="mb-4">
            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">严重程度</label>
            <select v-model="newIssue.severity" required class="w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 dark:bg-gray-700 dark:border-gray-600 dark:text-white">
              <option v-for="severity in severityTypes" :key="severity.id" :value="severity.id">{{ severity.name }}</option>
            </select>
          </div>
          <div class="mb-4">
            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">报告人</label>
            <select v-model="newIssue.reporterId" required class="w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 dark:bg-gray-700 dark:border-gray-600 dark:text-white">
              <option v-for="reporter in reporters" :key="reporter.id" :value="reporter.id">{{ reporter.name }}</option>
            </select>
          </div>
          <div class="mb-4">
            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">备注</label>
            <textarea v-model="newIssue.remark" class="w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 dark:bg-gray-700 dark:border-gray-600 dark:text-white"></textarea>
          </div>
          <div class="flex justify-end space-x-3">
            <button type="button" @click="showAddIssueModal = false" class="px-4 py-2 border border-gray-300 rounded-md text-gray-700 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-700">
              取消
            </button>
            <button type="submit" class="px-4 py-2 bg-red-600 text-white rounded-md hover:bg-red-700">
              提交
            </button>
          </div>
        </form>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'

// 质量检验数据
const inspections = ref([
  {
    id: 1,
    inspectionNo: 'QI2024001',
    typeId: 1,
    typeName: '进货检验',
    productId: 1,
    productName: '产品A',
    productCode: 'P001',
    batchNo: 'B2024001',
    date: '2024-01-15',
    result: 1,
    defects: '',
    inspectorId: 1,
    inspector: '张三',
    remark: '检验合格'
  },
  {
    id: 2,
    inspectionNo: 'QI2024002',
    typeId: 2,
    typeName: '过程检验',
    productId: 2,
    productName: '产品B',
    productCode: 'P002',
    batchNo: 'B2024002',
    date: '2024-01-16',
    result: 2,
    defects: '外观缺陷',
    inspectorId: 2,
    inspector: '李四',
    remark: '需要返工'
  }
])

// 质量问题数据
const issues = ref([
  {
    id: 1,
    issueNo: 'QN2024001',
    typeId: 1,
    typeName: '产品缺陷',
    productId: 1,
    productName: '产品A',
    productCode: 'P001',
    batchNo: 'B2024001',
    date: '2024-01-17',
    description: '产品表面有划痕',
    severity: 2,
    status: 1,
    reporterId: 1,
    reporter: '王五',
    resolutionDate: null,
    remark: '需要进一步调查'
  },
  {
    id: 2,
    issueNo: 'QN2024002',
    typeId: 2,
    typeName: '工艺问题',
    productId: 2,
    productName: '产品B',
    productCode: 'P002',
    batchNo: 'B2024002',
    date: '2024-01-18',
    description: '加工精度不达标',
    severity: 3,
    status: 2,
    reporterId: 2,
    reporter: '赵六',
    resolutionDate: '2024-01-20',
    remark: '已调整工艺参数'
  }
])

// 产品数据
const products = ref([
  { id: 1, name: '产品A', code: 'P001' },
  { id: 2, name: '产品B', code: 'P002' }
])

// 检验类型
const inspectionTypes = ref([
  { id: 1, name: '进货检验' },
  { id: 2, name: '过程检验' },
  { id: 3, name: '最终检验' }
])

// 问题类型
const issueTypes = ref([
  { id: 1, name: '产品缺陷' },
  { id: 2, name: '工艺问题' },
  { id: 3, name: '设备故障' },
  { id: 4, name: '其他问题' }
])

// 检验结果类型
const resultTypes = ref([
  { id: 1, name: '合格' },
  { id: 2, name: '不合格' },
  { id: 3, name: '待处理' }
])

// 严重程度类型
const severityTypes = ref([
  { id: 1, name: '轻微' },
  { id: 2, name: '一般' },
  { id: 3, name: '严重' },
  { id: 4, name: '致命' }
])

// 状态类型
const statusTypes = ref([
  { id: 1, name: '待处理' },
  { id: 2, name: '处理中' },
  { id: 3, name: '已解决' },
  { id: 4, name: '已关闭' }
])

// 时间范围
const timeRanges = ref([
  { id: 1, name: '本周' },
  { id: 2, name: '本月' },
  { id: 3, name: '本季度' },
  { id: 4, name: '本年' }
])

// 检验员数据
const inspectors = ref([
  { id: 1, name: '张三', position: '质量检验员' },
  { id: 2, name: '李四', position: '质量主管' }
])

// 报告人数据
const reporters = ref([
  { id: 1, name: '王五', position: '生产主管' },
  { id: 2, name: '赵六', position: '工艺工程师' }
])

// 筛选条件
const searchText = ref('')
const filters = ref({
  type: '',
  status: '',
  timeRange: ''
})

// 模态框状态
const showAddInspectionModal = ref(false)
const showAddIssueModal = ref(false)

// 新检验表单
const newInspection = ref({
  typeId: '',
  productId: '',
  batchNo: '',
  date: '',
  result: '',
  defects: '',
  inspectorId: '',
  remark: ''
})

// 新问题表单
const newIssue = ref({
  typeId: '',
  productId: '',
  batchNo: '',
  description: '',
  severity: '',
  reporterId: '',
  remark: ''
})

// 计算属性
const filteredInspections = computed(() => {
  return inspections.value.filter(inspection => {
    const matchesSearch = !searchText.value || 
      inspection.inspectionNo.toLowerCase().includes(searchText.value.toLowerCase()) ||
      inspection.productName.toLowerCase().includes(searchText.value.toLowerCase())
    const matchesType = !filters.value.type || inspection.typeId === filters.value.type
    const matchesTimeRange = !filters.value.timeRange || checkTimeRange(inspection.date, filters.value.timeRange)
    return matchesSearch && matchesType && matchesTimeRange
  })
})

const filteredIssues = computed(() => {
  return issues.value.filter(issue => {
    const matchesSearch = !searchText.value || 
      issue.issueNo.toLowerCase().includes(searchText.value.toLowerCase()) ||
      issue.description.toLowerCase().includes(searchText.value.toLowerCase())
    const matchesType = !filters.value.type || issue.typeId === filters.value.type
    const matchesStatus = !filters.value.status || issue.status === filters.value.status
    const matchesTimeRange = !filters.value.timeRange || checkTimeRange(issue.date, filters.value.timeRange)
    return matchesSearch && matchesType && matchesStatus && matchesTimeRange
  })
})

const monthlyInspections = computed(() => {
  return inspections.value.filter(inspection => {
    const inspectionDate = new Date(inspection.date)
    const now = new Date()
    return inspectionDate.getMonth() === now.getMonth() && inspectionDate.getFullYear() === now.getFullYear()
  }).length
})

const passRate = computed(() => {
  const monthlyInspections = inspections.value.filter(inspection => {
    const inspectionDate = new Date(inspection.date)
    const now = new Date()
    return inspectionDate.getMonth() === now.getMonth() && inspectionDate.getFullYear() === now.getFullYear()
  })
  if (monthlyInspections.length === 0) return 0
  const passedInspections = monthlyInspections.filter(inspection => inspection.result === 1)
  return Math.round((passedInspections.length / monthlyInspections.length) * 100)
})

const pendingIssues = computed(() => {
  return issues.value.filter(issue => issue.status === 1).length
})

const averageResolutionTime = computed(() => {
  const resolvedIssues = issues.value.filter(issue => issue.status === 3)
  if (resolvedIssues.length === 0) return 0
  const totalDays = resolvedIssues.reduce((sum, issue) => {
    const reportDate = new Date(issue.date)
    const resolveDate = new Date(issue.resolutionDate)
    return sum + Math.ceil((resolveDate - reportDate) / (1000 * 60 * 60 * 24))
  }, 0)
  return Math.round(totalDays / resolvedIssues.length)
})

const resolvedIssues = computed(() => {
  return issues.value.filter(issue => issue.status === 3).length
})

const resolutionRate = computed(() => {
  if (issues.value.length === 0) return 0
  const resolvedIssues = issues.value.filter(issue => issue.status === 3)
  return Math.round((resolvedIssues.length / issues.value.length) * 100)
})

const qualityCost = computed(() => {
  // 这里假设有一个计算质量成本的逻辑
  return 50000
})

const costChange = computed(() => {
  // 这里假设有一个计算环比变化的逻辑
  return -5
})

// 检查时间范围
const checkTimeRange = (date, rangeId) => {
  const now = new Date()
  const targetDate = new Date(date)
  switch (rangeId) {
    case 1: // 本周
      const weekStart = new Date(now.setDate(now.getDate() - now.getDay()))
      const weekEnd = new Date(now.setDate(now.getDate() - now.getDay() + 6))
      return targetDate >= weekStart && targetDate <= weekEnd
    case 2: // 本月
      return targetDate.getMonth() === now.getMonth() && targetDate.getFullYear() === now.getFullYear()
    case 3: // 本季度
      const quarterStart = new Date(now.getFullYear(), Math.floor(now.getMonth() / 3) * 3, 1)
      const quarterEnd = new Date(now.getFullYear(), Math.floor(now.getMonth() / 3) * 3 + 3, 0)
      return targetDate >= quarterStart && targetDate <= quarterEnd
    case 4: // 本年
      return targetDate.getFullYear() === now.getFullYear()
    default:
      return true
  }
}

// 格式化日期
const formatDate = (date) => {
  return new Date(date).toLocaleDateString('zh-CN')
}

// 格式化数字
const formatNumber = (num) => {
  return num.toLocaleString('zh-CN')
}

// 获取结果名称
const getResultName = (resultId) => {
  const result = resultTypes.value.find(r => r.id === resultId)
  return result ? result.name : '未知结果'
}

// 获取结果样式
const getResultClass = (resultId) => {
  const classes = {
    1: 'bg-green-100 text-green-800 dark:bg-green-700 dark:text-green-300',
    2: 'bg-red-100 text-red-800 dark:bg-red-700 dark:text-red-300',
    3: 'bg-yellow-100 text-yellow-800 dark:bg-yellow-700 dark:text-yellow-300'
  }
  return classes[resultId] || 'bg-gray-100 text-gray-800 dark:bg-gray-700 dark:text-gray-300'
}

// 获取状态名称
const getStatusName = (statusId) => {
  const status = statusTypes.value.find(s => s.id === statusId)
  return status ? status.name : '未知状态'
}

// 获取状态样式
const getStatusClass = (statusId) => {
  const classes = {
    1: 'bg-yellow-100 text-yellow-800 dark:bg-yellow-700 dark:text-yellow-300',
    2: 'bg-blue-100 text-blue-800 dark:bg-blue-700 dark:text-blue-300',
    3: 'bg-green-100 text-green-800 dark:bg-green-700 dark:text-green-300',
    4: 'bg-gray-100 text-gray-800 dark:bg-gray-700 dark:text-gray-300'
  }
  return classes[statusId] || 'bg-gray-100 text-gray-800 dark:bg-gray-700 dark:text-gray-300'
}

// 添加检验
const addInspection = () => {
  const type = inspectionTypes.value.find(t => t.id === newInspection.value.typeId)
  const product = products.value.find(p => p.id === newInspection.value.productId)
  const inspector = inspectors.value.find(i => i.id === newInspection.value.inspectorId)
  const inspection = {
    id: inspections.value.length + 1,
    inspectionNo: `QI${new Date().getFullYear()}${String(inspections.value.length + 1).padStart(3, '0')}`,
    typeId: newInspection.value.typeId,
    typeName: type.name,
    productId: newInspection.value.productId,
    productName: product.name,
    productCode: product.code,
    batchNo: newInspection.value.batchNo,
    date: newInspection.value.date,
    result: newInspection.value.result,
    defects: newInspection.value.defects,
    inspectorId: newInspection.value.inspectorId,
    inspector: inspector.name,
    remark: newInspection.value.remark
  }
  inspections.value.push(inspection)
  showAddInspectionModal.value = false
  resetNewInspection()
}

// 重置新检验表单
const resetNewInspection = () => {
  newInspection.value = {
    typeId: '',
    productId: '',
    batchNo: '',
    date: '',
    result: '',
    defects: '',
    inspectorId: '',
    remark: ''
  }
}

// 添加问题
const addIssue = () => {
  const type = issueTypes.value.find(t => t.id === newIssue.value.typeId)
  const product = products.value.find(p => p.id === newIssue.value.productId)
  const reporter = reporters.value.find(r => r.id === newIssue.value.reporterId)
  const issue = {
    id: issues.value.length + 1,
    issueNo: `QN${new Date().getFullYear()}${String(issues.value.length + 1).padStart(3, '0')}`,
    typeId: newIssue.value.typeId,
    typeName: type.name,
    productId: newIssue.value.productId,
    productName: product.name,
    productCode: product.code,
    batchNo: newIssue.value.batchNo,
    date: new Date().toISOString().split('T')[0],
    description: newIssue.value.description,
    severity: newIssue.value.severity,
    status: 1,
    reporterId: newIssue.value.reporterId,
    reporter: reporter.name,
    resolutionDate: null,
    remark: newIssue.value.remark
  }
  issues.value.push(issue)
  showAddIssueModal.value = false
  resetNewIssue()
}

// 重置新问题表单
const resetNewIssue = () => {
  newIssue.value = {
    typeId: '',
    productId: '',
    batchNo: '',
    description: '',
    severity: '',
    reporterId: '',
    remark: ''
  }
}

// 查看检验
const viewInspection = (inspection) => {
  // 实现查看检验逻辑
  console.log('查看检验:', inspection)
}

// 编辑检验
const editInspection = (inspection) => {
  // 实现编辑检验逻辑
  console.log('编辑检验:', inspection)
}

// 删除检验
const deleteInspection = (inspection) => {
  if (confirm(`确定要删除检验记录"${inspection.inspectionNo}"吗？`)) {
    const index = inspections.value.findIndex(i => i.id === inspection.id)
    if (index !== -1) {
      inspections.value.splice(index, 1)
    }
  }
}

// 查看问题
const viewIssue = (issue) => {
  // 实现查看问题逻辑
  console.log('查看问题:', issue)
}

// 编辑问题
const editIssue = (issue) => {
  // 实现编辑问题逻辑
  console.log('编辑问题:', issue)
}

// 删除问题
const deleteIssue = (issue) => {
  if (confirm(`确定要删除问题记录"${issue.issueNo}"吗？`)) {
    const index = issues.value.findIndex(i => i.id === issue.id)
    if (index !== -1) {
      issues.value.splice(index, 1)
    }
  }
}
</script> 