BaseLandFruitStatsCard.php 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  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. *
  54. * @return array
  55. */
  56. private function getLandFruitStats(): array
  57. {
  58. // 从作物表中统计指定土地等级的产出果实,按果实种类分组
  59. // 使用withTrashed()包含软删除的数据
  60. $cropStats = FarmCrop::withTrashed()
  61. ->where('land_level', $this->landType)
  62. ->whereNotNull('final_output_item_id')
  63. ->select('final_output_item_id', DB::raw('COUNT(*) as crop_count'))
  64. ->groupBy('final_output_item_id')
  65. ->get();
  66. if ($cropStats->isEmpty()) {
  67. return [];
  68. }
  69. // 获取物品名称
  70. $itemIds = $cropStats->pluck('final_output_item_id')->toArray();
  71. $items = Item::whereIn('id', $itemIds)->get()->keyBy('id');
  72. $stats = [];
  73. foreach ($cropStats as $stat) {
  74. $itemId = (int)$stat->final_output_item_id;
  75. $item = $items->get($itemId);
  76. if ($item) {
  77. $stats[] = [
  78. 'item_id' => $itemId,
  79. 'fruit_name' => $item->name,
  80. 'harvest_count' => (int)$stat->crop_count
  81. ];
  82. }
  83. }
  84. // 按作物数量降序排列
  85. usort($stats, function($a, $b) {
  86. return $b['harvest_count'] - $a['harvest_count'];
  87. });
  88. return $stats;
  89. }
  90. }