FruitRankingBase.php 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. <?php
  2. namespace App\Module\GameItems\AdminControllers\Metrics;
  3. use UCore\DcatAdmin\Metrics\Examples\Ranking;
  4. use Illuminate\Http\Request;
  5. use Illuminate\Support\Facades\DB;
  6. use App\Module\GameItems\Models\ItemUser;
  7. /**
  8. * 果实持有排名基础类
  9. * 为各种果实提供通用的排名功能
  10. */
  11. abstract class FruitRankingBase extends Ranking
  12. {
  13. /**
  14. * 果实物品ID
  15. * 子类需要重写此属性
  16. */
  17. protected $fruitId;
  18. /**
  19. * 果实名称
  20. * 子类需要重写此属性
  21. */
  22. protected $fruitName;
  23. /**
  24. * 初始化卡片内容
  25. */
  26. protected function init()
  27. {
  28. parent::init();
  29. $this->title($this->fruitName . '持有排名');
  30. $this->dropdown([
  31. '7' => '最近 7 天',
  32. '30' => '最近 30 天',
  33. '90' => '最近 90 天',
  34. 'all' => '全部时间',
  35. ]);
  36. }
  37. /**
  38. * 处理请求
  39. *
  40. * @param Request $request
  41. * @return mixed|void
  42. */
  43. public function handle(Request $request)
  44. {
  45. $timeRange = $request->get('option', 'all');
  46. $data = $this->getFruitRankingData($timeRange);
  47. // 卡片内容
  48. $this->withContent($data);
  49. }
  50. /**
  51. * 获取果实排名数据
  52. *
  53. * @param string $timeRange
  54. * @return array
  55. */
  56. protected function getFruitRankingData($timeRange)
  57. {
  58. // 构建查询
  59. $query = ItemUser::with('user')
  60. ->select([
  61. 'user_id',
  62. DB::raw('SUM(quantity) as total_quantity')
  63. ])
  64. ->where('item_id', $this->fruitId)
  65. ->where('is_frozen', 0) // 排除冻结的物品
  66. ->whereNull('expire_at'); // 排除已过期的物品
  67. // 根据时间范围过滤
  68. if ($timeRange !== 'all') {
  69. $days = (int)$timeRange;
  70. $query->where('created_at', '>=', now()->subDays($days));
  71. }
  72. $rankings = $query->groupBy('user_id')
  73. ->orderByDesc('total_quantity')
  74. ->limit(20)
  75. ->get();
  76. $result = [];
  77. foreach ($rankings as $index => $ranking) {
  78. $username = $ranking->user ? $ranking->user->username : null;
  79. $result[] = [
  80. 'rank' => $index + 1,
  81. 'title' => $username ?: "用户{$ranking->user_id}",
  82. 'number' => number_format($ranking->total_quantity) . ' 个',
  83. ];
  84. }
  85. // 如果没有数据,返回空排名提示
  86. if (empty($result)) {
  87. $result[] = [
  88. 'rank' => '-',
  89. 'title' => '暂无' . $this->fruitName . '持有数据',
  90. 'number' => '0 个',
  91. ];
  92. }
  93. return $result;
  94. }
  95. }