| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293 |
- <?php
- namespace App\Module\Farm\AdminControllers\Metrics;
- use App\Module\Farm\Models\FarmCropLog;
- use App\Module\Farm\Models\FarmLandType;
- use UCore\DcatAdmin\Metrics\Examples\NumberS2;
- use Illuminate\Http\Request;
- use Illuminate\Support\Facades\DB;
- /**
- * 农场土地产出果实统计卡片
- * 使用单行多数字卡片显示各个土地等级的产出果实总数统计
- */
- class FarmLandOutputStatsCard extends NumberS2
- {
- /**
- * 初始化卡片内容
- */
- protected function init()
- {
- parent::init();
- $this->title('各等级土地产出果实统计');
- // 移除下拉选项,因为产出统计不需要时间范围选择
- $this->dropdown([]);
- }
- /**
- * 处理请求
- *
- * @param Request $request
- * @return mixed|void
- */
- public function handle(Request $request)
- {
- $stats = $this->getLandOutputStats();
- // 转换为NumberS2需要的数据格式
- $dataList = [];
- foreach ($stats as $stat) {
- $dataList[$stat['name']] = $stat['total_output'];
- }
- $this->withContent($dataList);
- }
- /**
- * 获取各等级土地产出果实统计数据
- *
- * @return array
- */
- private function getLandOutputStats(): array
- {
- // 获取所有土地类型配置
- $landTypes = FarmLandType::orderBy('id')->get()->keyBy('id');
- // 从作物日志表中统计各土地类型的收获数据
- $harvestStats = FarmCropLog::where('event_type', FarmCropLog::EVENT_HARVESTED)
- ->select('land_type', DB::raw('SUM(JSON_EXTRACT(event_data, "$.amount")) as total_amount'))
- ->groupBy('land_type')
- ->get()
- ->keyBy('land_type');
- $stats = [];
- $totalOutput = 0;
- // 遍历所有土地类型,生成统计数据
- foreach ($landTypes as $landType) {
- $harvestData = $harvestStats->get($landType->id);
- $outputAmount = $harvestData ? (int)$harvestData->total_amount : 0;
- $totalOutput += $outputAmount;
- // 只显示有产出的土地类型
- if ($outputAmount > 0) {
- $stats[] = [
- 'name' => $landType->name,
- 'total_output' => $outputAmount
- ];
- }
- }
- // 添加总计
- if ($totalOutput > 0) {
- $stats[] = [
- 'name' => '总计',
- 'total_output' => $totalOutput
- ];
- }
- return $stats;
- }
- }
|