| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129 |
- <?php
- namespace App\Module\Farm\Services;
- use App\Module\Farm\Enums\DISASTER_TYPE;
- use App\Module\Farm\Logics\DisasterLogic;
- use Illuminate\Support\Facades\Log;
- class DisasterService
- {
- /**
- * 获取所有灾害 减产比例
- *
- * @return float[]
- */
- public static function getAllDisasters()
- {
- $disasterTypes = [
- DISASTER_TYPE::DROUGHT->valueInt() => 0.05, // 干旱
- DISASTER_TYPE::PEST->valueInt() => 0.05, // 虫害
- DISASTER_TYPE::WEED->valueInt() => 0.05, // 杂草
- ];
- return $disasterTypes;
- }
- /**
- * 获取灾害 产生比例
- *
- * @return float[]
- */
- public static function getRate()
- {
- $disasterTypes = [
- DISASTER_TYPE::DROUGHT->valueInt() => 0.9, // 干旱
- DISASTER_TYPE::PEST->valueInt() => 0.9, // 虫害
- DISASTER_TYPE::WEED->valueInt() => 0.9, // 杂草
- ];
- return $disasterTypes;
- }
- /**
- * 获取灾害类型对应的键名
- *
- * @param int $disasterType
- * @return string
- */
- public static function getDisasterKey(int $disasterType): string
- {
- $keys = [
- DISASTER_TYPE::DROUGHT->valueInt() => 'drought',
- DISASTER_TYPE::PEST->valueInt() => 'pest',
- DISASTER_TYPE::WEED->valueInt() => 'weed',
- ];
- return $keys[$disasterType] ?? '';
- }
- /**
- * 灾害检查间隔时间(分钟)
- *
- * @return int
- */
- public static function getCheckInterval(): int
- {
- return 5; // 每5分钟检查一次
- }
- /**
- * 批量生成灾害
- *
- * @param int|null $checkIntervalMinutes 检查间隔(分钟)
- * @return array 生成结果统计
- */
- public static function generateDisasterBatchs(?int $checkIntervalMinutes = null): array
- {
- try {
- $disasterLogic = new DisasterLogic();
- // 获取需要检查的作物列表
- $crops = $disasterLogic->getCropsNeedingDisasterCheck($checkIntervalMinutes);
- $totalCount = $crops->count();
- $generatedCount = 0;
- $skippedCount = 0;
- // 为每个作物单独处理,使用独立事务
- foreach ($crops as $crop) {
- try {
- // 为每个作物的灾害生成使用独立事务
- $result = \Illuminate\Support\Facades\DB::transaction(function () use ($disasterLogic, $crop) {
- return $disasterLogic->generateDisasters($crop);
- });
- if ($result === 'generated') {
- $generatedCount++;
- } elseif ($result === 'skipped') {
- $skippedCount++;
- }
- } catch (\Exception $e) {
- Log::error('单个作物灾害生成事务失败', [
- 'crop_id' => $crop->id,
- 'user_id' => $crop->user_id,
- 'error' => $e->getMessage()
- ]);
- $skippedCount++;
- }
- }
- return [
- 'total' => $totalCount,
- 'generated' => $generatedCount,
- 'skipped' => $skippedCount
- ];
- } catch (\Exception $e) {
- Log::error('批量生成灾害失败', [
- 'check_interval_minutes' => $checkIntervalMinutes,
- 'error' => $e->getMessage(),
- 'trace' => $e->getTraceAsString()
- ]);
- // 重新抛出异常,不隐藏错误
- throw $e;
- }
- }
- }
|