<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="showAddEquipmentModal = true" class="bg-blue-600 text-white px-4 py-2 rounded-md hover:bg-blue-700">
              新增设备
            </button>
            <button @click="showAddMaintenanceModal = true" class="bg-yellow-600 text-white px-4 py-2 rounded-md hover:bg-yellow-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">{{ totalEquipment }}</div>
          <div class="mt-2 text-sm text-gray-500 dark:text-gray-400">
            在用设备 <span class="text-green-600">{{ activeEquipment }}</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">{{ pendingMaintenance }}</div>
          <div class="mt-2 text-sm text-gray-500 dark:text-gray-400">
            维护完成率 <span class="text-green-600">{{ maintenanceCompletionRate }}%</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">{{ faultyEquipment }}</div>
          <div class="mt-2 text-sm text-gray-500 dark:text-gray-400">
            平均修复时间 <span class="text-blue-600">{{ averageRepairTime }}天</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">{{ equipmentUtilization }}%</div>
          <div class="mt-2 text-sm text-gray-500 dark:text-gray-400">
            环比变化 <span :class="utilizationChange >= 0 ? 'text-green-600' : 'text-red-600'">{{ utilizationChange }}%</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 equipmentTypes" :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.department" 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="dept in departments" :key="dept.id" :value="dept.id">{{ dept.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="equipment in filteredEquipment" :key="equipment.id">
              <td class="px-6 py-4 whitespace-nowrap">
                <div class="text-sm font-medium text-gray-900 dark:text-white">{{ equipment.equipmentNo }}</div>
                <div class="text-sm text-gray-500 dark:text-gray-400">{{ equipment.name }}</div>
                <div class="text-sm text-gray-500 dark:text-gray-400">{{ equipment.typeName }}</div>
              </td>
              <td class="px-6 py-4 whitespace-nowrap">
                <div class="text-sm text-gray-900 dark:text-white">{{ equipment.model }}</div>
                <div class="text-sm text-gray-500 dark:text-gray-400">部门: {{ equipment.departmentName }}</div>
                <div class="text-sm text-gray-500 dark:text-gray-400">负责人: {{ equipment.manager }}</div>
              </td>
              <td class="px-6 py-4 whitespace-nowrap">
                <span :class="getStatusClass(equipment.status)" class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full">
                  {{ getStatusName(equipment.status) }}
                </span>
                <div v-if="equipment.lastMaintenance" class="mt-1 text-sm text-gray-500 dark:text-gray-400">
                  上次维护: {{ formatDate(equipment.lastMaintenance) }}
                </div>
                <div v-if="equipment.nextMaintenance" class="mt-1 text-sm text-gray-500 dark:text-gray-400">
                  下次维护: {{ formatDate(equipment.nextMaintenance) }}
                </div>
              </td>
              <td class="px-6 py-4 whitespace-nowrap text-sm font-medium">
                <button @click="viewEquipment(equipment)" class="text-blue-600 hover:text-blue-900 dark:text-blue-400 dark:hover:text-blue-300 mr-3">查看</button>
                <button @click="editEquipment(equipment)" class="text-yellow-600 hover:text-yellow-900 dark:text-yellow-400 dark:hover:text-yellow-300 mr-3">编辑</button>
                <button @click="deleteEquipment(equipment)" 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="maintenance in filteredMaintenance" :key="maintenance.id">
              <td class="px-6 py-4 whitespace-nowrap">
                <div class="text-sm font-medium text-gray-900 dark:text-white">{{ maintenance.maintenanceNo }}</div>
                <div class="text-sm text-gray-500 dark:text-gray-400">{{ maintenance.typeName }}</div>
                <div class="text-sm text-gray-500 dark:text-gray-400">计划日期: {{ formatDate(maintenance.planDate) }}</div>
              </td>
              <td class="px-6 py-4 whitespace-nowrap">
                <div class="text-sm text-gray-900 dark:text-white">{{ maintenance.equipmentName }}</div>
                <div class="text-sm text-gray-500 dark:text-gray-400">{{ maintenance.equipmentNo }}</div>
                <div class="text-sm text-gray-500 dark:text-gray-400">负责人: {{ maintenance.manager }}</div>
              </td>
              <td class="px-6 py-4 whitespace-nowrap">
                <span :class="getStatusClass(maintenance.status)" class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full">
                  {{ getStatusName(maintenance.status) }}
                </span>
                <div v-if="maintenance.completionDate" class="mt-1 text-sm text-gray-500 dark:text-gray-400">
                  完成日期: {{ formatDate(maintenance.completionDate) }}
                </div>
              </td>
              <td class="px-6 py-4 whitespace-nowrap text-sm font-medium">
                <button @click="viewMaintenance(maintenance)" class="text-blue-600 hover:text-blue-900 dark:text-blue-400 dark:hover:text-blue-300 mr-3">查看</button>
                <button @click="editMaintenance(maintenance)" class="text-yellow-600 hover:text-yellow-900 dark:text-yellow-400 dark:hover:text-yellow-300 mr-3">编辑</button>
                <button @click="deleteMaintenance(maintenance)" 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="showAddEquipmentModal" 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="addEquipment">
          <div class="mb-4">
            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">设备类型</label>
            <select v-model="newEquipment.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 equipmentTypes" :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>
            <input type="text" v-model="newEquipment.name" 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="text" v-model="newEquipment.model" 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="newEquipment.departmentId" 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="dept in departments" :key="dept.id" :value="dept.id">{{ dept.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="newEquipment.managerId" 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="manager in managers" :key="manager.id" :value="manager.id">{{ manager.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="date" v-model="newEquipment.purchaseDate" 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="number" v-model="newEquipment.maintenanceInterval" 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="newEquipment.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="showAddEquipmentModal = 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="showAddMaintenanceModal" 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="addMaintenance">
          <div class="mb-4">
            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">维护类型</label>
            <select v-model="newMaintenance.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 maintenanceTypes" :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="newMaintenance.equipmentId" 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="equipment in equipments" :key="equipment.id" :value="equipment.id">{{ equipment.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="date" v-model="newMaintenance.planDate" 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="newMaintenance.managerId" 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="manager in managers" :key="manager.id" :value="manager.id">{{ manager.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="newMaintenance.content" 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>
            <textarea v-model="newMaintenance.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="showAddMaintenanceModal = 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-yellow-600 text-white rounded-md hover:bg-yellow-700">
              添加
            </button>
          </div>
        </form>
      </div>
    </div>
  </div>
</template>

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

// 设备数据
const equipments = ref([
  {
    id: 1,
    equipmentNo: 'EQ2024001',
    typeId: 1,
    typeName: '生产设备',
    name: '数控机床',
    model: 'CNC-001',
    departmentId: 1,
    departmentName: '生产部',
    managerId: 1,
    manager: '张三',
    purchaseDate: '2024-01-01',
    maintenanceInterval: 30,
    status: 1,
    lastMaintenance: '2024-01-15',
    nextMaintenance: '2024-02-15',
    remark: '主要生产设备'
  },
  {
    id: 2,
    equipmentNo: 'EQ2024002',
    typeId: 2,
    typeName: '检测设备',
    name: '三坐标测量仪',
    model: 'CMM-001',
    departmentId: 2,
    departmentName: '质检部',
    managerId: 2,
    manager: '李四',
    purchaseDate: '2024-01-05',
    maintenanceInterval: 15,
    status: 2,
    lastMaintenance: '2024-01-20',
    nextMaintenance: '2024-02-05',
    remark: '精密测量设备'
  }
])

// 维护计划数据
const maintenancePlans = ref([
  {
    id: 1,
    maintenanceNo: 'MP2024001',
    typeId: 1,
    typeName: '定期维护',
    equipmentId: 1,
    equipmentName: '数控机床',
    equipmentNo: 'EQ2024001',
    managerId: 1,
    manager: '张三',
    planDate: '2024-02-15',
    content: '定期保养和检查',
    status: 1,
    completionDate: null,
    remark: '按计划进行'
  },
  {
    id: 2,
    maintenanceNo: 'MP2024002',
    typeId: 2,
    typeName: '故障维修',
    equipmentId: 2,
    equipmentName: '三坐标测量仪',
    equipmentNo: 'EQ2024002',
    managerId: 2,
    manager: '李四',
    planDate: '2024-02-05',
    content: '更换传感器',
    status: 2,
    completionDate: '2024-02-06',
    remark: '已完成维修'
  }
])

// 设备类型
const equipmentTypes = ref([
  { id: 1, name: '生产设备' },
  { id: 2, name: '检测设备' },
  { id: 3, name: '辅助设备' },
  { id: 4, name: '其他设备' }
])

// 维护类型
const maintenanceTypes = 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 departments = ref([
  { id: 1, name: '生产部' },
  { id: 2, name: '质检部' },
  { id: 3, name: '维修部' },
  { id: 4, name: '其他部门' }
])

// 负责人数据
const managers = ref([
  { id: 1, name: '张三', position: '设备主管' },
  { id: 2, name: '李四', position: '维修主管' },
  { id: 3, name: '王五', position: '技术员' }
])

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

// 模态框状态
const showAddEquipmentModal = ref(false)
const showAddMaintenanceModal = ref(false)

// 新设备表单
const newEquipment = ref({
  typeId: '',
  name: '',
  model: '',
  departmentId: '',
  managerId: '',
  purchaseDate: '',
  maintenanceInterval: '',
  remark: ''
})

// 新维护计划表单
const newMaintenance = ref({
  typeId: '',
  equipmentId: '',
  planDate: '',
  managerId: '',
  content: '',
  remark: ''
})

// 计算属性
const filteredEquipment = computed(() => {
  try {
    return equipments.value.filter(equipment => {
      if (!equipment) return false
      
      const matchesSearch = !searchText.value || 
        (equipment.equipmentNo && equipment.equipmentNo.toLowerCase().includes(searchText.value.toLowerCase())) ||
        (equipment.name && equipment.name.toLowerCase().includes(searchText.value.toLowerCase()))
      const matchesType = !filters.value.type || equipment.typeId === filters.value.type
      const matchesStatus = !filters.value.status || equipment.status === filters.value.status
      const matchesDepartment = !filters.value.department || equipment.departmentId === filters.value.department
      return matchesSearch && matchesType && matchesStatus && matchesDepartment
    })
  } catch (error) {
    console.error('过滤设备时出错:', error)
    return []
  }
})

const filteredMaintenance = computed(() => {
  try {
    return maintenancePlans.value.filter(maintenance => {
      if (!maintenance) return false
      
      const matchesSearch = !searchText.value || 
        (maintenance.maintenanceNo && maintenance.maintenanceNo.toLowerCase().includes(searchText.value.toLowerCase())) ||
        (maintenance.equipmentName && maintenance.equipmentName.toLowerCase().includes(searchText.value.toLowerCase()))
      const matchesType = !filters.value.type || maintenance.typeId === filters.value.type
      const matchesStatus = !filters.value.status || maintenance.status === filters.value.status
      return matchesSearch && matchesType && matchesStatus
    })
  } catch (error) {
    console.error('过滤维护计划时出错:', error)
    return []
  }
})

const totalEquipment = computed(() => {
  return equipments.value.length || 0
})

const activeEquipment = computed(() => {
  return equipments.value.filter(equipment => equipment && equipment.status === 1).length || 0
})

const pendingMaintenance = computed(() => {
  return maintenancePlans.value.filter(maintenance => maintenance && maintenance.status === 1).length || 0
})

const maintenanceCompletionRate = computed(() => {
  if (!maintenancePlans.value.length) return 0
  const completedMaintenance = maintenancePlans.value.filter(maintenance => maintenance && maintenance.status === 2)
  return Math.round((completedMaintenance.length / maintenancePlans.value.length) * 100)
})

const faultyEquipment = computed(() => {
  return equipments.value.filter(equipment => equipment && equipment.status === 3).length || 0
})

const averageRepairTime = computed(() => {
  const completedMaintenance = maintenancePlans.value.filter(maintenance => maintenance && maintenance.status === 2)
  if (!completedMaintenance.length) return 0
  const totalDays = completedMaintenance.reduce((sum, maintenance) => {
    try {
      const planDate = maintenance.planDate ? new Date(maintenance.planDate) : new Date()
      const completionDate = maintenance.completionDate ? new Date(maintenance.completionDate) : new Date()
      return sum + Math.ceil((completionDate - planDate) / (1000 * 60 * 60 * 24))
    } catch (error) {
      console.error('计算修复时间时出错:', error)
      return sum
    }
  }, 0)
  return Math.round(totalDays / completedMaintenance.length)
})

const equipmentUtilization = computed(() => {
  // 这里假设有一个计算设备利用率的逻辑
  return 85
})

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

// 格式化日期
const formatDate = (date) => {
  try {
    if (!date) return '未知日期'
    const dateObj = new Date(date)
    if (isNaN(dateObj.getTime())) {
      return '无效日期'
    }
    return dateObj.toLocaleDateString('zh-CN')
  } catch (error) {
    console.error('日期格式化错误:', error)
    return '无效日期'
  }
}

// 获取状态名称
const getStatusName = (statusId) => {
  try {
    if (!statusId) return '未知状态'
    const status = statusTypes.value.find(s => s && s.id === statusId)
    return status ? status.name : '未知状态'
  } catch (error) {
    console.error('获取状态名称时出错:', error)
    return '未知状态'
  }
}

// 获取状态样式
const getStatusClass = (statusId) => {
  try {
    if (!statusId) return 'bg-gray-100 text-gray-800 dark:bg-gray-700 dark:text-gray-300'
    const classes = {
      1: 'bg-green-100 text-green-800 dark:bg-green-700 dark:text-green-300',
      2: 'bg-yellow-100 text-yellow-800 dark:bg-yellow-700 dark:text-yellow-300',
      3: 'bg-red-100 text-red-800 dark:bg-red-700 dark:text-red-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'
  } catch (error) {
    console.error('获取状态样式时出错:', error)
    return 'bg-gray-100 text-gray-800 dark:bg-gray-700 dark:text-gray-300'
  }
}

// 添加设备
const addEquipment = () => {
  try {
    if (!newEquipment.value.typeId || !newEquipment.value.name || !newEquipment.value.model || 
        !newEquipment.value.departmentId || !newEquipment.value.managerId || 
        !newEquipment.value.purchaseDate || !newEquipment.value.maintenanceInterval) {
      alert('请填写所有必填字段')
      return
    }

    const type = equipmentTypes.value.find(t => t && t.id === newEquipment.value.typeId)
    const department = departments.value.find(d => d && d.id === newEquipment.value.departmentId)
    const manager = managers.value.find(m => m && m.id === newEquipment.value.managerId)

    if (!type || !department || !manager) {
      alert('无效的选择')
      return
    }

    const equipment = {
      id: equipments.value.length + 1,
      equipmentNo: `EQ${new Date().getFullYear()}${String(equipments.value.length + 1).padStart(3, '0')}`,
      typeId: newEquipment.value.typeId,
      typeName: type.name,
      name: newEquipment.value.name,
      model: newEquipment.value.model,
      departmentId: newEquipment.value.departmentId,
      departmentName: department.name,
      managerId: newEquipment.value.managerId,
      manager: manager.name,
      purchaseDate: newEquipment.value.purchaseDate,
      maintenanceInterval: newEquipment.value.maintenanceInterval,
      status: 1,
      lastMaintenance: null,
      nextMaintenance: calculateNextMaintenance(newEquipment.value.purchaseDate, newEquipment.value.maintenanceInterval),
      remark: newEquipment.value.remark || ''
    }
    equipments.value.push(equipment)
    showAddEquipmentModal.value = false
    resetNewEquipment()
  } catch (error) {
    console.error('添加设备时出错:', error)
    alert('添加设备失败，请重试')
  }
}

// 计算下次维护日期
const calculateNextMaintenance = (purchaseDate, interval) => {
  try {
    if (!purchaseDate || !interval) return null
    const date = new Date(purchaseDate)
    date.setDate(date.getDate() + parseInt(interval))
    return date.toISOString().split('T')[0]
  } catch (error) {
    console.error('计算下次维护日期时出错:', error)
    return null
  }
}

// 重置新设备表单
const resetNewEquipment = () => {
  newEquipment.value = {
    typeId: '',
    name: '',
    model: '',
    departmentId: '',
    managerId: '',
    purchaseDate: '',
    maintenanceInterval: '',
    remark: ''
  }
}

// 添加维护计划
const addMaintenance = () => {
  try {
    if (!newMaintenance.value.typeId || !newMaintenance.value.equipmentId || 
        !newMaintenance.value.planDate || !newMaintenance.value.managerId || 
        !newMaintenance.value.content) {
      alert('请填写所有必填字段')
      return
    }

    const type = maintenanceTypes.value.find(t => t && t.id === newMaintenance.value.typeId)
    const equipment = equipments.value.find(e => e && e.id === newMaintenance.value.equipmentId)
    const manager = managers.value.find(m => m && m.id === newMaintenance.value.managerId)

    if (!type || !equipment || !manager) {
      alert('无效的选择')
      return
    }

    const maintenance = {
      id: maintenancePlans.value.length + 1,
      maintenanceNo: `MP${new Date().getFullYear()}${String(maintenancePlans.value.length + 1).padStart(3, '0')}`,
      typeId: newMaintenance.value.typeId,
      typeName: type.name,
      equipmentId: newMaintenance.value.equipmentId,
      equipmentName: equipment.name,
      equipmentNo: equipment.equipmentNo,
      managerId: newMaintenance.value.managerId,
      manager: manager.name,
      planDate: newMaintenance.value.planDate,
      content: newMaintenance.value.content,
      status: 1,
      completionDate: null,
      remark: newMaintenance.value.remark || ''
    }
    maintenancePlans.value.push(maintenance)
    showAddMaintenanceModal.value = false
    resetNewMaintenance()
  } catch (error) {
    console.error('添加维护计划时出错:', error)
    alert('添加维护计划失败，请重试')
  }
}

// 重置新维护计划表单
const resetNewMaintenance = () => {
  newMaintenance.value = {
    typeId: '',
    equipmentId: '',
    planDate: '',
    managerId: '',
    content: '',
    remark: ''
  }
}

// 查看设备
const viewEquipment = (equipment) => {
  // 实现查看设备逻辑
  console.log('查看设备:', equipment)
}

// 编辑设备
const editEquipment = (equipment) => {
  // 实现编辑设备逻辑
  console.log('编辑设备:', equipment)
}

// 删除设备
const deleteEquipment = (equipment) => {
  try {
    if (!equipment) return
    if (confirm(`确定要删除设备"${equipment.name || '未知设备'}"吗？`)) {
      const index = equipments.value.findIndex(e => e && e.id === equipment.id)
      if (index !== -1) {
        equipments.value.splice(index, 1)
      }
    }
  } catch (error) {
    console.error('删除设备时出错:', error)
    alert('删除设备失败，请重试')
  }
}

// 查看维护计划
const viewMaintenance = (maintenance) => {
  // 实现查看维护计划逻辑
  console.log('查看维护计划:', maintenance)
}

// 编辑维护计划
const editMaintenance = (maintenance) => {
  // 实现编辑维护计划逻辑
  console.log('编辑维护计划:', maintenance)
}

// 删除维护计划
const deleteMaintenance = (maintenance) => {
  try {
    if (!maintenance) return
    if (confirm(`确定要删除维护计划"${maintenance.maintenanceNo || '未知维护计划'}"吗？`)) {
      const index = maintenancePlans.value.findIndex(m => m && m.id === maintenance.id)
      if (index !== -1) {
        maintenancePlans.value.splice(index, 1)
      }
    }
  } catch (error) {
    console.error('删除维护计划时出错:', error)
    alert('删除维护计划失败，请重试')
  }
}
</script> 