WoodRanking.php 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  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. class WoodRanking extends Ranking
  12. {
  13. /**
  14. * 木材物品ID
  15. */
  16. protected $itemId = 33;
  17. /**
  18. * 初始化卡片内容
  19. */
  20. protected function init()
  21. {
  22. parent::init();
  23. $this->title('木材持有排名');
  24. $this->dropdown([
  25. '7' => '最近 7 天',
  26. '30' => '最近 30 天',
  27. '90' => '最近 90 天',
  28. 'all' => '全部时间',
  29. ]);
  30. }
  31. /**
  32. * 处理请求
  33. *
  34. * @param Request $request
  35. * @return mixed|void
  36. */
  37. public function handle(Request $request)
  38. {
  39. $timeRange = $request->get('option', 'all');
  40. $data = $this->getMaterialRankingData($timeRange);
  41. // 卡片内容
  42. $this->withContent($data);
  43. }
  44. /**
  45. * 获取木材排名数据
  46. *
  47. * @param string $timeRange
  48. * @return array
  49. */
  50. protected function getMaterialRankingData($timeRange)
  51. {
  52. // 构建查询
  53. $query = ItemUser::with('user')
  54. ->select([
  55. 'user_id',
  56. DB::raw('SUM(quantity) as total_quantity')
  57. ])
  58. ->where('item_id', $this->itemId)
  59. ->where('is_frozen', 0) // 排除冻结的物品
  60. ->whereNull('expire_at'); // 排除已过期的物品
  61. // 根据时间范围过滤
  62. if ($timeRange !== 'all') {
  63. $days = (int)$timeRange;
  64. $query->where('created_at', '>=', now()->subDays($days));
  65. }
  66. $rankings = $query->groupBy('user_id')
  67. ->orderByDesc('total_quantity')
  68. ->limit(20)
  69. ->get();
  70. $result = [];
  71. foreach ($rankings as $index => $ranking) {
  72. $username = $ranking->user ? $ranking->user->username : null;
  73. $result[] = [
  74. 'rank' => $index + 1,
  75. 'title' => $username ?: "用户{$ranking->user_id}",
  76. 'number' => number_format($ranking->total_quantity) . ' 个',
  77. ];
  78. }
  79. // 如果没有数据,返回空排名提示
  80. if (empty($result)) {
  81. $result[] = [
  82. 'rank' => '-',
  83. 'title' => '暂无木材持有数据',
  84. 'number' => '0 个',
  85. ];
  86. }
  87. return $result;
  88. }
  89. }