CropLogic.php 63 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680
  1. <?php
  2. namespace App\Module\Farm\Logics;
  3. use App\Module\Farm\Dtos\CropInfoDto;
  4. use App\Module\Farm\Dtos\HarvestResultDto;
  5. use App\Module\Farm\Enums\GROWTH_STAGE;
  6. use App\Module\Farm\Enums\LAND_STATUS;
  7. use App\Module\Farm\Events\CropGrowthStageChangedEvent;
  8. use App\Module\Farm\Events\CropHarvestedEvent;
  9. use App\Module\Farm\Events\CropPlantedEvent;
  10. use App\Module\Farm\Events\DisasterClearedEvent;
  11. use App\Module\Farm\Events\LandStatusChangedEvent;
  12. use App\Module\Farm\Models\FarmCrop;
  13. use App\Module\Farm\Models\FarmFruitGrowthCycle;
  14. use App\Module\Farm\Models\FarmHarvestLog;
  15. use App\Module\Farm\Models\FarmLand;
  16. use App\Module\Farm\Models\FarmSeed;
  17. use App\Module\Farm\Models\FarmSeedOutput;
  18. use App\Module\Farm\Models\FarmSowLog;
  19. use App\Module\Farm\Models\FarmCropLog;
  20. use App\Module\Game\Enums\REWARD_SOURCE_TYPE;
  21. use App\Module\GameItems\Services\ItemService;
  22. use Illuminate\Support\Facades\DB;
  23. use Illuminate\Support\Facades\Log;
  24. use UCore\Db\Helper;
  25. use UCore\Dto\Res;
  26. /**
  27. * 作物管理逻辑
  28. */
  29. class CropLogic
  30. {
  31. /**
  32. * 获取作物信息
  33. *
  34. * @param int $cropId
  35. * @return CropInfoDto|null
  36. */
  37. public function getCropInfo(int $cropId): ?CropInfoDto
  38. {
  39. try {
  40. $crop = FarmCrop::find($cropId);
  41. if (!$crop) {
  42. return null;
  43. }
  44. return CropInfoDto::fromModel($crop);
  45. } catch (\Exception $e) {
  46. Log::error('获取作物信息失败', [
  47. 'crop_id' => $cropId,
  48. 'error' => $e->getMessage(),
  49. 'trace' => $e->getTraceAsString()
  50. ]);
  51. throw $e; // 重新抛出异常
  52. }
  53. }
  54. /**
  55. * 获取土地上的作物信息
  56. *
  57. * @param int $landId
  58. * @return CropInfoDto|null
  59. */
  60. public function getCropByLandId(int $landId): ?CropInfoDto
  61. {
  62. try {
  63. $crop = FarmCrop::where('land_id', $landId)->first();
  64. if (!$crop) {
  65. return null;
  66. }
  67. return CropInfoDto::fromModel($crop);
  68. } catch (\Exception $e) {
  69. Log::error('获取土地作物信息失败', [
  70. 'land_id' => $landId,
  71. 'error' => $e->getMessage(),
  72. 'trace' => $e->getTraceAsString()
  73. ]);
  74. return null;
  75. }
  76. }
  77. /**
  78. * 种植作物
  79. *
  80. * @param int $userId
  81. * @param int $landId
  82. * @param int $itemId 种子物品ID
  83. * @return array|null 返回包含CropInfoDto和日志ID的数组,格式为['crop' => CropInfoDto, 'log_id' => int]
  84. * @throws \Exception
  85. */
  86. public function plantCrop(int $userId, int $landId, int $itemId): ?array
  87. {
  88. try {
  89. // 检查是否已开启事务
  90. Helper::check_tr();
  91. // 获取土地信息
  92. $land = FarmLand::where('id', $landId)
  93. ->where('user_id', $userId)
  94. ->first();
  95. if (!$land) {
  96. throw new \Exception('土地不存在');
  97. }
  98. // 检查土地状态
  99. if ($land->status !== LAND_STATUS::IDLE->value) {
  100. throw new \Exception('土地状态不允许种植');
  101. }
  102. // 检查是否已存在作物记录(重要:防止重复种植bug)
  103. $existingCrop = FarmCrop::where('land_id', $landId)->first();
  104. if ($existingCrop) {
  105. Log::warning('土地上已存在作物记录,无法种植新作物', [
  106. 'user_id' => $userId,
  107. 'land_id' => $landId,
  108. 'existing_crop_id' => $existingCrop->id,
  109. 'existing_crop_stage' => $existingCrop->growth_stage->value ?? $existingCrop->growth_stage,
  110. 'land_status' => $land->status
  111. ]);
  112. throw new \Exception('土地上已存在作物,请先清理后再种植');
  113. }
  114. // 根据物品ID获取种子配置信息
  115. $seed = FarmSeed::where('item_id', $itemId)->first();
  116. if (!$seed) {
  117. throw new \Exception('种子配置不存在');
  118. }
  119. $seedId = $seed->id;
  120. // 创建作物记录
  121. $crop = new FarmCrop();
  122. $crop->land_id = $landId;
  123. $crop->user_id = $userId;
  124. $crop->seed_id = $seedId;
  125. $crop->land_level = $land->land_type; // 记录种植时的土地等级
  126. $crop->plant_time = now();
  127. $crop->growth_stage = GROWTH_STAGE::SEED;
  128. $crop->stage_start_time = now(); // 设置当前阶段开始时间
  129. $crop->stage_end_time = now()->addSeconds($seed->seed_time);
  130. $crop->disasters = [];
  131. $crop->fertilized = false;
  132. $crop->last_disaster_check_time = now(); // 初始化灾害检查时间
  133. $crop->can_disaster = false; // 种子期不能产生灾害
  134. $crop->save();
  135. // 创建种植日志
  136. $sowLog = new FarmSowLog();
  137. $sowLog->user_id = $userId;
  138. $sowLog->land_id = $landId;
  139. $sowLog->crop_id = $crop->id;
  140. $sowLog->seed_id = $seedId;
  141. $sowLog->sow_time = now();
  142. $sowLog->save();
  143. // 更新土地状态
  144. $land->status = LAND_STATUS::PLANTING->value;
  145. $land->updateHasCrop();
  146. $land->save();
  147. // 触发作物种植事件
  148. event(new CropPlantedEvent($userId, $land, $crop));
  149. Log::info('作物种植成功', [
  150. 'user_id' => $userId,
  151. 'land_id' => $landId,
  152. 'seed_id' => $seedId,
  153. 'crop_id' => $crop->id,
  154. 'sow_log_id' => $sowLog->id
  155. ]);
  156. return [
  157. 'crop' => CropInfoDto::fromModel($crop),
  158. 'log_id' => $sowLog->id
  159. ];
  160. } catch (\Exception $e) {
  161. // 回滚事务
  162. DB::rollBack();
  163. Log::error('作物种植失败', [
  164. 'user_id' => $userId,
  165. 'land_id' => $landId,
  166. 'seed_id' => $seedId,
  167. 'error' => $e->getMessage(),
  168. 'trace' => $e->getTraceAsString()
  169. ]);
  170. return null;
  171. }
  172. }
  173. /**
  174. * 收获作物
  175. *
  176. * @param int $userId
  177. * @param int $landId
  178. * @return HarvestResultDto|null
  179. */
  180. public function harvestCrop(int $userId, int $landId): Res
  181. {
  182. try {
  183. // 事务检查
  184. Helper::check_tr();
  185. // 获取土地信息
  186. /**
  187. * @var FarmLand $land
  188. */
  189. $land = FarmLand::where('id', $landId)
  190. ->where('user_id', $userId)
  191. ->first();
  192. if (!$land) {
  193. throw new \Exception('土地不存在');
  194. }
  195. // 检查土地状态
  196. // if ($land->status !== LAND_STATUS::HARVESTABLE->value) {
  197. // throw new \Exception('土地状态不允许收获');
  198. // }
  199. // 获取作物信息
  200. $crop = FarmCrop::where('land_id', $landId)->lockForUpdate()->first();
  201. if (!$crop) {
  202. throw new \Exception('作物不存在');
  203. }
  204. // 检查作物生长阶段
  205. if ($crop->growth_stage !== GROWTH_STAGE::MATURE) {
  206. throw new \Exception('作物未成熟,不能收获');
  207. }
  208. // 获取种子信息
  209. $seed = $crop->seed;
  210. if (!$seed) {
  211. throw new \Exception('种子信息不存在');
  212. }
  213. // 严格验证:收获时必须有完整的产出数据
  214. if (!$crop->final_output_item_id) {
  215. Log::error('收获失败:作物没有确定的产出物品ID', [
  216. 'crop_id' => $crop->id,
  217. 'user_id' => $userId,
  218. 'seed_id' => $seed->id,
  219. 'growth_stage' => $crop->growth_stage->value
  220. ]);
  221. throw new \Exception("作物ID {$crop->id} 没有确定的产出物品ID,无法收获");
  222. }
  223. if (!$crop->final_output_amount) {
  224. Log::error('收获失败:作物没有确定的产量', [
  225. 'crop_id' => $crop->id,
  226. 'user_id' => $userId,
  227. 'seed_id' => $seed->id,
  228. 'growth_stage' => $crop->growth_stage->value,
  229. 'final_output_item_id' => $crop->final_output_item_id
  230. ]);
  231. throw new \Exception("作物ID {$crop->id} 没有确定的产量,无法收获");
  232. }
  233. // 使用成熟期确定的产量和产出物品
  234. $outputItemId = $crop->final_output_item_id;
  235. $outputAmount = $crop->final_output_amount;
  236. Log::info('使用成熟期确定的最终产量', [
  237. 'crop_id' => $crop->id,
  238. 'final_output_item_id' => $outputItemId,
  239. 'final_output_amount' => $outputAmount
  240. ]);
  241. // 创建收获记录
  242. $harvestLog = new FarmHarvestLog();
  243. $harvestLog->user_id = $userId;
  244. $harvestLog->land_id = $landId;
  245. $harvestLog->crop_id = $crop->id;
  246. $harvestLog->seed_id = $seed->id;
  247. $harvestLog->output_amount = $outputAmount;
  248. $harvestLog->harvest_time = now();
  249. $harvestLog->created_at = now();
  250. $harvestLog->save();
  251. // 收获后作物进入枯萎期,而不是直接删除
  252. $oldStage = $crop->growth_stage;
  253. $crop->growth_stage = GROWTH_STAGE::WITHERED;
  254. $crop->stage_start_time = now();
  255. $crop->stage_end_time = null; // 枯萎期没有结束时间
  256. $crop->fertilized = false; // 重置施肥状态
  257. $crop->save();
  258. // 更新土地状态为枯萎状态
  259. $land->status = LAND_STATUS::WITHERED->value;
  260. $land->updateHasCrop();
  261. $land->save();
  262. // 触发作物生长阶段变更事件(从成熟期到枯萎期)
  263. event(new CropGrowthStageChangedEvent($userId, $crop, $oldStage->value, GROWTH_STAGE::WITHERED->value));
  264. // 触发作物收获事件
  265. event(new CropHarvestedEvent($userId, $land, $crop, $harvestLog, $outputItemId, $outputAmount));
  266. Log::info('作物收获成功,进入枯萎期', [
  267. 'user_id' => $userId,
  268. 'land_id' => $landId,
  269. 'crop_id' => $crop->id,
  270. 'seed_id' => $seed->id,
  271. 'output_item_id' => $outputItemId,
  272. 'output_amount' => $outputAmount,
  273. 'harvest_log_id' => $harvestLog->id,
  274. 'old_stage' => $oldStage->value,
  275. 'new_stage' => GROWTH_STAGE::WITHERED->value,
  276. 'land_status' => LAND_STATUS::WITHERED->value
  277. ]);
  278. // 物品入包
  279. ItemService::addItem($userId, $outputItemId, $outputAmount, [
  280. 'source' => REWARD_SOURCE_TYPE::FARM_HARVEST->valueString(),
  281. 'source_type' => REWARD_SOURCE_TYPE::FARM_HARVEST->valueString(),
  282. 'source_id' => $harvestLog->id,
  283. 'FarmHarvestLog' => $harvestLog->id
  284. ]);
  285. // 记录收获事件
  286. FarmCropLog::logHarvested($userId, $landId, $crop->id, $seed->id, [
  287. 'item_id' => $outputItemId,
  288. 'amount' => $outputAmount,
  289. 'harvest_log_id' => $harvestLog->id,
  290. 'growth_stage' => GROWTH_STAGE::MATURE->value,
  291. 'land_type' => $crop->land_level,
  292. 'old_stage' => $oldStage->value,
  293. 'new_stage' => GROWTH_STAGE::WITHERED->value,
  294. 'land_status_before' => $land->status,
  295. 'land_status_after' => LAND_STATUS::WITHERED->value
  296. ]);
  297. return Res::success();
  298. } catch (\Exception $e) {
  299. // 回滚事务
  300. Log::error('作物收获失败', [
  301. 'user_id' => $userId,
  302. 'land_id' => $landId,
  303. 'error' => $e->getMessage(),
  304. 'trace' => $e->getTraceAsString()
  305. ]);
  306. return Res::error('');
  307. }
  308. }
  309. /**
  310. * 使用化肥(通过作物ID)
  311. *
  312. * @param int $cropId 作物ID
  313. * @param int $cropGrowthTime 减少的生长时间(秒)
  314. * @return Res
  315. */
  316. public function useFertilizerByCropId(int $cropId, int $cropGrowthTime): Res
  317. {
  318. try {
  319. Helper::check_tr();
  320. // 获取作物信息(防错误机制:确保作物存在)
  321. /**
  322. * @var FarmCrop $crop
  323. */
  324. $crop = FarmCrop::find($cropId);
  325. if (!$crop) {
  326. throw new \Exception('作物不存在');
  327. }
  328. // 防错误机制:基本状态检查,避免意外执行
  329. if ($crop->fertilized) {
  330. throw new \Exception('作物已施肥');
  331. }
  332. // 更新作物信息
  333. $crop->fertilized = true;
  334. // 根据 cropGrowthTime 参数减少当前阶段时间
  335. if ($crop->stage_end_time) {
  336. $currentTime = now();
  337. $endTime = $crop->stage_end_time;
  338. $remainingTime = $currentTime->diffInSeconds($endTime, false);
  339. if ($remainingTime > 0) {
  340. // 确保减少的时间不超过剩余时间
  341. $reducedTime = min($cropGrowthTime, $remainingTime);
  342. // 使用copy()方法创建副本,避免修改原始对象
  343. $newEndTime = $endTime->copy()->subSeconds($reducedTime);
  344. $crop->stage_end_time = $newEndTime;
  345. Log::info('化肥减少生长时间', [
  346. 'crop_id' => $crop->id,
  347. 'reduced_time' => $reducedTime,
  348. 'original_end_time' => $endTime->format('Y-m-d H:i:s'),
  349. 'new_end_time' => $crop->stage_end_time->format('Y-m-d H:i:s'),
  350. 'stage_start_time' => $crop->stage_start_time ? $crop->stage_start_time->format('Y-m-d H:i:s') : null
  351. ]);
  352. event(new CropGrowthStageChangedEvent($crop->user_id, $crop, $crop->growth_stage->value, $crop->growth_stage->value));
  353. } else {
  354. Log::warning('作物已经到达或超过结束时间,无法减少生长时间', [
  355. 'crop_id' => $crop->id,
  356. 'current_time' => $currentTime->format('Y-m-d H:i:s'),
  357. 'stage_end_time' => $endTime->format('Y-m-d H:i:s'),
  358. 'remaining_time' => $remainingTime
  359. ]);
  360. }
  361. }
  362. $crop->save();
  363. // 记录施肥事件日志
  364. \App\Module\Farm\Models\FarmCropLog::logFertilized(
  365. $crop->user_id,
  366. $crop->land_id,
  367. $crop->id,
  368. $crop->seed_id,
  369. [
  370. 'growth_stage' => $crop->growth_stage,
  371. 'land_type' => $crop->land->land_type ?? 1,
  372. 'crop_growth_time' => $cropGrowthTime,
  373. 'stage_end_time' => $crop->stage_end_time?->format('Y-m-d H:i:s'),
  374. 'fertilized_at' => now()->format('Y-m-d H:i:s'),
  375. ]
  376. );
  377. Log::info('使用化肥成功', [
  378. 'crop_id' => $crop->id,
  379. 'user_id' => $crop->user_id,
  380. 'land_id' => $crop->land_id,
  381. 'growth_stage' => $crop->growth_stage,
  382. 'stage_end_time' => $crop->stage_end_time
  383. ]);
  384. return Res::success('', [
  385. 'crop_id' => $crop->id,
  386. ]);
  387. } catch (\Exception $e) {
  388. Log::error('使用化肥失败', [
  389. 'crop_id' => $cropId,
  390. 'crop_growth_time' => $cropGrowthTime,
  391. 'error' => $e->getMessage(),
  392. 'trace' => $e->getTraceAsString()
  393. ]);
  394. return Res::error('使用化肥失败');
  395. }
  396. }
  397. /**
  398. * 使用化肥(通过土地ID,兼容旧接口)
  399. *
  400. * @param int $userId
  401. * @param int $landId
  402. * @param int $crop_growth_time
  403. * @return Res
  404. * @deprecated 建议使用 useFertilizerByCropId($cropId, $cropGrowthTime) 方法
  405. */
  406. public function useFertilizer(int $userId, int $landId, int $crop_growth_time): Res
  407. {
  408. try {
  409. Helper::check_tr();
  410. // 获取土地信息(防错误机制:确保土地存在)
  411. /**
  412. * @var FarmLand $land
  413. */
  414. $land = FarmLand::where('id', $landId)
  415. ->where('user_id', $userId)
  416. ->first();
  417. if (!$land) {
  418. throw new \Exception('土地不存在');
  419. }
  420. // 获取作物信息(防错误机制:确保作物存在)
  421. /**
  422. * @var FarmCrop $crop
  423. */
  424. $crop = FarmCrop::where('land_id', $landId)->first();
  425. if (!$crop) {
  426. throw new \Exception('作物不存在');
  427. }
  428. // 防错误机制:基本状态检查,避免意外执行
  429. // 不进行土地状态验证,只进行作物状态验证
  430. // if ($land->status !== LAND_STATUS::PLANTING->valueInt()) {
  431. // Log::warning('土地状态异常,但继续执行施肥', [
  432. // 'land_id' => $landId,
  433. // 'expected_status' => LAND_STATUS::PLANTING->valueInt(),
  434. // 'actual_status' => $land->status
  435. // ]);
  436. // }
  437. if ($crop->fertilized) {
  438. throw new \Exception('作物已施肥');
  439. }
  440. // 更新作物信息
  441. $crop->fertilized = true;
  442. // 根据 crop_growth_time 参数减少当前阶段时间
  443. if ($crop->stage_end_time) {
  444. $currentTime = now();
  445. $endTime = $crop->stage_end_time;
  446. $remainingTime = $currentTime->diffInSeconds($endTime, false);
  447. if ($remainingTime > 0) {
  448. // 确保减少的时间不超过剩余时间
  449. $reducedTime = min($crop_growth_time, $remainingTime);
  450. // 使用copy()方法创建副本,避免修改原始对象
  451. $newEndTime = $endTime->copy()->subSeconds($reducedTime);
  452. $crop->stage_end_time = $newEndTime;
  453. Log::info('化肥减少生长时间', [
  454. 'crop_id' => $crop->id,
  455. 'reduced_time' => $reducedTime,
  456. 'original_end_time' => $endTime->toDateTimeString(),
  457. 'new_end_time' => $crop->stage_end_time->toDateTimeString(),
  458. 'stage_start_time' => $crop->stage_start_time->toDateTimeString()
  459. ]);
  460. } else {
  461. Log::warning('作物已经到达或超过结束时间,无法减少生长时间', [
  462. 'crop_id' => $crop->id,
  463. 'current_time' => $currentTime->toDateTimeString(),
  464. 'stage_end_time' => $endTime->toDateTimeString(),
  465. 'remaining_time' => $remainingTime
  466. ]);
  467. }
  468. }
  469. $crop->save();
  470. Log::info('使用化肥成功', [
  471. 'user_id' => $userId,
  472. 'land_id' => $landId,
  473. 'crop_id' => $crop->id,
  474. 'growth_stage' => $crop->growth_stage,
  475. 'stage_end_time' => $crop->stage_end_time
  476. ]);
  477. return Res::success('', [
  478. 'crop_id' => $crop->id,
  479. ]);
  480. } catch (\Exception $e) {
  481. Log::error('使用化肥失败', [
  482. 'user_id' => $userId,
  483. 'land_id' => $landId,
  484. 'error' => $e->getMessage(),
  485. 'trace' => $e->getTraceAsString()
  486. ]);
  487. return Res::error('使用化肥失败');
  488. }
  489. }
  490. /**
  491. * 清理灾害
  492. *
  493. * @param int $userId
  494. * @param int $landId
  495. * @param int $disasterType
  496. * @return bool
  497. */
  498. public function clearDisaster(int $userId, int $landId, int $disasterType): bool
  499. {
  500. try {
  501. /**
  502. * @var FramLand $land
  503. */
  504. // 获取土地信息(使用锁定读取避免并发问题)
  505. $land = FarmLand::where('id', $landId)
  506. ->where('user_id', $userId)
  507. ->lockForUpdate()
  508. ->first();
  509. if (!$land) {
  510. throw new \Exception('土地不存在');
  511. }
  512. // 获取作物信息(使用锁定读取避免并发问题)
  513. $crop = FarmCrop::where('land_id', $landId)
  514. ->lockForUpdate()
  515. ->first();
  516. if (!$crop) {
  517. throw new \Exception('作物不存在');
  518. }
  519. // 检查灾害是否存在(优先检查作物中的灾害数据)
  520. $disasters = $crop->disasters ?? [];
  521. $disasterIndex = -1;
  522. $disasterInfo = null;
  523. foreach ($disasters as $index => $disaster) {
  524. if (($disaster['type'] ?? 0) == $disasterType && ($disaster['status'] ?? '') === 'active') {
  525. $disasterIndex = $index;
  526. $disasterInfo = $disaster;
  527. break;
  528. }
  529. }
  530. if ($disasterIndex === -1 || !$disasterInfo) {
  531. throw new \Exception('指定类型的灾害不存在');
  532. }
  533. // 记录土地状态信息(仅用于日志,不修改土地状态)
  534. Log::info('清理灾害时的土地状态', [
  535. 'user_id' => $userId,
  536. 'land_id' => $landId,
  537. 'land_status' => $land->status,
  538. 'crop_growth_stage' => $crop->growth_stage,
  539. 'disaster_type' => $disasterType,
  540. 'active_disasters_count' => count(array_filter($disasters, function($disaster) {
  541. return ($disaster['status'] ?? '') === 'active';
  542. }))
  543. ]);
  544. // 更新灾害状态
  545. $disasters[$disasterIndex]['status'] = 'cleared';
  546. $disasters[$disasterIndex]['cleared_at'] = now()->toDateTimeString();
  547. $crop->disasters = $disasters;
  548. // 检查是否还有其他活跃灾害
  549. $hasActiveDisaster = false;
  550. foreach ($disasters as $disaster) {
  551. if (($disaster['status'] ?? '') === 'active') {
  552. $hasActiveDisaster = true;
  553. break;
  554. }
  555. }
  556. // 如果没有其他活跃灾害,根据作物生长阶段更新土地状态
  557. $oldLandStatus = $land->status;
  558. if (!$hasActiveDisaster) {
  559. // 根据作物当前生长阶段设置土地状态
  560. if ($crop->growth_stage === GROWTH_STAGE::MATURE->value) {
  561. // 作物已成熟,土地状态为可收获
  562. $land->status = LAND_STATUS::HARVESTABLE->value;
  563. } elseif ($crop->growth_stage === GROWTH_STAGE::WITHERED->value) {
  564. // 作物已枯萎,土地状态为枯萎
  565. $land->status = LAND_STATUS::WITHERED->value;
  566. } else {
  567. // 其他阶段,土地状态为种植中
  568. $land->status = LAND_STATUS::PLANTING->value;
  569. }
  570. $land->updateHasCrop();
  571. }
  572. // 保存更改
  573. $crop->save();
  574. $land->save();
  575. // 如果土地状态发生了变化,触发土地状态变更事件
  576. if ($oldLandStatus !== $land->status) {
  577. event(new LandStatusChangedEvent($userId, $landId, $oldLandStatus, $land->status));
  578. }
  579. // 触发灾害清理事件
  580. event(new DisasterClearedEvent($userId, $crop, $disasterType, $disasterInfo));
  581. Log::info('灾害清理成功', [
  582. 'user_id' => $userId,
  583. 'land_id' => $landId,
  584. 'crop_id' => $crop->id,
  585. 'disaster_type' => $disasterType
  586. ]);
  587. // 记录灾害清除事件
  588. FarmCropLog::logDisasterCleared($userId, $landId, $crop->id, $crop->seed_id, [
  589. 'disaster_type' => $disasterType,
  590. 'disaster_info' => $disasterInfo,
  591. 'growth_stage' => $crop->growth_stage->value,
  592. 'land_type' => $crop->land_level,
  593. 'has_other_active_disasters' => $hasActiveDisaster,
  594. 'old_land_status' => $oldLandStatus,
  595. 'new_land_status' => $land->status,
  596. 'cleared_at' => now()->toDateTimeString()
  597. ]);
  598. return true;
  599. } catch (\Exception $e) {
  600. Log::error('灾害清理失败', [
  601. 'user_id' => $userId,
  602. 'land_id' => $landId,
  603. 'disaster_type' => $disasterType,
  604. 'error' => $e->getMessage(),
  605. 'trace' => $e->getTraceAsString()
  606. ]);
  607. return false;
  608. }
  609. }
  610. /**
  611. * 铲除作物
  612. *
  613. * @param int $userId
  614. * @param int $landId
  615. * @param int $toolItemId 使用的工具物品ID,0表示手动铲除
  616. * @return bool
  617. */
  618. public function removeCrop(int $userId, int $landId, int $toolItemId = 0): bool
  619. {
  620. try {
  621. // 检查是否已开启事务
  622. Helper::check_tr();
  623. // 获取土地信息
  624. /**
  625. * @var FarmLand $land
  626. */
  627. $land = FarmLand::where('id', $landId)
  628. ->where('user_id', $userId)
  629. ->first();
  630. if (!$land) {
  631. throw new \Exception('土地不存在');
  632. }
  633. // 检查土地状态
  634. if ($land->status === LAND_STATUS::IDLE->value) {
  635. throw new \Exception('土地上没有作物');
  636. }
  637. // 获取作物信息
  638. $crop = FarmCrop::where('land_id', $landId)->first();
  639. if (!$crop) {
  640. // 如果没有作物但土地状态不是空闲,修正土地状态
  641. $oldLandStatus = $land->status;
  642. $land->status = LAND_STATUS::IDLE->value;
  643. $land->updateHasCrop();
  644. $land->save();
  645. // 记录状态变更信息,由调用方处理事件触发
  646. Log::info('土地状态已修正', [
  647. 'user_id' => $userId,
  648. 'land_id' => $landId,
  649. 'old_status' => $oldLandStatus,
  650. 'new_status' => $land->status
  651. ]);
  652. return true;
  653. }
  654. // 记录旧状态
  655. $oldLandStatus = $land->status;
  656. // 记录铲除作物事件日志(在软删除之前记录,确保作物信息完整)
  657. FarmCropLog::logCropRemoved($userId, $landId, $crop->id, $crop->seed_id, [
  658. 'growth_stage' => $crop->growth_stage->value,
  659. 'land_type' => $crop->land_level,
  660. 'tool_item_id' => $toolItemId,
  661. 'removed_at' => now()->toDateTimeString(),
  662. 'soft_deleted' => true,
  663. 'old_land_status' => $oldLandStatus,
  664. 'new_land_status' => LAND_STATUS::IDLE->value,
  665. 'reason' => $toolItemId > 0 ? '使用工具铲除' : '用户手动铲除'
  666. ]);
  667. // 软删除作物记录(使用软删除保留数据用于审计)
  668. $crop->delete();
  669. // 更新土地状态
  670. $land->status = LAND_STATUS::IDLE->value;
  671. $land->updateHasCrop();
  672. $land->save();
  673. // 触发作物铲除事件(在事务内触发,确保数据一致性)
  674. event(new \App\Module\Farm\Events\CropRemovedEvent(
  675. $userId,
  676. $land,
  677. $crop,
  678. $toolItemId,
  679. $toolItemId > 0 ? '使用工具铲除' : '用户手动铲除',
  680. true
  681. ));
  682. Log::info('铲除作物成功(软删除)', [
  683. 'user_id' => $userId,
  684. 'land_id' => $landId,
  685. 'crop_id' => $crop->id,
  686. 'old_status' => $oldLandStatus,
  687. 'new_status' => $land->status,
  688. 'soft_deleted' => true
  689. ]);
  690. return true;
  691. } catch (\Exception $e) {
  692. Log::error('铲除作物失败', [
  693. 'user_id' => $userId,
  694. 'land_id' => $landId,
  695. 'error' => $e->getMessage(),
  696. 'trace' => $e->getTraceAsString()
  697. ]);
  698. throw $e; // 重新抛出异常,由调用方处理事务回滚
  699. }
  700. }
  701. /**
  702. * 强制删除作物(物理删除,谨慎使用)
  703. *
  704. * 此方法会永久删除作物记录,主要用于:
  705. * 1. 数据清理和维护
  706. * 2. 测试环境的数据重置
  707. * 3. 特殊的管理员操作
  708. *
  709. * @param int $userId 用户ID
  710. * @param int $landId 土地ID
  711. * @param string $reason 删除原因(用于日志记录)
  712. * @return bool
  713. * @throws \Exception
  714. */
  715. public function forceDeleteCrop(int $userId, int $landId, string $reason = '管理员操作'): bool
  716. {
  717. try {
  718. // 获取土地信息
  719. $land = FarmLand::find($landId);
  720. if (!$land) {
  721. throw new \Exception('土地不存在');
  722. }
  723. // 验证土地所有权
  724. if ($land->user_id !== $userId) {
  725. throw new \Exception('无权操作此土地');
  726. }
  727. // 获取作物信息(包括软删除的记录)
  728. $crop = FarmCrop::withTrashed()->where('land_id', $landId)->first();
  729. if (!$crop) {
  730. throw new \Exception('土地上没有作物');
  731. }
  732. // 记录旧状态
  733. $oldLandStatus = $land->status;
  734. $cropId = $crop->id;
  735. $wasSoftDeleted = $crop->trashed();
  736. // 强制删除作物记录(物理删除)
  737. $crop->forceDelete();
  738. // 更新土地状态
  739. $land->status = LAND_STATUS::IDLE->value;
  740. $land->updateHasCrop();
  741. $land->save();
  742. Log::warning('强制删除作物成功(物理删除)', [
  743. 'user_id' => $userId,
  744. 'land_id' => $landId,
  745. 'crop_id' => $cropId,
  746. 'old_status' => $oldLandStatus,
  747. 'new_status' => $land->status,
  748. 'was_soft_deleted' => $wasSoftDeleted,
  749. 'reason' => $reason,
  750. 'force_deleted' => true
  751. ]);
  752. return true;
  753. } catch (\Exception $e) {
  754. Log::error('强制删除作物失败', [
  755. 'user_id' => $userId,
  756. 'land_id' => $landId,
  757. 'reason' => $reason,
  758. 'error' => $e->getMessage(),
  759. 'trace' => $e->getTraceAsString()
  760. ]);
  761. throw $e;
  762. }
  763. }
  764. /**
  765. * 恢复软删除的作物
  766. *
  767. * @param int $userId 用户ID
  768. * @param int $landId 土地ID
  769. * @return bool
  770. * @throws \Exception
  771. */
  772. public function restoreCrop(int $userId, int $landId): bool
  773. {
  774. try {
  775. // 获取土地信息
  776. $land = FarmLand::find($landId);
  777. if (!$land) {
  778. throw new \Exception('土地不存在');
  779. }
  780. // 验证土地所有权
  781. if ($land->user_id !== $userId) {
  782. throw new \Exception('无权操作此土地');
  783. }
  784. // 检查土地上是否有活跃的作物
  785. $activeCrop = FarmCrop::where('land_id', $landId)->first();
  786. if ($activeCrop) {
  787. throw new \Exception('土地上已有活跃作物,无法恢复');
  788. }
  789. // 获取软删除的作物记录
  790. $crop = FarmCrop::onlyTrashed()->where('land_id', $landId)->first();
  791. if (!$crop) {
  792. throw new \Exception('没有找到可恢复的作物记录');
  793. }
  794. // 恢复作物记录
  795. $crop->restore();
  796. // 更新土地状态(根据作物的生长阶段)
  797. $newLandStatus = match($crop->growth_stage) {
  798. GROWTH_STAGE::WITHERED => LAND_STATUS::WITHERED,
  799. default => LAND_STATUS::PLANTING
  800. };
  801. $land->status = $newLandStatus->value;
  802. $land->updateHasCrop();
  803. $land->save();
  804. Log::info('恢复软删除作物成功', [
  805. 'user_id' => $userId,
  806. 'land_id' => $landId,
  807. 'crop_id' => $crop->id,
  808. 'crop_stage' => $crop->growth_stage->value,
  809. 'new_land_status' => $newLandStatus->value
  810. ]);
  811. return true;
  812. } catch (\Exception $e) {
  813. Log::error('恢复软删除作物失败', [
  814. 'user_id' => $userId,
  815. 'land_id' => $landId,
  816. 'error' => $e->getMessage(),
  817. 'trace' => $e->getTraceAsString()
  818. ]);
  819. throw $e;
  820. }
  821. }
  822. /**
  823. * 获取软删除的作物信息
  824. *
  825. * @param int $landId 土地ID
  826. * @return CropInfoDto|null
  827. */
  828. public function getTrashedCropByLandId(int $landId): ?CropInfoDto
  829. {
  830. try {
  831. // 获取软删除的作物记录
  832. $crop = FarmCrop::onlyTrashed()
  833. ->where('land_id', $landId)
  834. ->with(['seed', 'land', 'user'])
  835. ->first();
  836. if (!$crop) {
  837. return null;
  838. }
  839. return CropInfoDto::fromModel($crop);
  840. } catch (\Exception $e) {
  841. Log::error('获取软删除作物信息失败', [
  842. 'land_id' => $landId,
  843. 'error' => $e->getMessage(),
  844. 'trace' => $e->getTraceAsString()
  845. ]);
  846. return null;
  847. }
  848. }
  849. /**
  850. * 延时队列调用的作物状态更新方法
  851. *
  852. * @param array $params 包含crop_id、expected_stage等参数的数组
  853. * @return bool
  854. */
  855. public static function updateGrowthStageFromQueue(array $params): bool
  856. {
  857. try {
  858. $cropId = $params['crop_id'] ?? null;
  859. $expectedStage = $params['expected_stage'] ?? null;
  860. if (!$cropId) {
  861. Log::error('延时队列作物状态更新失败:缺少crop_id', $params);
  862. return false;
  863. }
  864. // 获取作物信息进行验证
  865. $crop = FarmCrop::find($cropId);
  866. if (!$crop) {
  867. Log::info('延时队列作物状态更新:作物不存在,可能已被删除', [
  868. 'crop_id' => $cropId
  869. ]);
  870. return true; // 作物已删除,任务完成
  871. }
  872. // 验证当前阶段是否符合预期(防止重复处理)
  873. if ($expectedStage && $crop->growth_stage->value !== $expectedStage) {
  874. Log::info('延时队列作物状态更新:作物状态已变化,跳过更新', [
  875. 'crop_id' => $cropId,
  876. 'expected_stage' => $expectedStage,
  877. 'actual_stage' => $crop->growth_stage->value
  878. ]);
  879. return true; // 状态已变化,可能已被其他任务处理
  880. }
  881. // 检查是否到达变更时间
  882. if ($crop->stage_end_time && now() < $crop->stage_end_time) {
  883. Log::info('延时队列作物状态更新:变更时间未到,跳过更新', [
  884. 'crop_id' => $cropId,
  885. 'stage_end_time' => $crop->stage_end_time->toDateTimeString(),
  886. 'current_time' => now()->toDateTimeString()
  887. ]);
  888. return true; // 时间未到,可能时间被修改了
  889. }
  890. // 执行状态更新
  891. $logic = new static();
  892. $result = $logic->updateGrowthStage($cropId);
  893. Log::info('延时队列作物状态更新完成', [
  894. 'crop_id' => $cropId,
  895. 'expected_stage' => $expectedStage,
  896. 'result' => $result
  897. ]);
  898. return $result;
  899. } catch (\Exception $e) {
  900. Log::error('延时队列作物状态更新失败', [
  901. 'params' => $params,
  902. 'error' => $e->getMessage(),
  903. 'trace' => $e->getTraceAsString()
  904. ]);
  905. return false;
  906. }
  907. }
  908. /**
  909. * 更新作物生长阶段
  910. *
  911. * @param int $cropId
  912. * @return bool
  913. */
  914. public function updateGrowthStage(int $cropId): bool
  915. {
  916. try {
  917. // 获取作物信息
  918. $crop = FarmCrop::find($cropId);
  919. if (!$crop) {
  920. throw new \Exception('作物不存在');
  921. }
  922. // 检查是否需要更新
  923. if (!$crop->stage_end_time || $crop->stage_end_time > now()) {
  924. return false;
  925. }
  926. // 获取当前生长阶段
  927. $oldStage = $crop->growth_stage;
  928. // 计算新的生长阶段
  929. $newStage = $this->calculateNextStage($crop);
  930. // 如果阶段没有变化,不需要更新
  931. if ($newStage === $oldStage) {
  932. return false;
  933. }
  934. // 如果进入发芽期,必须先确定最终产出果实ID(在计算阶段结束时间之前)
  935. if ($newStage === GROWTH_STAGE::SPROUT->value) {
  936. if (!$crop->final_output_item_id) {
  937. $seed = $crop->seed;
  938. // 如果是神秘种子,使用土地影响逻辑
  939. if ($seed && $seed->type == \App\Module\Farm\Enums\SEED_TYPE::MYSTERIOUS->value) {
  940. $land = $crop->land;
  941. $mysteryLogic = new \App\Module\Farm\Logics\MysterySeeLLogic();
  942. $selectedOutput = $mysteryLogic->selectFinalOutput($seed->id, $land->land_type);
  943. $crop->final_output_item_id = $selectedOutput['item_id'];
  944. Log::info('神秘种子确定最终产出(基于土地影响)', [
  945. 'crop_id' => $crop->id,
  946. 'user_id' => $crop->user_id,
  947. 'seed_id' => $seed->id,
  948. 'land_type' => $crop->land_level,
  949. 'final_output_item_id' => $selectedOutput['item_id']
  950. ]);
  951. // 记录确认果实种类事件
  952. FarmCropLog::logFruitConfirmed($crop->user_id, $crop->land_id, $crop->id, $seed->id, [
  953. 'final_output_item_id' => $selectedOutput['item_id'],
  954. 'growth_stage' => $newStage,
  955. 'land_type' => $crop->land_level,
  956. 'is_mystery_seed' => true,
  957. 'selected_output' => $selectedOutput,
  958. 'land_effect_applied' => true
  959. ]);
  960. } else {
  961. // 普通种子使用原有逻辑
  962. $outputInfo = $this->getRandomOutput($crop->seed_id);
  963. $crop->final_output_item_id = $outputInfo['item_id'];
  964. Log::info('作物进入发芽期,确定最终产出果实', [
  965. 'crop_id' => $crop->id,
  966. 'user_id' => $crop->user_id,
  967. 'seed_id' => $crop->seed_id,
  968. 'final_output_item_id' => $crop->final_output_item_id
  969. ]);
  970. // 记录确认果实种类事件
  971. FarmCropLog::logFruitConfirmed($crop->user_id, $crop->land_id, $crop->id, $seed->id, [
  972. 'final_output_item_id' => $outputInfo['item_id'],
  973. 'growth_stage' => $newStage,
  974. 'land_type' => $crop->land_level,
  975. 'is_mystery_seed' => false,
  976. 'output_info' => $outputInfo
  977. ]);
  978. }
  979. }
  980. }
  981. // 计算新阶段的结束时间(在确定final_output_item_id之后)
  982. $stageEndTime = $this->calculateStageEndTime($crop, $newStage);
  983. // 更新作物信息
  984. $crop->growth_stage = $newStage;
  985. $crop->stage_start_time = now(); // 设置新阶段的开始时间
  986. $crop->stage_end_time = $stageEndTime;
  987. $crop->fertilized = false; // 重置施肥状态
  988. // 验证:如果进入成熟期但没有final_output_item_id,这是一个严重错误
  989. if ($newStage === GROWTH_STAGE::MATURE->value && !$crop->final_output_item_id) {
  990. Log::error('严重错误:作物进入成熟期但没有确定最终产出果实ID', [
  991. 'crop_id' => $crop->id,
  992. 'user_id' => $crop->user_id,
  993. 'seed_id' => $crop->seed_id,
  994. 'current_stage' => $oldStage,
  995. 'new_stage' => $newStage
  996. ]);
  997. throw new \Exception("作物ID {$crop->id} 进入成熟期但没有确定最终产出果实ID,这是系统错误");
  998. }
  999. // 如果进入成熟期,计算并确定最终产量
  1000. if ($newStage === GROWTH_STAGE::MATURE->value && !$crop->final_output_amount) {
  1001. $finalAmount = $this->calculateMatureOutput($crop);
  1002. $crop->final_output_amount = $finalAmount;
  1003. Log::info('作物进入成熟期,确定最终产量', [
  1004. 'crop_id' => $crop->id,
  1005. 'user_id' => $crop->user_id,
  1006. 'seed_id' => $crop->seed_id,
  1007. 'final_output_amount' => $finalAmount,
  1008. 'final_output_item_id' => $crop->final_output_item_id
  1009. ]);
  1010. }
  1011. $crop->save();
  1012. // 如果进入枯萎期,需要更新土地状态
  1013. if ($newStage === GROWTH_STAGE::WITHERED->value) {
  1014. $land = $crop->land;
  1015. if ($land) {
  1016. $land->status = LAND_STATUS::WITHERED;
  1017. $land->updateHasCrop();
  1018. $land->save();
  1019. Log::info('作物进入枯萎期,更新土地状态', [
  1020. 'crop_id' => $crop->id,
  1021. 'land_id' => $land->id,
  1022. 'land_status' => LAND_STATUS::WITHERED->value
  1023. ]);
  1024. }
  1025. }
  1026. // 触发生长阶段变更事件
  1027. event(new CropGrowthStageChangedEvent($crop->user_id, $crop, $oldStage->value, $newStage));
  1028. Log::info('作物生长阶段更新成功', [
  1029. 'crop_id' => $cropId,
  1030. 'user_id' => $crop->user_id,
  1031. 'old_stage' => $oldStage,
  1032. 'new_stage' => $newStage,
  1033. 'stage_end_time' => $stageEndTime
  1034. ]);
  1035. return true;
  1036. } catch (\Exception $e) {
  1037. Log::error('作物生长阶段更新失败', [
  1038. 'crop_id' => $cropId,
  1039. 'error' => $e->getMessage(),
  1040. 'trace' => $e->getTraceAsString()
  1041. ]);
  1042. return false;
  1043. }
  1044. }
  1045. /**
  1046. * 计算下一个生长阶段
  1047. *
  1048. * @param FarmCrop $crop
  1049. * @return int
  1050. */
  1051. public function calculateNextStage(FarmCrop $crop): int
  1052. {
  1053. $currentStage = $crop->growth_stage;
  1054. // 如果当前是成熟期,检查是否应该进入枯萎期
  1055. $currentStageValue = is_object($currentStage) ? $currentStage->value : $currentStage;
  1056. if ($currentStageValue === GROWTH_STAGE::MATURE->value) {
  1057. // 如果成熟期已经超过结束时间,则进入枯萎期
  1058. if ($crop->stage_end_time && now() >= $crop->stage_end_time) {
  1059. return GROWTH_STAGE::WITHERED->value;
  1060. }
  1061. // 否则保持成熟期
  1062. return GROWTH_STAGE::MATURE->value;
  1063. }
  1064. // 使用阶段映射确定下一个阶段
  1065. // 按照protobuf中定义的数值顺序进行阶段转换:1 → 20 → 30 → 35 → 40 → 50
  1066. $stageMap = [
  1067. GROWTH_STAGE::SEED->value => GROWTH_STAGE::SPROUT->value, // 1 → 20
  1068. GROWTH_STAGE::SPROUT->value => GROWTH_STAGE::GROWTH->value, // 20 → 30
  1069. GROWTH_STAGE::GROWTH->value => GROWTH_STAGE::FRUIT->value, // 30 → 35 (新增果实期)
  1070. GROWTH_STAGE::FRUIT->value => GROWTH_STAGE::MATURE->value, // 35 → 40 (果实期到成熟期)
  1071. GROWTH_STAGE::MATURE->value => GROWTH_STAGE::WITHERED->value, // 40 → 50
  1072. GROWTH_STAGE::WITHERED->value => GROWTH_STAGE::WITHERED->value, // 50 → 50 (枯萎期保持不变)
  1073. ];
  1074. // 确保返回整数值
  1075. $currentStageValue = is_object($currentStage) ? $currentStage->value : $currentStage;
  1076. return $stageMap[$currentStageValue] ?? GROWTH_STAGE::WITHERED->value;
  1077. }
  1078. /**
  1079. * 计算阶段结束时间
  1080. *
  1081. * @param FarmCrop $crop
  1082. * @param int $stage
  1083. * @return \Carbon\Carbon|null
  1084. */
  1085. private function calculateStageEndTime(FarmCrop $crop, int $stage)
  1086. {
  1087. $seed = $crop->seed;
  1088. if (!$seed) {
  1089. return null;
  1090. }
  1091. $now = now();
  1092. // 种子期使用种子配置,其他阶段必须使用果实生长周期配置
  1093. if ($stage === GROWTH_STAGE::SEED->value) {
  1094. Log::info('使用种子期配置', [
  1095. 'crop_id' => $crop->id,
  1096. 'seed_time' => $seed->seed_time,
  1097. 'time_hours' => $seed->seed_time / 3600
  1098. ]);
  1099. return $now->addSeconds($seed->seed_time);
  1100. }
  1101. // 其他阶段必须有果实生长周期配置
  1102. $fruitGrowthCycle = null;
  1103. if ($crop->final_output_item_id) {
  1104. $fruitGrowthCycle = FarmFruitGrowthCycle::where('fruit_item_id', $crop->final_output_item_id)->first();
  1105. }
  1106. if (!$fruitGrowthCycle) {
  1107. Log::error('缺少果实生长周期配置', [
  1108. 'crop_id' => $crop->id,
  1109. 'stage' => $stage,
  1110. 'stage_name' => GROWTH_STAGE::getName($stage),
  1111. 'final_output_item_id' => $crop->final_output_item_id,
  1112. 'seed_id' => $seed->id,
  1113. 'seed_name' => $seed->name
  1114. ]);
  1115. throw new \Exception("作物ID {$crop->id} 缺少果实生长周期配置,无法计算阶段时间");
  1116. }
  1117. Log::info('计算阶段结束时间', [
  1118. 'crop_id' => $crop->id,
  1119. 'stage' => $stage,
  1120. 'stage_name' => GROWTH_STAGE::getName($stage),
  1121. 'final_output_item_id' => $crop->final_output_item_id,
  1122. 'fruit_item_id' => $fruitGrowthCycle->fruit_item_id,
  1123. 'seed_id' => $seed->id,
  1124. 'seed_name' => $seed->name
  1125. ]);
  1126. switch ($stage) {
  1127. case GROWTH_STAGE::SPROUT->value:
  1128. // 发芽期:使用果实生长周期配置
  1129. Log::info('使用发芽期配置', [
  1130. 'crop_id' => $crop->id,
  1131. 'sprout_time' => $fruitGrowthCycle->sprout_time,
  1132. 'time_hours' => $fruitGrowthCycle->sprout_time / 3600,
  1133. 'time_source' => '果实生长周期配置'
  1134. ]);
  1135. return $now->addSeconds($fruitGrowthCycle->sprout_time);
  1136. case GROWTH_STAGE::GROWTH->value:
  1137. // 生长期:使用果实生长周期配置
  1138. Log::info('使用生长期配置', [
  1139. 'crop_id' => $crop->id,
  1140. 'growth_time' => $fruitGrowthCycle->growth_time,
  1141. 'time_hours' => $fruitGrowthCycle->growth_time / 3600,
  1142. 'time_source' => '果实生长周期配置'
  1143. ]);
  1144. return $now->addSeconds($fruitGrowthCycle->growth_time);
  1145. case GROWTH_STAGE::FRUIT->value:
  1146. // 果实期:使用果实生长周期配置
  1147. Log::info('使用果实期配置', [
  1148. 'crop_id' => $crop->id,
  1149. 'fruit_time' => $fruitGrowthCycle->fruit_time,
  1150. 'time_hours' => $fruitGrowthCycle->fruit_time / 3600,
  1151. 'time_source' => '果实生长周期配置'
  1152. ]);
  1153. return $fruitGrowthCycle->fruit_time > 0 ? $now->addSeconds($fruitGrowthCycle->fruit_time) : null;
  1154. case GROWTH_STAGE::MATURE->value:
  1155. // 成熟期:使用果实生长周期配置
  1156. if ($fruitGrowthCycle->mature_time > 0) {
  1157. Log::info('使用成熟期配置', [
  1158. 'crop_id' => $crop->id,
  1159. 'mature_time' => $fruitGrowthCycle->mature_time,
  1160. 'time_hours' => $fruitGrowthCycle->mature_time / 3600,
  1161. 'time_source' => '果实生长周期配置'
  1162. ]);
  1163. return $now->addSeconds($fruitGrowthCycle->mature_time);
  1164. }
  1165. // 成熟期时间为0表示无时间限制
  1166. Log::info('成熟期无时间限制', ['crop_id' => $crop->id]);
  1167. return null;
  1168. case GROWTH_STAGE::WITHERED->value:
  1169. // 枯萎期:使用果实生长周期配置
  1170. if ($fruitGrowthCycle->wither_time > 0) {
  1171. Log::info('使用枯萎期配置', [
  1172. 'crop_id' => $crop->id,
  1173. 'wither_time' => $fruitGrowthCycle->wither_time,
  1174. 'time_hours' => $fruitGrowthCycle->wither_time / 3600,
  1175. 'time_source' => '果实生长周期配置'
  1176. ]);
  1177. return $now->addSeconds($fruitGrowthCycle->wither_time);
  1178. }
  1179. // 枯萎期时间为0表示无结束时间
  1180. Log::info('枯萎期无时间限制', ['crop_id' => $crop->id]);
  1181. return null;
  1182. default:
  1183. Log::warning('未知生长阶段', ['crop_id' => $crop->id, 'stage' => $stage]);
  1184. return null;
  1185. }
  1186. }
  1187. /**
  1188. * 获取随机产出
  1189. *
  1190. * @param int $seedId
  1191. * @return array
  1192. */
  1193. public function getRandomOutput(int $seedId): array
  1194. {
  1195. // 获取种子的所有产出配置
  1196. $outputs = FarmSeedOutput::where('seed_id', $seedId)->get();
  1197. if ($outputs->isEmpty()) {
  1198. // 如果没有产出配置,使用种子的默认产出
  1199. $seed = FarmSeed::find($seedId);
  1200. return [
  1201. 'item_id' => $seed->item_id,
  1202. 'min_amount' => $seed->min_output,
  1203. 'max_amount' => $seed->max_output,
  1204. ];
  1205. }
  1206. // 按概率排序
  1207. $outputs = $outputs->sortByDesc('probability');
  1208. // 获取默认产出
  1209. $defaultOutput = $outputs->firstWhere('is_default', true);
  1210. // 随机选择产出
  1211. $random = mt_rand(1, 100);
  1212. $cumulativeProbability = 0;
  1213. foreach ($outputs as $output) {
  1214. $cumulativeProbability += $output->probability;
  1215. if ($random <= $cumulativeProbability) {
  1216. return [
  1217. 'item_id' => $output->item_id,
  1218. 'min_amount' => $output->min_amount,
  1219. 'max_amount' => $output->max_amount,
  1220. ];
  1221. }
  1222. }
  1223. // 如果随机值超过了所有概率之和,使用默认产出
  1224. if ($defaultOutput) {
  1225. return [
  1226. 'item_id' => $defaultOutput->item_id,
  1227. 'min_amount' => $defaultOutput->min_amount,
  1228. 'max_amount' => $defaultOutput->max_amount,
  1229. ];
  1230. }
  1231. // 如果没有默认产出,使用第一个产出
  1232. $firstOutput = $outputs->first();
  1233. return [
  1234. 'item_id' => $firstOutput->item_id,
  1235. 'min_amount' => $firstOutput->min_amount,
  1236. 'max_amount' => $firstOutput->max_amount,
  1237. ];
  1238. }
  1239. /**
  1240. * 根据物品ID获取产出配置信息
  1241. *
  1242. * @param int $seedId
  1243. * @param int $itemId
  1244. * @return array
  1245. */
  1246. private function getOutputInfoByItemId(int $seedId, int $itemId): array
  1247. {
  1248. try {
  1249. // 获取种子的所有产出配置
  1250. $outputs = FarmSeedOutput::where('seed_id', $seedId)->get();
  1251. // 查找匹配的产出配置
  1252. $targetOutput = $outputs->firstWhere('item_id', $itemId);
  1253. if ($targetOutput) {
  1254. return [
  1255. 'item_id' => $targetOutput->item_id,
  1256. 'min_amount' => $targetOutput->min_amount,
  1257. 'max_amount' => $targetOutput->max_amount,
  1258. 'disaster_max_amount' => $targetOutput->disaster_max_amount ?? 2000,
  1259. 'disaster_min_amount' => $targetOutput->disaster_min_amount ?? 500,
  1260. ];
  1261. }
  1262. // 如果没有找到匹配的产出配置,使用种子的默认产出
  1263. $seed = FarmSeed::find($seedId);
  1264. if ($seed) {
  1265. return [
  1266. 'item_id' => $itemId, // 使用传入的物品ID
  1267. 'min_amount' => $seed->min_output,
  1268. 'max_amount' => $seed->max_output,
  1269. 'disaster_max_amount' => $seed->disaster_max_output ?? 2000,
  1270. 'disaster_min_amount' => $seed->disaster_min_output ?? 500,
  1271. ];
  1272. }
  1273. // 如果种子也不存在,返回默认值
  1274. Log::warning('种子不存在,使用默认产出配置', [
  1275. 'seed_id' => $seedId,
  1276. 'item_id' => $itemId
  1277. ]);
  1278. return [
  1279. 'item_id' => $targetOutput->item_id,
  1280. 'min_amount' => $targetOutput->min_amount,
  1281. 'max_amount' => $targetOutput->max_amount,
  1282. ];
  1283. } catch (\Exception $e) {
  1284. Log::error('获取产出配置信息失败', [
  1285. 'seed_id' => $seedId,
  1286. 'item_id' => $itemId,
  1287. 'error' => $e->getMessage()
  1288. ]);
  1289. // 发生错误时返回安全的默认值
  1290. return [
  1291. 'item_id' => $itemId,
  1292. 'min_amount' => 1,
  1293. 'max_amount' => 10,
  1294. 'disaster_max_amount' => 10,
  1295. ];
  1296. }
  1297. }
  1298. /**
  1299. * 计算成熟期产量
  1300. *
  1301. * 在作物进入成熟期时调用,计算并确定最终产量
  1302. *
  1303. * @param FarmCrop $crop 作物对象
  1304. * @return int 最终产量
  1305. */
  1306. public function calculateMatureOutput(FarmCrop $crop): int
  1307. {
  1308. try {
  1309. $land = $crop->land;
  1310. $seed = $crop->seed;
  1311. $farmUser = $crop->user;
  1312. // 1. 验证必须有产出物品ID
  1313. if (!$crop->final_output_item_id) {
  1314. Log::error('成熟期产量计算失败:作物没有确定的产出物品ID', [
  1315. 'crop_id' => $crop->id,
  1316. 'user_id' => $crop->user_id,
  1317. 'seed_id' => $seed->id,
  1318. 'growth_stage' => $crop->growth_stage->value
  1319. ]);
  1320. throw new \Exception("作物ID {$crop->id} 没有确定的产出物品ID,无法计算产量");
  1321. }
  1322. // 2. 获取基础产量(使用发芽期确定的产出配置)
  1323. $outputInfo = $this->getOutputInfoByItemId($seed->id, $crop->final_output_item_id);
  1324. // 检查是否有活跃灾害,只有活跃灾害才影响产量
  1325. $hasActiveDisaster = false;
  1326. if (!empty($crop->disasters)) {
  1327. foreach ($crop->disasters as $disaster) {
  1328. if (($disaster['status'] ?? '') === 'active') {
  1329. $hasActiveDisaster = true;
  1330. break;
  1331. }
  1332. }
  1333. }
  1334. $minBaseAmount = $outputInfo['min_amount'];
  1335. $maxBaseAmount = $outputInfo['max_amount'];
  1336. if ($hasActiveDisaster) {
  1337. // 有活跃灾害时,使用灾害时的产量区间
  1338. $disasterMinAmount = $outputInfo['disaster_min_amount'] ?? 500;
  1339. $disasterMaxAmount = $outputInfo['disaster_max_amount'] ?? 2000;
  1340. $minBaseAmount = $disasterMinAmount;
  1341. $maxBaseAmount = $disasterMaxAmount;
  1342. }
  1343. // 3. 计算基础产量(随机值)
  1344. $baseAmount = mt_rand($minBaseAmount, $maxBaseAmount);
  1345. // 3. 获取土地的产量加成(使用种植时记录的土地等级)
  1346. $landType = \App\Module\Farm\Models\FarmLandType::find($crop->land_level);
  1347. $landOutputBonus = $landType ? $landType->output_bonus : 0;
  1348. // 4. 获取房屋的产量加成
  1349. $houseConfig = $farmUser->houseConfig;
  1350. $houseOutputBonus = ($houseConfig->output_bonus ?? 0) / 100; // 将百分比值转换为小数
  1351. // 5. 检查是否有丰收之神加持
  1352. $hasHarvestBuff = $farmUser->buffs()
  1353. ->where('buff_type', \App\Module\Farm\Enums\BUFF_TYPE::HARVEST_GOD)
  1354. ->where('expire_time', '>', now())
  1355. ->exists();
  1356. // 6. 计算灾害减产(基础产量已经考虑了灾害影响,这里记录用于日志)
  1357. $disasterPenalty = 0;
  1358. if (!empty($crop->disasters)) {
  1359. $dJian = \App\Module\Farm\Services\DisasterService::getAllDisasters();
  1360. foreach ($crop->disasters as $disaster) {
  1361. if (($disaster['status'] ?? '') === 'active') {
  1362. // 递加减产比例(仅用于日志记录)
  1363. $disasterPenalty += $dJian[$disaster['type']] ?? 0.05; // 默认5%减产
  1364. }
  1365. }
  1366. }
  1367. // 7. 计算最终产量
  1368. $finalAmount = $baseAmount;
  1369. // 应用土地加成
  1370. $finalAmount = (int)($finalAmount * (1 + $landOutputBonus));
  1371. // 应用房屋加成
  1372. $finalAmount = (int)($finalAmount * (1 + $houseOutputBonus));
  1373. // 注意:灾害影响已经在基础产量计算时考虑,这里不再重复应用
  1374. // 如果有丰收之神加持,使用最大可能产量
  1375. if ($hasHarvestBuff) {
  1376. // 丰收之神加持时的最大产量也要考虑活跃灾害影响
  1377. $maxPossibleAmount = $hasActiveDisaster ?
  1378. ($outputInfo['disaster_max_amount'] ?? 2000) :
  1379. $outputInfo['max_amount'];
  1380. $maxPossibleAmount = (int)($maxPossibleAmount * (1 + $landOutputBonus));
  1381. $maxPossibleAmount = (int)($maxPossibleAmount * (1 + $houseOutputBonus));
  1382. $finalAmount = max($finalAmount, $maxPossibleAmount);
  1383. }
  1384. // 8. 应用产量限制
  1385. // 确保产量不超过全局最高产量
  1386. $globalMaxOutput = 3000;
  1387. $finalAmount = min($finalAmount, $globalMaxOutput);
  1388. // 如果有活跃灾害,确保产量不超过产出配置的灾害时最高产量(双重保险)
  1389. if ($hasActiveDisaster) {
  1390. $disasterMaxAmount = $outputInfo['disaster_max_amount'] ?? 2000;
  1391. $finalAmount = min($finalAmount, $disasterMaxAmount);
  1392. }
  1393. // 确保最小产量为1
  1394. $finalAmount = max(1, $finalAmount);
  1395. Log::info('成熟期产量计算完成', [
  1396. 'crop_id' => $crop->id,
  1397. 'user_id' => $crop->user_id,
  1398. 'seed_id' => $seed->id,
  1399. 'base_amount' => $baseAmount,
  1400. 'min_base_amount' => $minBaseAmount,
  1401. 'max_base_amount' => $maxBaseAmount,
  1402. 'final_amount' => $finalAmount,
  1403. 'land_bonus' => $landOutputBonus,
  1404. 'house_bonus' => $houseOutputBonus,
  1405. 'has_active_disaster' => $hasActiveDisaster,
  1406. 'disaster_penalty' => $disasterPenalty,
  1407. 'has_harvest_buff' => $hasHarvestBuff,
  1408. 'disaster_max_amount' => $outputInfo['disaster_max_amount'] ?? 2000,
  1409. 'global_max_output' => $globalMaxOutput,
  1410. 'final_output_item_id' => $crop->final_output_item_id
  1411. ]);
  1412. // 记录确认产出数量事件
  1413. FarmCropLog::logOutputCalculated($crop->user_id, $crop->land_id, $crop->id, $seed->id, [
  1414. 'base_amount' => $baseAmount,
  1415. 'final_amount' => $finalAmount,
  1416. 'land_bonus' => $landOutputBonus,
  1417. 'house_bonus' => $houseOutputBonus,
  1418. 'has_active_disaster' => $hasActiveDisaster,
  1419. 'disaster_penalty' => $disasterPenalty,
  1420. 'has_harvest_buff' => $hasHarvestBuff,
  1421. 'disaster_max_amount' => $outputInfo['disaster_max_amount'] ?? 2000,
  1422. 'global_max_output' => $globalMaxOutput,
  1423. 'growth_stage' => GROWTH_STAGE::MATURE->value,
  1424. 'land_type' => $crop->land_level,
  1425. 'final_output_item_id' => $crop->final_output_item_id
  1426. ]);
  1427. return $finalAmount;
  1428. } catch (\Exception $e) {
  1429. Log::error('成熟期产量计算失败', [
  1430. 'crop_id' => $crop->id,
  1431. 'user_id' => $crop->user_id,
  1432. 'error' => $e->getMessage(),
  1433. 'trace' => $e->getTraceAsString()
  1434. ]);
  1435. // 发生错误时返回种子的最小产量
  1436. return $crop->seed->min_output ?? 1;
  1437. }
  1438. }
  1439. }