writeln('开始更新船舶信息...'); try { // 查询需要更新的船舶 // 如果logistics_ship表有status字段,查询status为2的船舶 // 如果没有status字段,可以查询所有船舶或者根据其他条件筛选 $ships = $this->getShipsToUpdate(); if ($ships->isEmpty()) { $output->writeln('没有找到需要更新的船舶'); return self::SUCCESS; } $output->writeln("找到 {$ships->count()} 艘需要更新的船舶"); $successCount = 0; $errorCount = 0; foreach ($ships as $ship) { try { $output->write("正在更新船舶 {$ship->mmsi} (ID: {$ship->id})... "); // 获取船舶MMSI号,这里假设使用IMO作为MMSI $mmsi = $ship->mmsi; // 通过ShipService获取船舶最新信息 $shipInfo = ShipService::getShipInfo($mmsi); if (!$shipInfo['success']) { $output->writeln("失败: " . $shipInfo['message']); $errorCount++; continue; } $apiData = $shipInfo['data']['data'] ?? null; if (!$apiData) { $output->writeln("失败: API返回数据为空"); $errorCount++; continue; } // 保存当前船舶信息到历史表 $this->saveToHistory($ship); // 更新船舶信息 $updateData = $this->mapApiDataToShip($apiData); $ship->fill($updateData); $ship->save(); $output->writeln("成功"); $successCount++; // 添加延迟避免API请求过于频繁 sleep(1); } catch (\Exception $e) { $output->writeln("失败: " . $e->getMessage()); $errorCount++; Log::error("更新船舶信息失败", [ 'ship_id' => $ship->id, 'imo' => $ship->IMO, 'error' => $e->getMessage() ]); } } $output->writeln("更新完成!成功: {$successCount}, 失败: {$errorCount}"); } catch (\Exception $e) { $output->writeln("执行失败: " . $e->getMessage()); Log::error("船舶信息更新任务执行失败", [ 'error' => $e->getMessage(), 'trace' => $e->getTraceAsString() ]); return self::FAILURE; } return self::SUCCESS; } /** * 获取需要更新的船舶列表 * @return \Illuminate\Database\Eloquent\Collection */ private function getShipsToUpdate() { return LogisticsShip::where('status', 1)->get(); } /** * 保存船舶信息到历史表 * @param LogisticsShip $ship */ private function saveToHistory(LogisticsShip $ship): void { $historyData = $ship->toArray(); $historyData['ship_id'] = $ship->id; unset($historyData['id']); // 移除主键,让数据库自动生成 LogisticsShipHis::create($historyData); } /** * 将API数据映射到船舶表字段 * @param array $apiData * @return array */ private function mapApiDataToShip(array $apiData): array { return [ 'IMO' => $apiData['imo'] ?? '', 'call_sign' => $apiData['call_sign'] ?? '', 'ship_name' => $apiData['ship_name'] ?? '', 'ship_cnname' => $apiData['ship_cnname'] ?? '', 'wail' => $apiData['call_sign'] ?? '', 'dest' => $apiData['dest'] ?? '', 'length' => $apiData['length'] ?? '', 'width' => $apiData['width'] ?? '', 'lat' => $apiData['lat'] ?? '', 'lng' => $apiData['lng'] ?? '', 'eta_utc' => $apiData['eta_utc'] ?? null, 'last_time_utc' => $apiData['last_time_utc'] ?? null, 'updated_at' => date('Y-m-d H:i:s') ]; } }