CropLogic.php 58 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572
  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. return null;
  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)->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. $land = FarmLand::where('id', $landId)
  503. ->where('user_id', $userId)
  504. ->lockForUpdate()
  505. ->first();
  506. if (!$land) {
  507. throw new \Exception('土地不存在');
  508. }
  509. // 获取作物信息(使用锁定读取避免并发问题)
  510. $crop = FarmCrop::where('land_id', $landId)
  511. ->lockForUpdate()
  512. ->first();
  513. if (!$crop) {
  514. throw new \Exception('作物不存在');
  515. }
  516. // 检查灾害是否存在(优先检查作物中的灾害数据)
  517. $disasters = $crop->disasters ?? [];
  518. $disasterIndex = -1;
  519. $disasterInfo = null;
  520. foreach ($disasters as $index => $disaster) {
  521. if (($disaster['type'] ?? 0) == $disasterType && ($disaster['status'] ?? '') === 'active') {
  522. $disasterIndex = $index;
  523. $disasterInfo = $disaster;
  524. break;
  525. }
  526. }
  527. if ($disasterIndex === -1 || !$disasterInfo) {
  528. throw new \Exception('指定类型的灾害不存在');
  529. }
  530. // 检查土地状态(移到灾害检查之后,因为作物数据更准确)
  531. if ($land->status !== LAND_STATUS::DISASTER->value) {
  532. // 如果土地状态不是灾害状态,但作物确实有活跃灾害,修正土地状态
  533. Log::warning('土地状态与作物灾害数据不一致,自动修正', [
  534. 'user_id' => $userId,
  535. 'land_id' => $landId,
  536. 'land_status' => $land->status,
  537. 'expected_status' => LAND_STATUS::DISASTER->value,
  538. 'active_disasters' => array_filter($disasters, function($disaster) {
  539. return ($disaster['status'] ?? '') === 'active';
  540. })
  541. ]);
  542. $land->status = LAND_STATUS::DISASTER->value;
  543. $land->save();
  544. }
  545. // 更新灾害状态
  546. $disasters[$disasterIndex]['status'] = 'cleared';
  547. $disasters[$disasterIndex]['cleared_at'] = now()->toDateTimeString();
  548. $crop->disasters = $disasters;
  549. // 检查是否还有其他活跃灾害
  550. $hasActiveDisaster = false;
  551. foreach ($disasters as $disaster) {
  552. if (($disaster['status'] ?? '') === 'active') {
  553. $hasActiveDisaster = true;
  554. break;
  555. }
  556. }
  557. // 如果没有其他活跃灾害,更新土地状态
  558. $oldLandStatus = $land->status;
  559. if (!$hasActiveDisaster) {
  560. $land->status = LAND_STATUS::PLANTING->value;
  561. $land->updateHasCrop();
  562. }
  563. // 保存更改
  564. $crop->save();
  565. $land->save();
  566. // 如果土地状态发生了变化,触发土地状态变更事件
  567. if ($oldLandStatus !== $land->status) {
  568. event(new LandStatusChangedEvent($userId, $landId, $oldLandStatus, $land->status));
  569. }
  570. // 触发灾害清理事件
  571. event(new DisasterClearedEvent($userId, $crop, $disasterType, $disasterInfo));
  572. Log::info('灾害清理成功', [
  573. 'user_id' => $userId,
  574. 'land_id' => $landId,
  575. 'crop_id' => $crop->id,
  576. 'disaster_type' => $disasterType
  577. ]);
  578. // 记录灾害清除事件
  579. FarmCropLog::logDisasterCleared($userId, $landId, $crop->id, $crop->seed_id, [
  580. 'disaster_type' => $disasterType,
  581. 'disaster_info' => $disasterInfo,
  582. 'growth_stage' => $crop->growth_stage->value,
  583. 'land_type' => $crop->land_level,
  584. 'has_other_active_disasters' => $hasActiveDisaster,
  585. 'old_land_status' => $oldLandStatus,
  586. 'new_land_status' => $land->status,
  587. 'cleared_at' => now()->toDateTimeString()
  588. ]);
  589. return true;
  590. } catch (\Exception $e) {
  591. Log::error('灾害清理失败', [
  592. 'user_id' => $userId,
  593. 'land_id' => $landId,
  594. 'disaster_type' => $disasterType,
  595. 'error' => $e->getMessage(),
  596. 'trace' => $e->getTraceAsString()
  597. ]);
  598. return false;
  599. }
  600. }
  601. /**
  602. * 铲除作物
  603. *
  604. * @param int $userId
  605. * @param int $landId
  606. * @return bool
  607. */
  608. public function removeCrop(int $userId, int $landId): bool
  609. {
  610. try {
  611. // 检查是否已开启事务
  612. Helper::check_tr();
  613. // 获取土地信息
  614. $land = FarmLand::where('id', $landId)
  615. ->where('user_id', $userId)
  616. ->first();
  617. if (!$land) {
  618. throw new \Exception('土地不存在');
  619. }
  620. // 检查土地状态
  621. if ($land->status === LAND_STATUS::IDLE->value) {
  622. throw new \Exception('土地上没有作物');
  623. }
  624. // 获取作物信息
  625. $crop = FarmCrop::where('land_id', $landId)->first();
  626. if (!$crop) {
  627. // 如果没有作物但土地状态不是空闲,修正土地状态
  628. $oldLandStatus = $land->status;
  629. $land->status = LAND_STATUS::IDLE->value;
  630. $land->updateHasCrop();
  631. $land->save();
  632. // 记录状态变更信息,由调用方处理事件触发
  633. Log::info('土地状态已修正', [
  634. 'user_id' => $userId,
  635. 'land_id' => $landId,
  636. 'old_status' => $oldLandStatus,
  637. 'new_status' => $land->status
  638. ]);
  639. return true;
  640. }
  641. // 软删除作物记录(使用软删除保留数据用于审计)
  642. $crop->delete();
  643. // 记录旧状态
  644. $oldLandStatus = $land->status;
  645. // 更新土地状态
  646. $land->status = LAND_STATUS::IDLE->value;
  647. $land->updateHasCrop();
  648. $land->save();
  649. // 记录状态变更信息,由调用方处理事件触发和事务提交
  650. Log::info('铲除作物成功(软删除)', [
  651. 'user_id' => $userId,
  652. 'land_id' => $landId,
  653. 'crop_id' => $crop->id,
  654. 'old_status' => $oldLandStatus,
  655. 'new_status' => $land->status,
  656. 'soft_deleted' => true
  657. ]);
  658. return true;
  659. } catch (\Exception $e) {
  660. Log::error('铲除作物失败', [
  661. 'user_id' => $userId,
  662. 'land_id' => $landId,
  663. 'error' => $e->getMessage(),
  664. 'trace' => $e->getTraceAsString()
  665. ]);
  666. throw $e; // 重新抛出异常,由调用方处理事务回滚
  667. }
  668. }
  669. /**
  670. * 强制删除作物(物理删除,谨慎使用)
  671. *
  672. * 此方法会永久删除作物记录,主要用于:
  673. * 1. 数据清理和维护
  674. * 2. 测试环境的数据重置
  675. * 3. 特殊的管理员操作
  676. *
  677. * @param int $userId 用户ID
  678. * @param int $landId 土地ID
  679. * @param string $reason 删除原因(用于日志记录)
  680. * @return bool
  681. * @throws \Exception
  682. */
  683. public function forceDeleteCrop(int $userId, int $landId, string $reason = '管理员操作'): bool
  684. {
  685. try {
  686. // 获取土地信息
  687. $land = FarmLand::find($landId);
  688. if (!$land) {
  689. throw new \Exception('土地不存在');
  690. }
  691. // 验证土地所有权
  692. if ($land->user_id !== $userId) {
  693. throw new \Exception('无权操作此土地');
  694. }
  695. // 获取作物信息(包括软删除的记录)
  696. $crop = FarmCrop::withTrashed()->where('land_id', $landId)->first();
  697. if (!$crop) {
  698. throw new \Exception('土地上没有作物');
  699. }
  700. // 记录旧状态
  701. $oldLandStatus = $land->status;
  702. $cropId = $crop->id;
  703. $wasSoftDeleted = $crop->trashed();
  704. // 强制删除作物记录(物理删除)
  705. $crop->forceDelete();
  706. // 更新土地状态
  707. $land->status = LAND_STATUS::IDLE->value;
  708. $land->updateHasCrop();
  709. $land->save();
  710. Log::warning('强制删除作物成功(物理删除)', [
  711. 'user_id' => $userId,
  712. 'land_id' => $landId,
  713. 'crop_id' => $cropId,
  714. 'old_status' => $oldLandStatus,
  715. 'new_status' => $land->status,
  716. 'was_soft_deleted' => $wasSoftDeleted,
  717. 'reason' => $reason,
  718. 'force_deleted' => true
  719. ]);
  720. return true;
  721. } catch (\Exception $e) {
  722. Log::error('强制删除作物失败', [
  723. 'user_id' => $userId,
  724. 'land_id' => $landId,
  725. 'reason' => $reason,
  726. 'error' => $e->getMessage(),
  727. 'trace' => $e->getTraceAsString()
  728. ]);
  729. throw $e;
  730. }
  731. }
  732. /**
  733. * 恢复软删除的作物
  734. *
  735. * @param int $userId 用户ID
  736. * @param int $landId 土地ID
  737. * @return bool
  738. * @throws \Exception
  739. */
  740. public function restoreCrop(int $userId, int $landId): bool
  741. {
  742. try {
  743. // 获取土地信息
  744. $land = FarmLand::find($landId);
  745. if (!$land) {
  746. throw new \Exception('土地不存在');
  747. }
  748. // 验证土地所有权
  749. if ($land->user_id !== $userId) {
  750. throw new \Exception('无权操作此土地');
  751. }
  752. // 检查土地上是否有活跃的作物
  753. $activeCrop = FarmCrop::where('land_id', $landId)->first();
  754. if ($activeCrop) {
  755. throw new \Exception('土地上已有活跃作物,无法恢复');
  756. }
  757. // 获取软删除的作物记录
  758. $crop = FarmCrop::onlyTrashed()->where('land_id', $landId)->first();
  759. if (!$crop) {
  760. throw new \Exception('没有找到可恢复的作物记录');
  761. }
  762. // 恢复作物记录
  763. $crop->restore();
  764. // 更新土地状态(根据作物的生长阶段)
  765. $newLandStatus = match($crop->growth_stage) {
  766. GROWTH_STAGE::WITHERED => LAND_STATUS::WITHERED,
  767. default => LAND_STATUS::PLANTING
  768. };
  769. $land->status = $newLandStatus->value;
  770. $land->updateHasCrop();
  771. $land->save();
  772. Log::info('恢复软删除作物成功', [
  773. 'user_id' => $userId,
  774. 'land_id' => $landId,
  775. 'crop_id' => $crop->id,
  776. 'crop_stage' => $crop->growth_stage->value,
  777. 'new_land_status' => $newLandStatus->value
  778. ]);
  779. return true;
  780. } catch (\Exception $e) {
  781. Log::error('恢复软删除作物失败', [
  782. 'user_id' => $userId,
  783. 'land_id' => $landId,
  784. 'error' => $e->getMessage(),
  785. 'trace' => $e->getTraceAsString()
  786. ]);
  787. throw $e;
  788. }
  789. }
  790. /**
  791. * 获取软删除的作物信息
  792. *
  793. * @param int $landId 土地ID
  794. * @return CropInfoDto|null
  795. */
  796. public function getTrashedCropByLandId(int $landId): ?CropInfoDto
  797. {
  798. try {
  799. // 获取软删除的作物记录
  800. $crop = FarmCrop::onlyTrashed()
  801. ->where('land_id', $landId)
  802. ->with(['seed', 'land', 'user'])
  803. ->first();
  804. if (!$crop) {
  805. return null;
  806. }
  807. return CropInfoDto::fromModel($crop);
  808. } catch (\Exception $e) {
  809. Log::error('获取软删除作物信息失败', [
  810. 'land_id' => $landId,
  811. 'error' => $e->getMessage(),
  812. 'trace' => $e->getTraceAsString()
  813. ]);
  814. return null;
  815. }
  816. }
  817. /**
  818. * 更新作物生长阶段
  819. *
  820. * @param int $cropId
  821. * @return bool
  822. */
  823. public function updateGrowthStage(int $cropId): bool
  824. {
  825. try {
  826. // 获取作物信息
  827. $crop = FarmCrop::find($cropId);
  828. if (!$crop) {
  829. throw new \Exception('作物不存在');
  830. }
  831. // 检查是否需要更新
  832. if (!$crop->stage_end_time || $crop->stage_end_time > now()) {
  833. return false;
  834. }
  835. // 获取当前生长阶段
  836. $oldStage = $crop->growth_stage;
  837. // 计算新的生长阶段
  838. $newStage = $this->calculateNextStage($crop);
  839. // 如果阶段没有变化,不需要更新
  840. if ($newStage === $oldStage) {
  841. return false;
  842. }
  843. // 如果进入发芽期,必须先确定最终产出果实ID(在计算阶段结束时间之前)
  844. if ($newStage === GROWTH_STAGE::SPROUT->value) {
  845. if (!$crop->final_output_item_id) {
  846. $seed = $crop->seed;
  847. // 如果是神秘种子,使用土地影响逻辑
  848. if ($seed && $seed->type == \App\Module\Farm\Enums\SEED_TYPE::MYSTERIOUS->value) {
  849. $land = $crop->land;
  850. $mysteryLogic = new \App\Module\Farm\Logics\MysterySeeLLogic();
  851. $selectedOutput = $mysteryLogic->selectFinalOutput($seed->id, $land->land_type);
  852. $crop->final_output_item_id = $selectedOutput['item_id'];
  853. Log::info('神秘种子确定最终产出(基于土地影响)', [
  854. 'crop_id' => $crop->id,
  855. 'user_id' => $crop->user_id,
  856. 'seed_id' => $seed->id,
  857. 'land_type' => $crop->land_level,
  858. 'final_output_item_id' => $selectedOutput['item_id']
  859. ]);
  860. // 记录确认果实种类事件
  861. FarmCropLog::logFruitConfirmed($crop->user_id, $crop->land_id, $crop->id, $seed->id, [
  862. 'final_output_item_id' => $selectedOutput['item_id'],
  863. 'growth_stage' => $newStage,
  864. 'land_type' => $crop->land_level,
  865. 'is_mystery_seed' => true,
  866. 'selected_output' => $selectedOutput,
  867. 'land_effect_applied' => true
  868. ]);
  869. } else {
  870. // 普通种子使用原有逻辑
  871. $outputInfo = $this->getRandomOutput($crop->seed_id);
  872. $crop->final_output_item_id = $outputInfo['item_id'];
  873. Log::info('作物进入发芽期,确定最终产出果实', [
  874. 'crop_id' => $crop->id,
  875. 'user_id' => $crop->user_id,
  876. 'seed_id' => $crop->seed_id,
  877. 'final_output_item_id' => $crop->final_output_item_id
  878. ]);
  879. // 记录确认果实种类事件
  880. FarmCropLog::logFruitConfirmed($crop->user_id, $crop->land_id, $crop->id, $seed->id, [
  881. 'final_output_item_id' => $outputInfo['item_id'],
  882. 'growth_stage' => $newStage,
  883. 'land_type' => $crop->land_level,
  884. 'is_mystery_seed' => false,
  885. 'output_info' => $outputInfo
  886. ]);
  887. }
  888. }
  889. }
  890. // 计算新阶段的结束时间(在确定final_output_item_id之后)
  891. $stageEndTime = $this->calculateStageEndTime($crop, $newStage);
  892. // 更新作物信息
  893. $crop->growth_stage = $newStage;
  894. $crop->stage_start_time = now(); // 设置新阶段的开始时间
  895. $crop->stage_end_time = $stageEndTime;
  896. $crop->fertilized = false; // 重置施肥状态
  897. // 验证:如果进入成熟期但没有final_output_item_id,这是一个严重错误
  898. if ($newStage === GROWTH_STAGE::MATURE->value && !$crop->final_output_item_id) {
  899. Log::error('严重错误:作物进入成熟期但没有确定最终产出果实ID', [
  900. 'crop_id' => $crop->id,
  901. 'user_id' => $crop->user_id,
  902. 'seed_id' => $crop->seed_id,
  903. 'current_stage' => $oldStage,
  904. 'new_stage' => $newStage
  905. ]);
  906. throw new \Exception("作物ID {$crop->id} 进入成熟期但没有确定最终产出果实ID,这是系统错误");
  907. }
  908. // 如果进入成熟期,计算并确定最终产量
  909. if ($newStage === GROWTH_STAGE::MATURE->value && !$crop->final_output_amount) {
  910. $finalAmount = $this->calculateMatureOutput($crop);
  911. $crop->final_output_amount = $finalAmount;
  912. Log::info('作物进入成熟期,确定最终产量', [
  913. 'crop_id' => $crop->id,
  914. 'user_id' => $crop->user_id,
  915. 'seed_id' => $crop->seed_id,
  916. 'final_output_amount' => $finalAmount,
  917. 'final_output_item_id' => $crop->final_output_item_id
  918. ]);
  919. }
  920. $crop->save();
  921. // 如果进入枯萎期,需要更新土地状态
  922. if ($newStage === GROWTH_STAGE::WITHERED->value) {
  923. $land = $crop->land;
  924. if ($land) {
  925. $land->status = LAND_STATUS::WITHERED;
  926. $land->updateHasCrop();
  927. $land->save();
  928. Log::info('作物进入枯萎期,更新土地状态', [
  929. 'crop_id' => $crop->id,
  930. 'land_id' => $land->id,
  931. 'land_status' => LAND_STATUS::WITHERED->value
  932. ]);
  933. }
  934. }
  935. // 触发生长阶段变更事件
  936. event(new CropGrowthStageChangedEvent($crop->user_id, $crop, $oldStage->value, $newStage));
  937. Log::info('作物生长阶段更新成功', [
  938. 'crop_id' => $cropId,
  939. 'user_id' => $crop->user_id,
  940. 'old_stage' => $oldStage,
  941. 'new_stage' => $newStage,
  942. 'stage_end_time' => $stageEndTime
  943. ]);
  944. return true;
  945. } catch (\Exception $e) {
  946. Log::error('作物生长阶段更新失败', [
  947. 'crop_id' => $cropId,
  948. 'error' => $e->getMessage(),
  949. 'trace' => $e->getTraceAsString()
  950. ]);
  951. return false;
  952. }
  953. }
  954. /**
  955. * 计算下一个生长阶段
  956. *
  957. * @param FarmCrop $crop
  958. * @return int
  959. */
  960. public function calculateNextStage(FarmCrop $crop): int
  961. {
  962. $currentStage = $crop->growth_stage;
  963. // 如果当前是成熟期,检查是否应该进入枯萎期
  964. $currentStageValue = is_object($currentStage) ? $currentStage->value : $currentStage;
  965. if ($currentStageValue === GROWTH_STAGE::MATURE->value) {
  966. // 如果成熟期已经超过结束时间,则进入枯萎期
  967. if ($crop->stage_end_time && now() >= $crop->stage_end_time) {
  968. return GROWTH_STAGE::WITHERED->value;
  969. }
  970. // 否则保持成熟期
  971. return GROWTH_STAGE::MATURE->value;
  972. }
  973. // 使用阶段映射确定下一个阶段
  974. // 按照protobuf中定义的数值顺序进行阶段转换:1 → 20 → 30 → 35 → 40 → 50
  975. $stageMap = [
  976. GROWTH_STAGE::SEED->value => GROWTH_STAGE::SPROUT->value, // 1 → 20
  977. GROWTH_STAGE::SPROUT->value => GROWTH_STAGE::GROWTH->value, // 20 → 30
  978. GROWTH_STAGE::GROWTH->value => GROWTH_STAGE::FRUIT->value, // 30 → 35 (新增果实期)
  979. GROWTH_STAGE::FRUIT->value => GROWTH_STAGE::MATURE->value, // 35 → 40 (果实期到成熟期)
  980. GROWTH_STAGE::MATURE->value => GROWTH_STAGE::WITHERED->value, // 40 → 50
  981. GROWTH_STAGE::WITHERED->value => GROWTH_STAGE::WITHERED->value, // 50 → 50 (枯萎期保持不变)
  982. ];
  983. // 确保返回整数值
  984. $currentStageValue = is_object($currentStage) ? $currentStage->value : $currentStage;
  985. return $stageMap[$currentStageValue] ?? GROWTH_STAGE::WITHERED->value;
  986. }
  987. /**
  988. * 计算阶段结束时间
  989. *
  990. * @param FarmCrop $crop
  991. * @param int $stage
  992. * @return \Carbon\Carbon|null
  993. */
  994. private function calculateStageEndTime(FarmCrop $crop, int $stage)
  995. {
  996. $seed = $crop->seed;
  997. if (!$seed) {
  998. return null;
  999. }
  1000. $now = now();
  1001. // 种子期使用种子配置,其他阶段必须使用果实生长周期配置
  1002. if ($stage === GROWTH_STAGE::SEED->value) {
  1003. Log::info('使用种子期配置', [
  1004. 'crop_id' => $crop->id,
  1005. 'seed_time' => $seed->seed_time,
  1006. 'time_hours' => $seed->seed_time / 3600
  1007. ]);
  1008. return $now->addSeconds($seed->seed_time);
  1009. }
  1010. // 其他阶段必须有果实生长周期配置
  1011. $fruitGrowthCycle = null;
  1012. if ($crop->final_output_item_id) {
  1013. $fruitGrowthCycle = FarmFruitGrowthCycle::where('fruit_item_id', $crop->final_output_item_id)->first();
  1014. }
  1015. if (!$fruitGrowthCycle) {
  1016. Log::error('缺少果实生长周期配置', [
  1017. 'crop_id' => $crop->id,
  1018. 'stage' => $stage,
  1019. 'stage_name' => GROWTH_STAGE::getName($stage),
  1020. 'final_output_item_id' => $crop->final_output_item_id,
  1021. 'seed_id' => $seed->id,
  1022. 'seed_name' => $seed->name
  1023. ]);
  1024. throw new \Exception("作物ID {$crop->id} 缺少果实生长周期配置,无法计算阶段时间");
  1025. }
  1026. Log::info('计算阶段结束时间', [
  1027. 'crop_id' => $crop->id,
  1028. 'stage' => $stage,
  1029. 'stage_name' => GROWTH_STAGE::getName($stage),
  1030. 'final_output_item_id' => $crop->final_output_item_id,
  1031. 'fruit_item_id' => $fruitGrowthCycle->fruit_item_id,
  1032. 'seed_id' => $seed->id,
  1033. 'seed_name' => $seed->name
  1034. ]);
  1035. switch ($stage) {
  1036. case GROWTH_STAGE::SPROUT->value:
  1037. // 发芽期:使用果实生长周期配置
  1038. Log::info('使用发芽期配置', [
  1039. 'crop_id' => $crop->id,
  1040. 'sprout_time' => $fruitGrowthCycle->sprout_time,
  1041. 'time_hours' => $fruitGrowthCycle->sprout_time / 3600,
  1042. 'time_source' => '果实生长周期配置'
  1043. ]);
  1044. return $now->addSeconds($fruitGrowthCycle->sprout_time);
  1045. case GROWTH_STAGE::GROWTH->value:
  1046. // 生长期:使用果实生长周期配置
  1047. Log::info('使用生长期配置', [
  1048. 'crop_id' => $crop->id,
  1049. 'growth_time' => $fruitGrowthCycle->growth_time,
  1050. 'time_hours' => $fruitGrowthCycle->growth_time / 3600,
  1051. 'time_source' => '果实生长周期配置'
  1052. ]);
  1053. return $now->addSeconds($fruitGrowthCycle->growth_time);
  1054. case GROWTH_STAGE::FRUIT->value:
  1055. // 果实期:使用果实生长周期配置
  1056. Log::info('使用果实期配置', [
  1057. 'crop_id' => $crop->id,
  1058. 'fruit_time' => $fruitGrowthCycle->fruit_time,
  1059. 'time_hours' => $fruitGrowthCycle->fruit_time / 3600,
  1060. 'time_source' => '果实生长周期配置'
  1061. ]);
  1062. return $fruitGrowthCycle->fruit_time > 0 ? $now->addSeconds($fruitGrowthCycle->fruit_time) : null;
  1063. case GROWTH_STAGE::MATURE->value:
  1064. // 成熟期:使用果实生长周期配置
  1065. if ($fruitGrowthCycle->mature_time > 0) {
  1066. Log::info('使用成熟期配置', [
  1067. 'crop_id' => $crop->id,
  1068. 'mature_time' => $fruitGrowthCycle->mature_time,
  1069. 'time_hours' => $fruitGrowthCycle->mature_time / 3600,
  1070. 'time_source' => '果实生长周期配置'
  1071. ]);
  1072. return $now->addSeconds($fruitGrowthCycle->mature_time);
  1073. }
  1074. // 成熟期时间为0表示无时间限制
  1075. Log::info('成熟期无时间限制', ['crop_id' => $crop->id]);
  1076. return null;
  1077. case GROWTH_STAGE::WITHERED->value:
  1078. // 枯萎期:使用果实生长周期配置
  1079. if ($fruitGrowthCycle->wither_time > 0) {
  1080. Log::info('使用枯萎期配置', [
  1081. 'crop_id' => $crop->id,
  1082. 'wither_time' => $fruitGrowthCycle->wither_time,
  1083. 'time_hours' => $fruitGrowthCycle->wither_time / 3600,
  1084. 'time_source' => '果实生长周期配置'
  1085. ]);
  1086. return $now->addSeconds($fruitGrowthCycle->wither_time);
  1087. }
  1088. // 枯萎期时间为0表示无结束时间
  1089. Log::info('枯萎期无时间限制', ['crop_id' => $crop->id]);
  1090. return null;
  1091. default:
  1092. Log::warning('未知生长阶段', ['crop_id' => $crop->id, 'stage' => $stage]);
  1093. return null;
  1094. }
  1095. }
  1096. /**
  1097. * 获取随机产出
  1098. *
  1099. * @param int $seedId
  1100. * @return array
  1101. */
  1102. public function getRandomOutput(int $seedId): array
  1103. {
  1104. // 获取种子的所有产出配置
  1105. $outputs = FarmSeedOutput::where('seed_id', $seedId)->get();
  1106. if ($outputs->isEmpty()) {
  1107. // 如果没有产出配置,使用种子的默认产出
  1108. $seed = FarmSeed::find($seedId);
  1109. return [
  1110. 'item_id' => $seed->item_id,
  1111. 'min_amount' => $seed->min_output,
  1112. 'max_amount' => $seed->max_output,
  1113. ];
  1114. }
  1115. // 按概率排序
  1116. $outputs = $outputs->sortByDesc('probability');
  1117. // 获取默认产出
  1118. $defaultOutput = $outputs->firstWhere('is_default', true);
  1119. // 随机选择产出
  1120. $random = mt_rand(1, 100);
  1121. $cumulativeProbability = 0;
  1122. foreach ($outputs as $output) {
  1123. $cumulativeProbability += $output->probability;
  1124. if ($random <= $cumulativeProbability) {
  1125. return [
  1126. 'item_id' => $output->item_id,
  1127. 'min_amount' => $output->min_amount,
  1128. 'max_amount' => $output->max_amount,
  1129. ];
  1130. }
  1131. }
  1132. // 如果随机值超过了所有概率之和,使用默认产出
  1133. if ($defaultOutput) {
  1134. return [
  1135. 'item_id' => $defaultOutput->item_id,
  1136. 'min_amount' => $defaultOutput->min_amount,
  1137. 'max_amount' => $defaultOutput->max_amount,
  1138. ];
  1139. }
  1140. // 如果没有默认产出,使用第一个产出
  1141. $firstOutput = $outputs->first();
  1142. return [
  1143. 'item_id' => $firstOutput->item_id,
  1144. 'min_amount' => $firstOutput->min_amount,
  1145. 'max_amount' => $firstOutput->max_amount,
  1146. ];
  1147. }
  1148. /**
  1149. * 根据物品ID获取产出配置信息
  1150. *
  1151. * @param int $seedId
  1152. * @param int $itemId
  1153. * @return array
  1154. */
  1155. private function getOutputInfoByItemId(int $seedId, int $itemId): array
  1156. {
  1157. try {
  1158. // 获取种子的所有产出配置
  1159. $outputs = FarmSeedOutput::where('seed_id', $seedId)->get();
  1160. // 查找匹配的产出配置
  1161. $targetOutput = $outputs->firstWhere('item_id', $itemId);
  1162. if ($targetOutput) {
  1163. return [
  1164. 'item_id' => $targetOutput->item_id,
  1165. 'min_amount' => $targetOutput->min_amount,
  1166. 'max_amount' => $targetOutput->max_amount,
  1167. 'disaster_max_amount' => $targetOutput->disaster_max_amount ?? 2000,
  1168. 'disaster_min_amount' => $targetOutput->disaster_min_amount ?? 500,
  1169. ];
  1170. }
  1171. // 如果没有找到匹配的产出配置,使用种子的默认产出
  1172. $seed = FarmSeed::find($seedId);
  1173. if ($seed) {
  1174. return [
  1175. 'item_id' => $itemId, // 使用传入的物品ID
  1176. 'min_amount' => $seed->min_output,
  1177. 'max_amount' => $seed->max_output,
  1178. 'disaster_max_amount' => $seed->disaster_max_output ?? 2000,
  1179. 'disaster_min_amount' => $seed->disaster_min_output ?? 500,
  1180. ];
  1181. }
  1182. // 如果种子也不存在,返回默认值
  1183. Log::warning('种子不存在,使用默认产出配置', [
  1184. 'seed_id' => $seedId,
  1185. 'item_id' => $itemId
  1186. ]);
  1187. return [
  1188. 'item_id' => $targetOutput->item_id,
  1189. 'min_amount' => $targetOutput->min_amount,
  1190. 'max_amount' => $targetOutput->max_amount,
  1191. ];
  1192. } catch (\Exception $e) {
  1193. Log::error('获取产出配置信息失败', [
  1194. 'seed_id' => $seedId,
  1195. 'item_id' => $itemId,
  1196. 'error' => $e->getMessage()
  1197. ]);
  1198. // 发生错误时返回安全的默认值
  1199. return [
  1200. 'item_id' => $itemId,
  1201. 'min_amount' => 1,
  1202. 'max_amount' => 10,
  1203. 'disaster_max_amount' => 10,
  1204. ];
  1205. }
  1206. }
  1207. /**
  1208. * 计算成熟期产量
  1209. *
  1210. * 在作物进入成熟期时调用,计算并确定最终产量
  1211. *
  1212. * @param FarmCrop $crop 作物对象
  1213. * @return int 最终产量
  1214. */
  1215. public function calculateMatureOutput(FarmCrop $crop): int
  1216. {
  1217. try {
  1218. $land = $crop->land;
  1219. $seed = $crop->seed;
  1220. $farmUser = $crop->user;
  1221. // 1. 验证必须有产出物品ID
  1222. if (!$crop->final_output_item_id) {
  1223. Log::error('成熟期产量计算失败:作物没有确定的产出物品ID', [
  1224. 'crop_id' => $crop->id,
  1225. 'user_id' => $crop->user_id,
  1226. 'seed_id' => $seed->id,
  1227. 'growth_stage' => $crop->growth_stage->value
  1228. ]);
  1229. throw new \Exception("作物ID {$crop->id} 没有确定的产出物品ID,无法计算产量");
  1230. }
  1231. // 2. 获取基础产量(使用发芽期确定的产出配置)
  1232. $outputInfo = $this->getOutputInfoByItemId($seed->id, $crop->final_output_item_id);
  1233. // 检查是否有灾害,如果有灾害则使用灾害时的产量区间
  1234. $hasDisaster = !empty($crop->disasters);
  1235. $minBaseAmount = $outputInfo['min_amount'];
  1236. $maxBaseAmount = $outputInfo['max_amount'];
  1237. if ($hasDisaster) {
  1238. // 有灾害时,使用灾害时的产量区间
  1239. $disasterMinAmount = $outputInfo['disaster_min_amount'] ?? 500;
  1240. $disasterMaxAmount = $outputInfo['disaster_max_amount'] ?? 2000;
  1241. $minBaseAmount = $disasterMinAmount;
  1242. $maxBaseAmount = $disasterMaxAmount;
  1243. }
  1244. // 3. 计算基础产量(随机值)
  1245. $baseAmount = mt_rand($minBaseAmount, $maxBaseAmount);
  1246. // 3. 获取土地的产量加成(使用种植时记录的土地等级)
  1247. $landType = \App\Module\Farm\Models\FarmLandType::find($crop->land_level);
  1248. $landOutputBonus = $landType ? $landType->output_bonus : 0;
  1249. // 4. 获取房屋的产量加成
  1250. $houseConfig = $farmUser->houseConfig;
  1251. $houseOutputBonus = ($houseConfig->output_bonus ?? 0) / 100; // 将百分比值转换为小数
  1252. // 5. 检查是否有丰收之神加持
  1253. $hasHarvestBuff = $farmUser->buffs()
  1254. ->where('buff_type', \App\Module\Farm\Enums\BUFF_TYPE::HARVEST_GOD)
  1255. ->where('expire_time', '>', now())
  1256. ->exists();
  1257. // 6. 计算灾害减产(基础产量已经考虑了灾害影响,这里记录用于日志)
  1258. $disasterPenalty = 0;
  1259. if (!empty($crop->disasters)) {
  1260. $dJian = \App\Module\Farm\Services\DisasterService::getAllDisasters();
  1261. foreach ($crop->disasters as $disaster) {
  1262. if (($disaster['status'] ?? '') === 'active') {
  1263. // 递加减产比例(仅用于日志记录)
  1264. $disasterPenalty += $dJian[$disaster['type']] ?? 0.05; // 默认5%减产
  1265. }
  1266. }
  1267. }
  1268. // 7. 计算最终产量
  1269. $finalAmount = $baseAmount;
  1270. // 应用土地加成
  1271. $finalAmount = (int)($finalAmount * (1 + $landOutputBonus));
  1272. // 应用房屋加成
  1273. $finalAmount = (int)($finalAmount * (1 + $houseOutputBonus));
  1274. // 注意:灾害影响已经在基础产量计算时考虑,这里不再重复应用
  1275. // 如果有丰收之神加持,使用最大可能产量
  1276. if ($hasHarvestBuff) {
  1277. // 丰收之神加持时的最大产量也要考虑灾害影响
  1278. $maxPossibleAmount = $hasDisaster ?
  1279. ($outputInfo['disaster_max_amount'] ?? 2000) :
  1280. $outputInfo['max_amount'];
  1281. $maxPossibleAmount = (int)($maxPossibleAmount * (1 + $landOutputBonus));
  1282. $maxPossibleAmount = (int)($maxPossibleAmount * (1 + $houseOutputBonus));
  1283. $finalAmount = max($finalAmount, $maxPossibleAmount);
  1284. }
  1285. // 8. 应用产量限制
  1286. // 确保产量不超过全局最高产量
  1287. $globalMaxOutput = 3000;
  1288. $finalAmount = min($finalAmount, $globalMaxOutput);
  1289. // 如果有灾害,确保产量不超过产出配置的灾害时最高产量(双重保险)
  1290. if ($hasDisaster) {
  1291. $disasterMaxAmount = $outputInfo['disaster_max_amount'] ?? 2000;
  1292. $finalAmount = min($finalAmount, $disasterMaxAmount);
  1293. }
  1294. // 确保最小产量为1
  1295. $finalAmount = max(1, $finalAmount);
  1296. Log::info('成熟期产量计算完成', [
  1297. 'crop_id' => $crop->id,
  1298. 'user_id' => $crop->user_id,
  1299. 'seed_id' => $seed->id,
  1300. 'base_amount' => $baseAmount,
  1301. 'min_base_amount' => $minBaseAmount,
  1302. 'max_base_amount' => $maxBaseAmount,
  1303. 'final_amount' => $finalAmount,
  1304. 'land_bonus' => $landOutputBonus,
  1305. 'house_bonus' => $houseOutputBonus,
  1306. 'has_disaster' => $hasDisaster,
  1307. 'disaster_penalty' => $disasterPenalty,
  1308. 'has_harvest_buff' => $hasHarvestBuff,
  1309. 'disaster_max_amount' => $outputInfo['disaster_max_amount'] ?? 2000,
  1310. 'global_max_output' => $globalMaxOutput,
  1311. 'final_output_item_id' => $crop->final_output_item_id
  1312. ]);
  1313. // 记录确认产出数量事件
  1314. FarmCropLog::logOutputCalculated($crop->user_id, $crop->land_id, $crop->id, $seed->id, [
  1315. 'base_amount' => $baseAmount,
  1316. 'final_amount' => $finalAmount,
  1317. 'land_bonus' => $landOutputBonus,
  1318. 'house_bonus' => $houseOutputBonus,
  1319. 'has_disaster' => $hasDisaster,
  1320. 'disaster_penalty' => $disasterPenalty,
  1321. 'has_harvest_buff' => $hasHarvestBuff,
  1322. 'disaster_max_amount' => $outputInfo['disaster_max_amount'] ?? 2000,
  1323. 'global_max_output' => $globalMaxOutput,
  1324. 'growth_stage' => GROWTH_STAGE::MATURE->value,
  1325. 'land_type' => $crop->land_level,
  1326. 'final_output_item_id' => $crop->final_output_item_id
  1327. ]);
  1328. return $finalAmount;
  1329. } catch (\Exception $e) {
  1330. Log::error('成熟期产量计算失败', [
  1331. 'crop_id' => $crop->id,
  1332. 'user_id' => $crop->user_id,
  1333. 'error' => $e->getMessage(),
  1334. 'trace' => $e->getTraceAsString()
  1335. ]);
  1336. // 发生错误时返回种子的最小产量
  1337. return $crop->seed->min_output ?? 1;
  1338. }
  1339. }
  1340. }