FarmLandOutputStatsCard.php 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. <?php
  2. namespace App\Module\Farm\AdminControllers\Metrics;
  3. use App\Module\Farm\Models\FarmCropLog;
  4. use App\Module\Farm\Models\FarmLandType;
  5. use UCore\DcatAdmin\Metrics\Examples\NumberS2;
  6. use Illuminate\Http\Request;
  7. use Illuminate\Support\Facades\DB;
  8. /**
  9. * 农场土地产出果实统计卡片
  10. * 使用单行多数字卡片显示各个土地等级的产出果实总数统计
  11. */
  12. class FarmLandOutputStatsCard extends NumberS2
  13. {
  14. /**
  15. * 初始化卡片内容
  16. */
  17. protected function init()
  18. {
  19. parent::init();
  20. $this->title('各等级土地产出果实统计');
  21. // 移除下拉选项,因为产出统计不需要时间范围选择
  22. $this->dropdown([]);
  23. }
  24. /**
  25. * 处理请求
  26. *
  27. * @param Request $request
  28. * @return mixed|void
  29. */
  30. public function handle(Request $request)
  31. {
  32. $stats = $this->getLandOutputStats();
  33. // 转换为NumberS2需要的数据格式
  34. $dataList = [];
  35. foreach ($stats as $stat) {
  36. $dataList[$stat['name']] = $stat['total_output'];
  37. }
  38. $this->withContent($dataList);
  39. }
  40. /**
  41. * 获取各等级土地产出果实统计数据
  42. *
  43. * @return array
  44. */
  45. private function getLandOutputStats(): array
  46. {
  47. // 获取所有土地类型配置
  48. $landTypes = FarmLandType::orderBy('id')->get()->keyBy('id');
  49. // 从作物日志表中统计各土地类型的收获数据
  50. $harvestStats = FarmCropLog::where('event_type', FarmCropLog::EVENT_HARVESTED)
  51. ->select('land_type', DB::raw('SUM(JSON_EXTRACT(event_data, "$.amount")) as total_amount'))
  52. ->groupBy('land_type')
  53. ->get()
  54. ->keyBy('land_type');
  55. $stats = [];
  56. $totalOutput = 0;
  57. // 遍历所有土地类型,生成统计数据
  58. foreach ($landTypes as $landType) {
  59. $harvestData = $harvestStats->get($landType->id);
  60. $outputAmount = $harvestData ? (int)$harvestData->total_amount : 0;
  61. $totalOutput += $outputAmount;
  62. // 只显示有产出的土地类型
  63. if ($outputAmount > 0) {
  64. $stats[] = [
  65. 'name' => $landType->name,
  66. 'total_output' => $outputAmount
  67. ];
  68. }
  69. }
  70. // 添加总计
  71. if ($totalOutput > 0) {
  72. $stats[] = [
  73. 'name' => '总计',
  74. 'total_output' => $totalOutput
  75. ];
  76. }
  77. return $stats;
  78. }
  79. }