FarmLogCollector.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418
  1. <?php
  2. namespace App\Module\Game\Logics\UserLogCollectors;
  3. use App\Module\Farm\Models\FarmHarvestLog;
  4. use App\Module\Farm\Models\FarmUpgradeLog;
  5. /**
  6. * 农场日志收集器
  7. *
  8. * 收集农场相关日志表的新增记录,转换为用户友好的日志消息
  9. */
  10. class FarmLogCollector extends BaseLogCollector
  11. {
  12. /**
  13. * 源表名
  14. *
  15. * @var string
  16. */
  17. protected string $sourceTable = 'farm_harvest_logs';
  18. /**
  19. * 源类型
  20. *
  21. * @var string
  22. */
  23. protected string $sourceType = 'farm';
  24. /**
  25. * 获取新的记录
  26. *
  27. * @param int $lastProcessedId 上次处理的最大ID
  28. * @return \Illuminate\Database\Eloquent\Collection
  29. */
  30. protected function getNewRecords(int $lastProcessedId)
  31. {
  32. // 收集收获日志
  33. $harvestLogs = FarmHarvestLog::where('id', '>', $lastProcessedId)
  34. ->orderBy('id')
  35. ->limit($this->maxRecords / 2) // 分配一半给收获日志
  36. ->get()
  37. ->map(function ($log) {
  38. $log->log_type = 'harvest';
  39. return $log;
  40. });
  41. // 收集升级日志
  42. $upgradeLogs = FarmUpgradeLog::where('id', '>', $lastProcessedId)
  43. ->orderBy('id')
  44. ->limit($this->maxRecords / 2) // 分配一半给升级日志
  45. ->get()
  46. ->map(function ($log) {
  47. $log->log_type = 'upgrade';
  48. return $log;
  49. });
  50. // 合并并按ID排序
  51. return $harvestLogs->concat($upgradeLogs)->sortBy('id');
  52. }
  53. /**
  54. * 按时间获取新的记录
  55. *
  56. * @param int $lastProcessedTimestamp 上次处理的最大时间戳
  57. * @return \Illuminate\Database\Eloquent\Collection
  58. */
  59. protected function getNewRecordsByTime(int $lastProcessedTimestamp)
  60. {
  61. $lastTime = date('Y-m-d H:i:s', $lastProcessedTimestamp);
  62. // 收集收获日志
  63. $harvestLogs = FarmHarvestLog::where('created_at', '>', $lastTime)
  64. ->orderBy('created_at')
  65. ->orderBy('id')
  66. ->limit($this->maxRecords / 2) // 分配一半给收获日志
  67. ->get()
  68. ->map(function ($log) {
  69. $log->log_type = 'harvest';
  70. return $log;
  71. });
  72. // 收集升级日志
  73. $upgradeLogs = FarmUpgradeLog::where('created_at', '>', $lastTime)
  74. ->orderBy('created_at')
  75. ->orderBy('id')
  76. ->limit($this->maxRecords / 2) // 分配一半给升级日志
  77. ->get()
  78. ->map(function ($log) {
  79. $log->log_type = 'upgrade';
  80. return $log;
  81. });
  82. // 合并并按时间排序
  83. return $harvestLogs->concat($upgradeLogs)->sortBy(['created_at', 'id']);
  84. }
  85. /**
  86. * 获取记录的时间戳
  87. *
  88. * @param mixed $record 农场日志记录
  89. * @return int 时间戳
  90. */
  91. protected function getRecordTimestamp($record): int
  92. {
  93. return strtotime($record->created_at);
  94. }
  95. /**
  96. * 根据记录ID获取原始记录的时间戳
  97. * 由于农场收集器处理多个表,需要特殊处理
  98. *
  99. * @param int $recordId 记录ID
  100. * @return int 时间戳
  101. */
  102. protected function getOriginalRecordTimestamp(int $recordId): int
  103. {
  104. try {
  105. // 先尝试从收获日志表查找
  106. $harvestRecord = FarmHarvestLog::find($recordId);
  107. if ($harvestRecord) {
  108. return strtotime($harvestRecord->created_at);
  109. }
  110. // 再尝试从升级日志表查找
  111. $upgradeRecord = FarmUpgradeLog::find($recordId);
  112. if ($upgradeRecord) {
  113. return strtotime($upgradeRecord->created_at);
  114. }
  115. return 0;
  116. } catch (\Exception $e) {
  117. \Illuminate\Support\Facades\Log::error("获取农场日志原始时间戳失败", [
  118. 'record_id' => $recordId,
  119. 'error' => $e->getMessage()
  120. ]);
  121. return 0;
  122. }
  123. }
  124. /**
  125. * 转换记录为用户日志数据
  126. *
  127. * @param mixed $record 农场日志记录
  128. * @return array|null 用户日志数据,null表示跳过
  129. */
  130. protected function convertToUserLog($record): ?array
  131. {
  132. try {
  133. if ($record->log_type === 'harvest') {
  134. return $this->convertHarvestLog($record);
  135. } elseif ($record->log_type === 'upgrade') {
  136. return $this->convertUpgradeLog($record);
  137. }
  138. return null;
  139. } catch (\Exception $e) {
  140. \Illuminate\Support\Facades\Log::error("转换农场日志失败", [
  141. 'record_id' => $record->id,
  142. 'log_type' => $record->log_type ?? 'unknown',
  143. 'error' => $e->getMessage()
  144. ]);
  145. return null;
  146. }
  147. }
  148. /**
  149. * 转换收获日志
  150. *
  151. * @param FarmHarvestLog $record
  152. * @return array|null
  153. */
  154. private function convertHarvestLog(FarmHarvestLog $record): ?array
  155. {
  156. // 获取作物名称
  157. $cropName = $this->getCropName($record->seed_id);
  158. // 构建收获消息
  159. $message = "收获{$record->land_id}号土地的{$cropName}";
  160. // 添加收获数量信息
  161. if ($record->harvest_quantity > 0) {
  162. $message .= ",获得{$record->harvest_quantity}个";
  163. }
  164. // 添加经验信息
  165. if ($record->exp_gained > 0) {
  166. $message .= ",获得经验{$record->exp_gained}";
  167. }
  168. return $this->createUserLogData(
  169. $record->user_id,
  170. $message,
  171. $record->id,
  172. $record->created_at
  173. );
  174. }
  175. /**
  176. * 转换升级日志
  177. *
  178. * @param FarmUpgradeLog $record
  179. * @return array|null
  180. */
  181. private function convertUpgradeLog(FarmUpgradeLog $record): ?array
  182. {
  183. $message = $this->buildUpgradeMessage($record);
  184. return $this->createUserLogData(
  185. $record->user_id,
  186. $message,
  187. $record->id,
  188. $record->created_at
  189. );
  190. }
  191. /**
  192. * 构建升级消息
  193. *
  194. * @param FarmUpgradeLog $record
  195. * @return string
  196. */
  197. private function buildUpgradeMessage(FarmUpgradeLog $record): string
  198. {
  199. // 使用UPGRADE_TYPE枚举判断升级类型
  200. switch ($record->upgrade_type) {
  201. case \App\Module\Farm\Enums\UPGRADE_TYPE::HOUSE->value:
  202. return "房屋升级到{$record->new_level}级";
  203. case \App\Module\Farm\Enums\UPGRADE_TYPE::LAND->value:
  204. $oldLandType = $this->getLandTypeName($record->old_level);
  205. $newLandType = $this->getLandTypeName($record->new_level);
  206. return "土地{$record->target_id}从{$oldLandType}升级为{$newLandType}";
  207. default:
  208. return "升级类型{$record->upgrade_type}从{$record->old_level}级升级到{$record->new_level}级";
  209. }
  210. }
  211. /**
  212. * 获取作物名称
  213. *
  214. * @param int $seedId 种子ID
  215. * @return string
  216. */
  217. private function getCropName(int $seedId): string
  218. {
  219. try {
  220. // 尝试从配置中获取种子信息
  221. $seedConfig = \App\Module\Farm\Models\FarmSeed::find($seedId);
  222. if ($seedConfig) {
  223. return $seedConfig->name;
  224. }
  225. return "作物{$seedId}";
  226. } catch (\Exception $e) {
  227. return "作物{$seedId}";
  228. }
  229. }
  230. /**
  231. * 静态缓存:土地类型名称映射
  232. *
  233. * @var array|null
  234. */
  235. private static ?array $landTypeNames = null;
  236. /**
  237. * 获取土地类型名称
  238. *
  239. * @param int $typeId 土地类型ID
  240. * @return string
  241. */
  242. private function getLandTypeName(int $typeId): string
  243. {
  244. // 初始化静态缓存
  245. if (self::$landTypeNames === null) {
  246. $this->initLandTypeNamesCache();
  247. }
  248. return self::$landTypeNames[$typeId] ?? "未知土地类型{$typeId}";
  249. }
  250. /**
  251. * 初始化土地类型名称缓存
  252. *
  253. * @return void
  254. */
  255. private function initLandTypeNamesCache(): void
  256. {
  257. try {
  258. // 从数据库读取所有土地类型
  259. $landTypes = \App\Module\Farm\Models\FarmLandType::select('id', 'name')
  260. ->get()
  261. ->pluck('name', 'id')
  262. ->toArray();
  263. self::$landTypeNames = $landTypes;
  264. \Illuminate\Support\Facades\Log::info("土地类型缓存初始化完成", [
  265. 'count' => count($landTypes),
  266. 'types' => $landTypes
  267. ]);
  268. } catch (\Exception $e) {
  269. // 如果数据库查询失败,使用默认值
  270. self::$landTypeNames = [
  271. 1 => '普通土地',
  272. 2 => '红土地',
  273. 3 => '黑土地',
  274. 4 => '金色特殊土地',
  275. 5 => '蓝色特殊土地',
  276. 6 => '紫色特殊土地',
  277. ];
  278. \Illuminate\Support\Facades\Log::warning("土地类型缓存初始化失败,使用默认值", [
  279. 'error' => $e->getMessage(),
  280. 'default_types' => self::$landTypeNames
  281. ]);
  282. }
  283. }
  284. /**
  285. * 清除土地类型名称缓存(用于测试或数据更新后)
  286. *
  287. * @return void
  288. */
  289. public static function clearLandTypeNamesCache(): void
  290. {
  291. self::$landTypeNames = null;
  292. }
  293. /**
  294. * 格式化消耗物品信息
  295. *
  296. * @param mixed $costItems 消耗物品数据
  297. * @return string
  298. */
  299. private function formatCostItems($costItems): string
  300. {
  301. try {
  302. if (is_string($costItems)) {
  303. $costItems = json_decode($costItems, true);
  304. }
  305. if (!is_array($costItems)) {
  306. return '';
  307. }
  308. $costDesc = [];
  309. foreach ($costItems as $item) {
  310. if (isset($item['name']) && isset($item['quantity'])) {
  311. $costDesc[] = "{$item['name']} {$item['quantity']}";
  312. }
  313. }
  314. return implode('、', $costDesc);
  315. } catch (\Exception $e) {
  316. return '';
  317. }
  318. }
  319. /**
  320. * 是否应该记录此日志
  321. *
  322. * @param mixed $record
  323. * @return bool
  324. */
  325. private function shouldLogRecord($record): bool
  326. {
  327. // 对于收获日志,跳过收获数量为0的记录
  328. if ($record->log_type === 'harvest' && $record->harvest_quantity <= 0) {
  329. return false;
  330. }
  331. return true;
  332. }
  333. /**
  334. * 重写获取最后处理ID的方法,因为要处理多个表
  335. * 从user_logs表中查询农场相关的最后处理记录
  336. *
  337. * @return int
  338. */
  339. protected function getLastProcessedId(): int
  340. {
  341. try {
  342. // 查询农场相关的最后处理记录
  343. $lastLog = \App\Module\Game\Models\UserLog::where('source_type', $this->sourceType)
  344. ->whereIn('source_table', ['farm_harvest_logs', 'farm_upgrade_logs'])
  345. ->orderBy('source_id', 'desc')
  346. ->first();
  347. return $lastLog ? $lastLog->source_id : 0;
  348. } catch (\Exception $e) {
  349. \Illuminate\Support\Facades\Log::error("获取农场日志最后处理ID失败", [
  350. 'collector' => $this->collectorName,
  351. 'error' => $e->getMessage()
  352. ]);
  353. return 0;
  354. }
  355. }
  356. /**
  357. * 重写更新最后处理ID的方法
  358. * 不再需要手动更新,因为进度通过user_logs表自动追踪
  359. *
  360. * @param int $id
  361. * @return void
  362. */
  363. protected function updateLastProcessedId(int $id): void
  364. {
  365. // 不再需要手动更新,进度通过user_logs表自动追踪
  366. // 这个方法保留是为了兼容性
  367. }
  368. }