service = $service; $this->oldStatus = $oldStatus; $this->newStatus = $newStatus; $this->reason = $reason; $this->changedAt = now(); $this->metadata = $metadata; } /** * 获取事件数据数组 * * @return array */ public function toArray(): array { return [ 'service_id' => $this->service->id, 'service_code' => $this->service->code, 'service_name' => $this->service->name, 'old_status' => $this->oldStatus->value, 'old_status_label' => $this->oldStatus->getLabel(), 'new_status' => $this->newStatus->value, 'new_status_label' => $this->newStatus->getLabel(), 'reason' => $this->reason, 'changed_at' => $this->changedAt->toISOString(), 'metadata' => $this->metadata, ]; } /** * 判断是否为严重状态变更 * * @return bool */ public function isCriticalChange(): bool { // 从正常状态变为错误状态 if ($this->oldStatus === SERVICE_STATUS::ACTIVE && in_array($this->newStatus, [SERVICE_STATUS::ERROR, SERVICE_STATUS::DISABLED])) { return true; } // 变为过期状态 if ($this->newStatus === SERVICE_STATUS::EXPIRED) { return true; } return false; } /** * 判断是否为恢复状态变更 * * @return bool */ public function isRecoveryChange(): bool { // 从错误状态恢复到正常状态 if (in_array($this->oldStatus, [SERVICE_STATUS::ERROR, SERVICE_STATUS::DISABLED, SERVICE_STATUS::MAINTENANCE]) && $this->newStatus === SERVICE_STATUS::ACTIVE) { return true; } return false; } /** * 获取告警级别 * * @return string */ public function getAlertLevel(): string { if ($this->isCriticalChange()) { return 'CRITICAL'; } if ($this->isRecoveryChange()) { return 'INFO'; } if ($this->newStatus === SERVICE_STATUS::MAINTENANCE) { return 'WARNING'; } return 'INFO'; } /** * 获取通知消息 * * @return string */ public function getNotificationMessage(): string { $serviceName = $this->service->name; $oldLabel = $this->oldStatus->getLabel(); $newLabel = $this->newStatus->getLabel(); $message = "第三方服务 [{$serviceName}] 状态从 [{$oldLabel}] 变更为 [{$newLabel}]"; if ($this->reason) { $message .= ",原因:{$this->reason}"; } return $message; } /** * 判断是否需要发送通知 * * @return bool */ public function shouldNotify(): bool { // 严重变更或恢复变更需要通知 return $this->isCriticalChange() || $this->isRecoveryChange(); } }