LandLogic.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548
  1. <?php
  2. namespace App\Module\Farm\Logics;
  3. use App\Module\Farm\Dtos\LandInfoDto;
  4. use App\Module\Farm\Enums\LAND_STATUS;
  5. use App\Module\Farm\Enums\LAND_TYPE;
  6. use App\Module\Farm\Enums\UPGRADE_TYPE;
  7. use App\Module\Farm\Events\LandCreatedEvent;
  8. use App\Module\Farm\Events\LandUpgradedEvent;
  9. use App\Module\Farm\Models\FarmLand;
  10. use App\Module\Farm\Models\FarmLandType;
  11. use App\Module\Farm\Models\FarmLandUpgradeConfig;
  12. use App\Module\Farm\Models\FarmUpgradeLog;
  13. use App\Module\Farm\Models\FarmUser;
  14. use App\Module\Game\Enums\REWARD_SOURCE_TYPE;
  15. use App\Module\Game\Services\ConsumeService;
  16. use Illuminate\Support\Collection;
  17. use Illuminate\Support\Facades\Log;
  18. use UCore\Dto\Res;
  19. use UCore\Exception\LogicException;
  20. use UCore\Db\Helper;
  21. /**
  22. * 土地管理逻辑
  23. */
  24. class LandLogic
  25. {
  26. /**
  27. * 获取用户的所有土地
  28. *
  29. * @param int $userId
  30. * @return Collection|LandInfoDto[]
  31. */
  32. public function getUserLands(int $userId): Collection
  33. {
  34. try {
  35. $lands = FarmLand::where('user_id', $userId)
  36. ->orderBy('position')
  37. ->get();
  38. // dd($lands);
  39. return $lands->map(function ($land) {
  40. return LandInfoDto::fromModel($land);
  41. });
  42. } catch (\Exception $e) {
  43. Log::error('获取用户土地失败', [
  44. 'user_id' => $userId,
  45. 'error' => $e->getMessage(),
  46. 'trace' => $e->getTraceAsString()
  47. ]);
  48. return collect();
  49. }
  50. }
  51. /**
  52. * 获取用户指定位置的土地
  53. *
  54. * @param int $userId
  55. * @param int $position
  56. * @return LandInfoDto|null
  57. */
  58. public function getUserLandByPosition(int $userId, int $position): ?LandInfoDto
  59. {
  60. try {
  61. $land = FarmLand::where('user_id', $userId)
  62. ->where('position', $position)
  63. ->first();
  64. if (!$land) {
  65. return null;
  66. }
  67. return LandInfoDto::fromModel($land);
  68. } catch (\Exception $e) {
  69. Log::error('获取用户指定位置土地失败', [
  70. 'user_id' => $userId,
  71. 'position' => $position,
  72. 'error' => $e->getMessage(),
  73. 'trace' => $e->getTraceAsString()
  74. ]);
  75. return null;
  76. }
  77. }
  78. /**
  79. * 创建土地
  80. *
  81. * @param int $userId
  82. * @param int $position
  83. * @param int $landType
  84. * @return FarmLand|null
  85. */
  86. public function createLand(int $userId, int $position, int $landType): ?FarmLand
  87. {
  88. try {
  89. // 检查位置是否已有土地
  90. $existingLand = FarmLand::where('user_id', $userId)
  91. ->where('position', $position)
  92. ->first();
  93. if ($existingLand) {
  94. return $existingLand;
  95. }
  96. // 创建新土地
  97. $land = new FarmLand();
  98. $land->user_id = $userId;
  99. $land->position = $position;
  100. $land->land_type = $landType;
  101. $land->status = LAND_STATUS::IDLE->value;
  102. $land->save();
  103. // 触发土地创建事件
  104. event(new LandCreatedEvent($userId, $land->id));
  105. Log::info('创建土地成功', [
  106. 'user_id' => $userId,
  107. 'position' => $position,
  108. 'land_type' => $landType,
  109. 'land_id' => $land->id
  110. ]);
  111. return $land;
  112. } catch (\Exception $e) {
  113. Log::error('创建土地失败', [
  114. 'user_id' => $userId,
  115. 'position' => $position,
  116. 'land_type' => $landType,
  117. 'error' => $e->getMessage(),
  118. 'trace' => $e->getTraceAsString()
  119. ]);
  120. return null;
  121. }
  122. }
  123. /**
  124. * 升级土地
  125. * 调用前必须已经完成所有验证(土地归属、状态、路径、材料等)
  126. * 要求调用者已开启事务
  127. *
  128. * @param int $userId
  129. * @param int $landId
  130. * @param int $targetType
  131. * @return bool
  132. */
  133. public function upgradeLand(int $userId, int $landId, int $targetType): bool
  134. {
  135. // 验证事务是否已开启
  136. Helper::check_tr();
  137. // 获取土地信息
  138. /**
  139. * @var FarmLand $land
  140. */
  141. $land = FarmLand::where('id', $landId)
  142. ->where('user_id', $userId)
  143. ->first();
  144. // 防错误机制:基础数据检查
  145. if (!$land) {
  146. throw new LogicException('Logic层防错误:土地不存在,验证层应该已经检查过');
  147. }
  148. // 防错误机制:状态检查
  149. if ($land->status !== LAND_STATUS::IDLE->value) {
  150. throw new LogicException('Logic层防错误:土地状态不允许升级,验证层应该已经检查过');
  151. }
  152. // 防错误机制:类型检查
  153. if ($land->land_type === $targetType) {
  154. throw new LogicException('Logic层防错误:土地已经是目标类型,验证层应该已经检查过');
  155. }
  156. // 获取升级配置(这里不再进行完整验证,只获取配置)
  157. $config = FarmLandUpgradeConfig::where('from_type_id', $land->land_type)
  158. ->where('to_type_id', $targetType)
  159. ->first();
  160. // 防错误机制:配置检查
  161. if (!$config) {
  162. throw new LogicException('Logic层防错误:升级配置不存在,验证层应该已经检查过');
  163. }
  164. // 更新土地类型
  165. $oldType = $land->land_type;
  166. $land->land_type = $targetType;
  167. $land->save();
  168. if(!$land->save()){
  169. // 保存失败
  170. throw new LogicException('升级失败-2');
  171. }
  172. // 创建升级记录
  173. $upgradeLog = new FarmUpgradeLog();
  174. $upgradeLog->user_id = $userId;
  175. $upgradeLog->upgrade_type = UPGRADE_TYPE::LAND->value;
  176. $upgradeLog->target_id = $landId;
  177. $upgradeLog->old_level = $oldType;
  178. $upgradeLog->new_level = $targetType;
  179. $upgradeLog->materials_consumed = [];
  180. $upgradeLog->upgrade_time = now();
  181. $upgradeLog->created_at = now();
  182. if(!$upgradeLog->save()){
  183. // 保存失败
  184. throw new LogicException('升级失败-3');
  185. }
  186. // 进行消耗
  187. $ec = ConsumeService::executeConsume(
  188. $userId, $config->materials,
  189. REWARD_SOURCE_TYPE::LAND_UPGRADE,
  190. $upgradeLog->id, false);
  191. if ($ec->error) {
  192. throw new LogicException('消耗失败');
  193. }
  194. $upgradeLog->materials_consumed = $ec->data['list'];
  195. $upgradeLog->save();
  196. // 触发土地升级事件
  197. event(new LandUpgradedEvent($userId, $land, $oldType, $targetType, $upgradeLog));
  198. Log::info('土地升级成功', [
  199. 'user_id' => $userId,
  200. 'land_id' => $landId,
  201. 'old_type' => $oldType,
  202. 'new_type' => $targetType,
  203. 'upgrade_log_id' => $upgradeLog->id
  204. ]);
  205. return true;
  206. }
  207. /**
  208. * 检查升级路径
  209. *
  210. * @param $userId
  211. * @param $currentType
  212. * @param $targetType
  213. * @param bool $checkM 是否检查消耗
  214. * @return Res
  215. * @throws \Exception
  216. */
  217. static public function checkUpgradePath(int $userId, int $currentType, int $targetType, bool $checkM = true): Res
  218. {
  219. // 获取升级配置
  220. /**
  221. * @var FarmLandUpgradeConfig $upgradeConfig
  222. */
  223. $upgradeConfig = FarmLandUpgradeConfig::where('from_type_id', $currentType)
  224. ->where('to_type_id', $targetType)
  225. ->first();
  226. if (!$upgradeConfig) {
  227. Log::error('升级路径不存在', [
  228. 'user_id' => $userId,
  229. 'current_type' => $currentType,
  230. 'target_type' => $targetType
  231. ]);
  232. return Res::error('升级路径不存在', [
  233. 'user_id' => $userId,
  234. 'current_type' => $currentType,
  235. 'target_type' => $targetType
  236. ]);
  237. }
  238. // 检查用户房屋等级是否满足要求
  239. $targetLandType = FarmLandType::find($targetType);
  240. $farmUser = FarmUser::where('user_id', $userId)->first();
  241. if (!$farmUser || $farmUser->house_level < $targetLandType->unlock_house_level) {
  242. Log::error('房屋等级不足,无法升级到该土地类型', [
  243. 'user_id' => $userId,
  244. 'current_type' => $currentType,
  245. 'target_type' => $targetType,
  246. 'house_level' => $farmUser->house_level,
  247. 'unlock_house_level' => $targetLandType->unlock_house_level
  248. ]);
  249. return Res::error('房屋等级不足,无法升级到该土地类型', [
  250. 'user_id' => $userId,
  251. 'current_type' => $currentType,
  252. 'target_type' => $targetType,
  253. 'house_level' => $farmUser->house_level,
  254. 'unlock_house_level' => $targetLandType->unlock_house_level
  255. ]);
  256. }
  257. // 检查特殊土地数量限制
  258. if ($targetLandType->is_special) {
  259. $specialLandCount = FarmLand::where('user_id', $userId)
  260. ->whereIn('land_type', [ LAND_TYPE::GOLD->value, LAND_TYPE::BLUE->value, LAND_TYPE::PURPLE->value ])
  261. ->count();
  262. $houseConfig = $farmUser->houseConfig;
  263. if ($specialLandCount >= $houseConfig->special_land_limit) {
  264. Log::error('特殊土地数量已达上限', [
  265. 'user_id' => $userId,
  266. 'current_type' => $currentType,
  267. 'target_type' => $targetType,
  268. 'special_land_count' => $specialLandCount,
  269. 'special_land_limit' => $houseConfig->special_land_limit
  270. ]);
  271. return Res::error('特殊土地数量已达上限', [
  272. 'user_id' => $userId,
  273. 'current_type' => $currentType,
  274. 'target_type' => $targetType,
  275. 'special_land_count' => $specialLandCount,
  276. 'special_land_limit' => $houseConfig->special_land_limit
  277. ]);
  278. }
  279. }
  280. // 检查消耗
  281. if ($checkM) {
  282. $res = ConsumeService::checkConsume($userId, $upgradeConfig->materials);
  283. if ($res->error) {
  284. Log::error('当前路径资源不足', [
  285. 'user_id' => $userId,
  286. 'current_type' => $currentType,
  287. 'target_type' => $targetType,
  288. 'error' => $res->message
  289. ]);
  290. return Res::error('当前路径资源不足', [
  291. 'msg' => $res->message
  292. ]);
  293. }
  294. }
  295. return Res::success('升级路径可用', [
  296. 'config' => $upgradeConfig
  297. ]);
  298. }
  299. /**
  300. * 获取升级所需材料
  301. *
  302. * @param int $currentType 当前土地类型
  303. * @param int $targetType 目标土地类型
  304. * @return array 升级所需材料
  305. */
  306. public function getUpgradeMaterials(int $currentType, int $targetType): array
  307. {
  308. try {
  309. // 从数据库中获取升级配置
  310. $upgradeConfig = FarmLandUpgradeConfig::where('from_type_id', $currentType)
  311. ->where('to_type_id', $targetType)
  312. ->first();
  313. if (!$upgradeConfig) {
  314. return [];
  315. }
  316. // 使用模型的 getUpgradeMaterials 方法获取材料
  317. return $upgradeConfig->getUpgradeMaterials();
  318. } catch (\Exception $e) {
  319. Log::error('获取升级所需材料失败', [
  320. 'current_type' => $currentType,
  321. 'target_type' => $targetType,
  322. 'error' => $e->getMessage(),
  323. 'trace' => $e->getTraceAsString()
  324. ]);
  325. return [];
  326. }
  327. }
  328. /**
  329. * 获取可用的升级路径(不进行消耗检查)
  330. *
  331. * @param int $userId 用户ID
  332. * @param int $landId 土地ID
  333. * @param int|null $toType 目标土地类型ID(可选)
  334. * @return FarmLandUpgradeConfig[]
  335. *
  336. */
  337. public function getAvailableUpgradePaths(int $userId, int $landId, ?int $toType = null): array
  338. {
  339. try {
  340. // 获取土地信息
  341. $land = FarmLand::where('id', $landId)
  342. ->where('user_id', $userId)
  343. ->first();
  344. if (!$land) {
  345. return [];
  346. }
  347. // 获取当前土地类型
  348. $currentType = $land->land_type;
  349. // 获取用户房屋等级
  350. /**
  351. * @var FarmUser $farmUser
  352. */
  353. $farmUser = FarmUser::where('user_id', $userId)->first();
  354. if (!$farmUser) {
  355. return [];
  356. }
  357. $houseLevel = $farmUser->house_level;
  358. // 获取可用的升级路径
  359. $query = FarmLandUpgradeConfig::where('from_type_id', $currentType)
  360. ->with('toType');
  361. // 如果指定了目标类型,则只获取该类型的升级路径
  362. if ($toType !== null) {
  363. $query->where('to_type_id', $toType);
  364. }
  365. $upgradePaths = $query->get();
  366. // 过滤出符合房屋等级要求的升级路径
  367. $availablePaths = $upgradePaths->filter(function ($path) use ($houseLevel) {
  368. return $path->toType->unlock_house_level <= $houseLevel;
  369. });
  370. // 检查特殊土地数量限制
  371. $specialLandCount = FarmLand::where('user_id', $userId)
  372. ->whereIn('land_type', [ LAND_TYPE::GOLD->value, LAND_TYPE::BLUE->value, LAND_TYPE::PURPLE->value ])
  373. ->count();
  374. $houseConfig = $farmUser->houseConfig;
  375. // 如果没有找到对应的房屋配置,使用默认值0
  376. $specialLandLimit = $houseConfig ? $houseConfig->special_land_limit : 0;
  377. // 如果特殊土地已达上限,过滤掉特殊土地升级路径
  378. if ($specialLandCount >= $specialLandLimit) {
  379. $availablePaths = $availablePaths->filter(function ($path) {
  380. return !$path->toType->is_special;
  381. });
  382. }
  383. // 格式化返回结果
  384. return $availablePaths->toArray();
  385. } catch (\Exception $e) {
  386. Log::error('获取可用升级路径失败', [
  387. 'user_id' => $userId,
  388. 'land_id' => $landId,
  389. 'error' => $e->getMessage(),
  390. 'trace' => $e->getTraceAsString()
  391. ]);
  392. return [];
  393. }
  394. }
  395. /**
  396. * 获取用户所有可收获的土地
  397. *
  398. * @param int $userId 用户ID
  399. * @return Collection|LandInfoDto[]
  400. */
  401. public function getHarvestableLands(int $userId): Collection
  402. {
  403. try {
  404. // 查询状态为可收获的土地
  405. $lands = FarmLand::where('user_id', $userId)
  406. ->where('status', LAND_STATUS::HARVESTABLE->value)
  407. ->orderBy('position')
  408. ->get();
  409. return $lands->map(function ($land) {
  410. return LandInfoDto::fromModel($land);
  411. });
  412. } catch (\Exception $e) {
  413. Log::error('获取可收获土地失败', [
  414. 'user_id' => $userId,
  415. 'error' => $e->getMessage(),
  416. 'trace' => $e->getTraceAsString()
  417. ]);
  418. return collect();
  419. }
  420. }
  421. /**
  422. * 获取用户所有空闲的土地
  423. *
  424. * @param int $userId 用户ID
  425. * @return Collection|LandInfoDto[]
  426. */
  427. public function getIdleLands(int $userId): Collection
  428. {
  429. try {
  430. // 查询状态为空闲的土地
  431. $lands = FarmLand::where('user_id', $userId)
  432. ->where('status', LAND_STATUS::IDLE->value)
  433. ->orderBy('position')
  434. ->get();
  435. return $lands->map(function ($land) {
  436. return LandInfoDto::fromModel($land);
  437. });
  438. } catch (\Exception $e) {
  439. Log::error('获取空闲土地失败', [
  440. 'user_id' => $userId,
  441. 'error' => $e->getMessage(),
  442. 'trace' => $e->getTraceAsString()
  443. ]);
  444. return collect();
  445. }
  446. }
  447. /**
  448. * 获取用户所有有作物的土地
  449. *
  450. * @param int $userId 用户ID
  451. * @return Collection|LandInfoDto[]
  452. */
  453. public function getLandsWithCrops(int $userId): Collection
  454. {
  455. try {
  456. // 查询状态为种植中的土地
  457. $lands = FarmLand::where('user_id', $userId)
  458. ->where('has_crop', true)
  459. ->orderBy('position')
  460. ->get();
  461. return $lands->map(function ($land) {
  462. return LandInfoDto::fromModel($land);
  463. });
  464. } catch (\Exception $e) {
  465. Log::error('获取有作物的土地失败', [
  466. 'user_id' => $userId,
  467. 'error' => $e->getMessage(),
  468. 'trace' => $e->getTraceAsString()
  469. ]);
  470. return collect();
  471. }
  472. }
  473. }