CropLogic.php 59 KB

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