// 维护记录示例数据
import { MaintenanceRecord, MaterialUsage } from '../types/machinery';
import { machineryStorage } from './machineryStorage';

/**
 * 初始化维护记录示例数据
 * 包含多种维护类型、配件使用、维护场景等
 */
export function initializeMaintenanceMockData() {
  // 检查是否已有数据（避免重复初始化）
  const allRecords = machineryStorage.getAllMaintenanceRecords();
  if (allRecords.length > 0) {
    return; // 已有数据
  }

  // 获取所有农机，为前3台农机创建维护记录
  const allMachinery = machineryStorage.getAllMachinery();
  if (allMachinery.length === 0) {
    return; // 没有农机，无法创建维护记录
  }

  const mockRecords: MaintenanceRecord[] = [];
  const now = new Date();

  // ==================== 农机1：约翰迪尔拖拉机维护记录 ====================
  if (allMachinery[0]) {
    const machinery1Id = allMachinery[0].id;

    // 1. 日常保养记录
    mockRecords.push({
      id: `maintenance-${Date.now()}-001`,
      machineryId: machinery1Id,
      type: '日常保养',
      startTime: new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000).toISOString(), // 7天前
      endTime: new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000 + 2 * 60 * 60 * 1000).toISOString(), // 持续2小时
      workHours: 2,
      nextMaintenanceTime: new Date(now.getTime() + 23 * 24 * 60 * 60 * 1000).toISOString(), // 23天后
      maintenanceItems: '更换机油、机油滤芯，检查空气滤芯，润滑各部位，检查轮胎气压，清洁设备外观',
      partsAndMaterials: [
        { materialId: 'material-oil-001', quantity: 15 }, // 液压油 15升
        { materialId: 'material-filter-001', quantity: 2 }, // 机油滤芯 2个
      ],
      cost: 850,
      technician: '李师傅',
      remarks: '定期保养，设备运行正常，无异常发现',
      createdAt: new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000).toISOString(),
      createdBy: '系统管理员',
    });

    // 2. 定期维护记录
    mockRecords.push({
      id: `maintenance-${Date.now()}-002`,
      machineryId: machinery1Id,
      type: '定期维护',
      startTime: new Date(now.getTime() - 45 * 24 * 60 * 60 * 1000).toISOString(), // 45天前
      endTime: new Date(now.getTime() - 45 * 24 * 60 * 60 * 1000 + 4 * 60 * 60 * 1000).toISOString(), // 持续4小时
      workHours: 4,
      nextMaintenanceTime: new Date(now.getTime() + 135 * 24 * 60 * 60 * 1000).toISOString(), // 135天后（半年维护）
      maintenanceItems: '更换空气滤芯、燃油滤芯，检查刹车系统，调整传动皮带，检查液压系统，校准作业深度传感器，全面检查电气系统',
      partsAndMaterials: [
        { materialId: 'material-filter-002', quantity: 1 }, // 空气滤芯 1个
        { materialId: 'material-filter-003', quantity: 1 }, // 燃油滤芯 1个
        { materialId: 'material-oil-001', quantity: 20 }, // 液压油 20升
        { materialId: 'material-parts-001', quantity: 2 }, // 传动皮带 2条
      ],
      cost: 2380,
      technician: '王工',
      remarks: '半年度定期维护，更换了老化的传动皮带，刹车系统调整正常，液压系统压力正常',
      createdAt: new Date(now.getTime() - 45 * 24 * 60 * 60 * 1000).toISOString(),
      createdBy: '系统管理员',
    });

    // 3. 故障维修记录
    mockRecords.push({
      id: `maintenance-${Date.now()}-003`,
      machineryId: machinery1Id,
      type: '故障维修',
      startTime: new Date(now.getTime() - 20 * 24 * 60 * 60 * 1000).toISOString(), // 20天前
      endTime: new Date(now.getTime() - 20 * 24 * 60 * 60 * 1000 + 6 * 60 * 60 * 1000).toISOString(), // 持续6小时
      workHours: 6,
      maintenanceItems: '修复液压系统漏油问题，更换损坏的油封和O型圈，检查并紧固各连接部位，清洗液压油箱，补充液压油',
      partsAndMaterials: [
        { materialId: 'material-parts-002', quantity: 3 }, // 油封 3个
        { materialId: 'material-parts-003', quantity: 5 }, // O型圈 5个
        { materialId: 'material-oil-001', quantity: 8 }, // 液压油 8升
      ],
      cost: 1560,
      technician: '李师傅、张技师',
      remarks: '发现液压油管接头处油封老化导致漏油，已更换新油封，测试正常。建议加强日常检查。',
      createdAt: new Date(now.getTime() - 20 * 24 * 60 * 60 * 1000).toISOString(),
      createdBy: '系统管理员',
    });

    // 4. 年检记录
    mockRecords.push({
      id: `maintenance-${Date.now()}-004`,
      machineryId: machinery1Id,
      type: '年检',
      startTime: new Date(now.getTime() - 90 * 24 * 60 * 60 * 1000).toISOString(), // 90天前
      endTime: new Date(now.getTime() - 90 * 24 * 60 * 60 * 1000 + 3 * 60 * 60 * 1000).toISOString(), // 持续3小时
      workHours: 3,
      nextMaintenanceTime: new Date(now.getTime() + 275 * 24 * 60 * 60 * 1000).toISOString(), // 275天后（下次年检）
      maintenanceItems: '年度安全检查，排放检测，噪音测试，制动性能测试，灯光系统检查，安全装置检查，更换易损件',
      partsAndMaterials: [
        { materialId: 'material-parts-004', quantity: 4 }, // 刹车片 4片
        { materialId: 'material-parts-005', quantity: 2 }, // 灯泡 2个
      ],
      cost: 1200,
      technician: '农机监理站-刘检验员',
      remarks: '年检合格，所有安全项目符合标准。建议更换刹车片，已现场更换。年检证书编号：AJ-2024-001',
      createdAt: new Date(now.getTime() - 90 * 24 * 60 * 60 * 1000).toISOString(),
      createdBy: '系统管理员',
    });
  }

  // ==================== 农机2：收割机维护记录 ====================
  if (allMachinery[1]) {
    const machinery2Id = allMachinery[1].id;

    // 1. 作业季前检修
    mockRecords.push({
      id: `maintenance-${Date.now()}-005`,
      machineryId: machinery2Id,
      type: '定期维护',
      startTime: new Date(now.getTime() - 60 * 24 * 60 * 60 * 1000).toISOString(), // 60天前
      endTime: new Date(now.getTime() - 60 * 24 * 60 * 60 * 1000 + 8 * 60 * 60 * 1000).toISOString(), // 持续8小时
      workHours: 8,
      nextMaintenanceTime: new Date(now.getTime() + 30 * 24 * 60 * 60 * 1000).toISOString(),
      maintenanceItems: '收获季节前全面检修：更换刀片组件，调整脱粒滚筒间隙，清理筛网，检查传动链条张紧度，润滑各轴承点，检查液压升降系统，更换磨损严重的传动带',
      partsAndMaterials: [
        { materialId: 'material-parts-006', quantity: 8 }, // 收割刀片 8片
        { materialId: 'material-parts-001', quantity: 3 }, // 传动皮带 3条
        { materialId: 'material-oil-002', quantity: 5 }, // 齿轮油 5升
        { materialId: 'material-parts-007', quantity: 1 }, // 传动链条 1条
      ],
      cost: 4200,
      technician: '赵师傅、孙师傅',
      remarks: '收获季节前全面检修，刀片已全部更换为新件，脱粒系统调整到最佳状态，试运行正常。',
      createdAt: new Date(now.getTime() - 60 * 24 * 60 * 60 * 1000).toISOString(),
      createdBy: '系统管理员',
    });

    // 2. 作业中故障抢修
    mockRecords.push({
      id: `maintenance-${Date.now()}-006`,
      machineryId: machinery2Id,
      type: '故障维修',
      startTime: new Date(now.getTime() - 30 * 24 * 60 * 60 * 1000).toISOString(), // 30天前
      endTime: new Date(now.getTime() - 30 * 24 * 60 * 60 * 1000 + 5 * 60 * 60 * 1000).toISOString(), // 持续5小时
      workHours: 5,
      maintenanceItems: '紧急抢修：更换损坏的传动轴承，修复电气线路短路问题，调整清粮风机，紧固松动的螺栓',
      partsAndMaterials: [
        { materialId: 'material-parts-008', quantity: 2 }, // 轴承 2个
        { materialId: 'material-parts-009', quantity: 10 }, // 电线 10米
        { materialId: 'material-parts-010', quantity: 20 }, // 螺栓螺母 20套
      ],
      cost: 1850,
      technician: '李师傅、王工（紧急出车）',
      remarks: '收割作业中突发故障，传动轴承损坏导致异响。现场紧急更换轴承，检查发现部分电气线路老化短路，一并处理。抢修后恢复作业。',
      createdAt: new Date(now.getTime() - 30 * 24 * 60 * 60 * 1000).toISOString(),
      createdBy: '系统管理员',
    });

    // 3. 作业季后保养
    mockRecords.push({
      id: `maintenance-${Date.now()}-007`,
      machineryId: machinery2Id,
      type: '日常保养',
      startTime: new Date(now.getTime() - 10 * 24 * 60 * 60 * 1000).toISOString(), // 10天前
      endTime: new Date(now.getTime() - 10 * 24 * 60 * 60 * 1000 + 4 * 60 * 60 * 1000).toISOString(), // 持续4小时
      workHours: 4,
      nextMaintenanceTime: new Date(now.getTime() + 20 * 24 * 60 * 60 * 1000).toISOString(),
      maintenanceItems: '收获季节后保养：全面清理机身杂物和积尘，更换机油和滤芯，检查所有润滑点，防锈处理，存放准备',
      partsAndMaterials: [
        { materialId: 'material-oil-003', quantity: 18 }, // 机油 18升
        { materialId: 'material-filter-001', quantity: 1 }, // 机油滤芯 1个
        { materialId: 'material-filter-002', quantity: 1 }, // 空气滤芯 1个
        { materialId: 'material-parts-011', quantity: 2 }, // 防锈剂 2瓶
      ],
      cost: 950,
      technician: '张师傅',
      remarks: '收获季节结束后的保养，设备已清洗干净，关键部位已涂抹防锈剂，准备入库存放。',
      createdAt: new Date(now.getTime() - 10 * 24 * 60 * 60 * 1000).toISOString(),
      createdBy: '系统管理员',
    });
  }

  // ==================== 农机3：播种机维护记录 ====================
  if (allMachinery[2]) {
    const machinery3Id = allMachinery[2].id;

    // 1. 播种前调试
    mockRecords.push({
      id: `maintenance-${Date.now()}-008`,
      machineryId: machinery3Id,
      type: '定期维护',
      startTime: new Date(now.getTime() - 50 * 24 * 60 * 60 * 1000).toISOString(), // 50天前
      endTime: new Date(now.getTime() - 50 * 24 * 60 * 60 * 1000 + 3 * 60 * 60 * 1000).toISOString(), // 持续3小时
      workHours: 3,
      nextMaintenanceTime: new Date(now.getTime() + 40 * 24 * 60 * 60 * 1000).toISOString(),
      maintenanceItems: '播种前调试：检查并调整排种器间距，校准播种深度，检查施肥装置，清洗种子箱，润滑传动部件，调整镇压轮',
      partsAndMaterials: [
        { materialId: 'material-parts-012', quantity: 6 }, // 排种轮 6个
        { materialId: 'material-oil-004', quantity: 3 }, // 润滑脂 3kg
      ],
      cost: 680,
      technician: '赵师傅',
      remarks: '播种前例行调试，排种器调整到最佳状态，播种深度校准完成，试播效果良好。',
      createdAt: new Date(now.getTime() - 50 * 24 * 60 * 60 * 1000).toISOString(),
      createdBy: '系统管理员',
    });

    // 2. 日常保养
    mockRecords.push({
      id: `maintenance-${Date.now()}-009`,
      machineryId: machinery3Id,
      type: '日常保养',
      startTime: new Date(now.getTime() - 15 * 24 * 60 * 60 * 1000).toISOString(), // 15天前
      endTime: new Date(now.getTime() - 15 * 24 * 60 * 60 * 1000 + 2 * 60 * 60 * 1000).toISOString(), // 持续2小时
      workHours: 2,
      nextMaintenanceTime: new Date(now.getTime() + 15 * 24 * 60 * 60 * 1000).toISOString(),
      maintenanceItems: '作业中保养：清理种子箱残留，检查排种器磨损情况，润滑各活动部件，紧固松动螺栓',
      partsAndMaterials: [
        { materialId: 'material-oil-004', quantity: 1 }, // 润滑脂 1kg
      ],
      cost: 150,
      technician: '李师傅',
      remarks: '播种作业中的日常保养，设备运行正常，无异常磨损。',
      createdAt: new Date(now.getTime() - 15 * 24 * 60 * 60 * 1000).toISOString(),
      createdBy: '系统管理员',
    });

    // 3. 小修记录
    mockRecords.push({
      id: `maintenance-${Date.now()}-010`,
      machineryId: machinery3Id,
      type: '故障维修',
      startTime: new Date(now.getTime() - 5 * 24 * 60 * 60 * 1000).toISOString(), // 5天前
      endTime: new Date(now.getTime() - 5 * 24 * 60 * 60 * 1000 + 1.5 * 60 * 60 * 1000).toISOString(), // 持续1.5小时
      workHours: 1.5,
      maintenanceItems: '更换磨损的开沟器刀片，调整施肥管道，修复堵塞的排种孔',
      partsAndMaterials: [
        { materialId: 'material-parts-013', quantity: 4 }, // 开沟器刀片 4个
      ],
      cost: 420,
      technician: '张师傅',
      remarks: '开沟器刀片磨损严重影响作业质量，现场更换新刀片，调整后播种深度一致性良好。',
      createdAt: new Date(now.getTime() - 5 * 24 * 60 * 60 * 1000).toISOString(),
      createdBy: '系统管理员',
    });
  }

  // ==================== 通用维护案例 ====================
  // 如果有更多农机，添加更多示例
  if (allMachinery[3]) {
    const machinery4Id = allMachinery[3].id;

    // 预防性维护示例
    mockRecords.push({
      id: `maintenance-${Date.now()}-011`,
      machineryId: machinery4Id,
      type: '定期维护',
      startTime: new Date(now.getTime() - 25 * 24 * 60 * 60 * 1000).toISOString(),
      endTime: new Date(now.getTime() - 25 * 24 * 60 * 60 * 1000 + 3 * 60 * 60 * 1000).toISOString(),
      workHours: 3,
      nextMaintenanceTime: new Date(now.getTime() + 65 * 24 * 60 * 60 * 1000).toISOString(),
      maintenanceItems: '预防性维护：全面检查关键部件，更换易损件，系统清洁，性能测试',
      partsAndMaterials: [
        { materialId: 'material-filter-001', quantity: 1 },
        { materialId: 'material-filter-002', quantity: 1 },
        { materialId: 'material-oil-001', quantity: 10 },
      ],
      cost: 1100,
      technician: '王工',
      remarks: '按照预防性维护计划执行，提前发现并处理了潜在故障点，确保设备可靠运行。',
      createdAt: new Date(now.getTime() - 25 * 24 * 60 * 60 * 1000).toISOString(),
      createdBy: '系统管理员',
    });
  }

  // 保存所有维护记录
  mockRecords.forEach(record => {
    machineryStorage.saveMaintenanceRecord(record);
  });

  console.log(`✅ 已初始化 ${mockRecords.length} 条维护记录示例数据`);
}

/**
 * 清除所有维护记录（仅用于测试）
 */
export function clearMaintenanceRecords() {
  localStorage.removeItem('smart_agriculture_machinery_maintenance');
  console.log('🗑️ 已清除所有维护记录');
}

/**
 * 获取维护记录统计信息
 */
export function getMaintenanceStatistics() {
  const records = machineryStorage.getAllMaintenanceRecords();
  
  const stats = {
    total: records.length,
    byType: {
      '日常保养': records.filter(r => r.type === '日常保养').length,
      '定期维护': records.filter(r => r.type === '定期维护').length,
      '故障维修': records.filter(r => r.type === '故障维修').length,
      '年检': records.filter(r => r.type === '年检').length,
    },
    totalCost: records.reduce((sum, r) => sum + r.cost, 0),
    totalWorkHours: records.reduce((sum, r) => sum + r.workHours, 0),
    avgCostPerRecord: records.length > 0 ? records.reduce((sum, r) => sum + r.cost, 0) / records.length : 0,
    recentRecords: records
      .sort((a, b) => new Date(b.startTime).getTime() - new Date(a.startTime).getTime())
      .slice(0, 5),
  };

  return stats;
}
