93 lines
2.8 KiB
PHP
93 lines
2.8 KiB
PHP
<?php
|
|
|
|
namespace App\Console\Commands\BiAng;
|
|
|
|
use App\Enums\DeviceStatus;
|
|
use App\Enums\DeviceType;
|
|
use App\Models\Device;
|
|
use App\Models\WormStatisticsReport;
|
|
use App\Services\BiAngDeviceService;
|
|
use Illuminate\Console\Command;
|
|
use Illuminate\Support\Arr;
|
|
|
|
class WormStatisticsSyncCommand extends Command
|
|
{
|
|
/**
|
|
* The name and signature of the console command.
|
|
*
|
|
* @var string
|
|
*/
|
|
protected $signature = 'biang:worm-statistics-sync';
|
|
|
|
/**
|
|
* The console command description.
|
|
*
|
|
* @var string
|
|
*/
|
|
protected $description = '虫情设备统计数据同步';
|
|
|
|
/**
|
|
* Execute the console command.
|
|
*/
|
|
public function handle()
|
|
{
|
|
$this->sync();
|
|
}
|
|
|
|
protected function sync(): void
|
|
{
|
|
/** @var \Illuminate\Database\Eloquent\Collection */
|
|
$devices = Device::with(['project'])
|
|
->supplierBy('device-supplier-biang')
|
|
->where('type', DeviceType::Worm)
|
|
->whereIn('status', [DeviceStatus::Online, DeviceStatus::Offline])
|
|
->get();
|
|
|
|
if ($devices->isEmpty()) {
|
|
$this->warn('没有找到虫情设备');
|
|
return;
|
|
}
|
|
|
|
$today = today();
|
|
|
|
foreach ($devices as $device) {
|
|
$this->info('==================================');
|
|
|
|
$latestReportedAt = WormStatisticsReport::Where('device_id', $device->id)->latest('reported_at')->value('reported_at');
|
|
|
|
$start = $latestReportedAt ? $latestReportedAt->copy() : $today->copy()->subDays(179);
|
|
|
|
$days = $start->diffInDays($today, false);
|
|
|
|
if ($days > 179) {
|
|
$end = $start->copy()->addDays(179);
|
|
} else {
|
|
if ($days < 2) {
|
|
$start = $today->copy()->subDays(2);
|
|
}
|
|
$end = $today->copy();
|
|
}
|
|
$this->info('设备编号: '.$device->sn);
|
|
$this->info('开始日期: '.$start->toDateString());
|
|
$this->info('结束日期: '.$end->toDateString());
|
|
|
|
$statistics = (new BiAngDeviceService())->getWormStatistics($device, $start, $end);
|
|
|
|
foreach (data_get($statistics, 'data.records', []) as $item) {
|
|
$data = collect(Arr::except($item, '日期'))->map(fn ($v, $k) => ['name' => $k, 'num' => $v]);
|
|
|
|
WormStatisticsReport::updateOrCreate([
|
|
'device_id' => $device->id,
|
|
'reported_at' => $item['日期'],
|
|
], [
|
|
'agricultural_base_id' => $device->agricultural_base_id,
|
|
'worm_num' => $data->sum('num'),
|
|
'data' => $data->values(),
|
|
]);
|
|
}
|
|
|
|
$this->info('==================================');
|
|
}
|
|
}
|
|
}
|