BaseLandFruitStatsCard.php 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. <?php
  2. namespace App\Module\Farm\AdminControllers\Metrics;
  3. use App\Module\Farm\Models\FarmCrop;
  4. use App\Module\GameItems\Models\Item;
  5. use UCore\DcatAdmin\Metrics\Examples\NumberS2;
  6. use Illuminate\Http\Request;
  7. use Illuminate\Support\Facades\DB;
  8. /**
  9. * 农场土地产出果实种类统计卡片基类
  10. * 使用FarmCrop模型统计指定土地等级的产出果实种类
  11. */
  12. abstract class BaseLandFruitStatsCard extends NumberS2
  13. {
  14. /**
  15. * 土地类型ID
  16. * 子类需要重写此属性
  17. */
  18. protected int $landType;
  19. /**
  20. * 土地类型名称
  21. * 子类需要重写此属性
  22. */
  23. protected string $landTypeName;
  24. /**
  25. * 初始化卡片内容
  26. */
  27. protected function init()
  28. {
  29. parent::init();
  30. $this->title($this->landTypeName . '产出果实统计');
  31. // 移除下拉选项,因为产出统计不需要时间范围选择
  32. $this->dropdown([]);
  33. }
  34. /**
  35. * 处理请求
  36. *
  37. * @param Request $request
  38. * @return mixed|void
  39. */
  40. public function handle(Request $request)
  41. {
  42. $stats = $this->getLandFruitStats();
  43. // 转换为NumberS2需要的数据格式
  44. $dataList = [];
  45. foreach ($stats as $stat) {
  46. $dataList[$stat['fruit_name']] = $stat['harvest_count'];
  47. }
  48. $this->withContent($dataList);
  49. }
  50. /**
  51. * 获取指定土地类型的果实种类统计数据
  52. *
  53. * @return array
  54. */
  55. private function getLandFruitStats(): array
  56. {
  57. // 从作物表中统计指定土地等级的产出果实,按果实种类分组
  58. $cropStats = FarmCrop::where('land_level', $this->landType)
  59. ->whereNotNull('final_output_item_id')
  60. ->select('final_output_item_id', DB::raw('COUNT(*) as crop_count'))
  61. ->groupBy('final_output_item_id')
  62. ->get();
  63. if ($cropStats->isEmpty()) {
  64. return [];
  65. }
  66. // 获取物品名称
  67. $itemIds = $cropStats->pluck('final_output_item_id')->toArray();
  68. $items = Item::whereIn('id', $itemIds)->get()->keyBy('id');
  69. $stats = [];
  70. foreach ($cropStats as $stat) {
  71. $itemId = (int)$stat->final_output_item_id;
  72. $item = $items->get($itemId);
  73. if ($item) {
  74. $stats[] = [
  75. 'item_id' => $itemId,
  76. 'fruit_name' => $item->name,
  77. 'harvest_count' => (int)$stat->crop_count
  78. ];
  79. }
  80. }
  81. // 按作物数量降序排列
  82. usort($stats, function($a, $b) {
  83. return $b['harvest_count'] - $a['harvest_count'];
  84. });
  85. return $stats;
  86. }
  87. }