MaterialRanking.php 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  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. use App\Module\User\Models\User;
  8. /**
  9. * 材料持有排名图表
  10. * 显示三大材料(木材/石材/钢材)的用户持有排名
  11. */
  12. class MaterialRanking extends Ranking
  13. {
  14. /**
  15. * 材料ID映射
  16. */
  17. protected $materialIds = [
  18. 'wood' => 33, // 木材
  19. 'stone' => 34, // 石材
  20. 'steel' => 35, // 钢材
  21. ];
  22. /**
  23. * 材料名称映射
  24. */
  25. protected $materialNames = [
  26. 'wood' => '木材',
  27. 'stone' => '石材',
  28. 'steel' => '钢材',
  29. ];
  30. /**
  31. * 初始化卡片内容
  32. */
  33. protected function init()
  34. {
  35. parent::init();
  36. $this->title('材料持有排名');
  37. $this->dropdown([
  38. 'wood' => '木材排行榜',
  39. 'stone' => '石材排行榜',
  40. 'steel' => '钢材排行榜',
  41. ]);
  42. }
  43. /**
  44. * 处理请求
  45. *
  46. * @param Request $request
  47. * @return mixed|void
  48. */
  49. public function handle(Request $request)
  50. {
  51. $materialType = $request->get('option', 'wood');
  52. $data = $this->getMaterialRankingData($materialType);
  53. // 卡片内容
  54. $this->withContent($data);
  55. }
  56. /**
  57. * 获取材料排名数据
  58. *
  59. * @param string $materialType
  60. * @return array
  61. */
  62. protected function getMaterialRankingData($materialType)
  63. {
  64. $itemId = $this->materialIds[$materialType] ?? $this->materialIds['wood'];
  65. $materialName = $this->materialNames[$materialType] ?? $this->materialNames['wood'];
  66. // 查询用户材料持有量排名(前20名)
  67. $rankings = ItemUser::with('user')
  68. ->select([
  69. 'user_id',
  70. DB::raw('SUM(quantity) as total_quantity')
  71. ])
  72. ->where('item_id', $itemId)
  73. ->where('is_frozen', 0) // 排除冻结的物品
  74. ->whereNull('expire_at') // 排除已过期的物品
  75. ->groupBy('user_id')
  76. ->orderByDesc('total_quantity')
  77. ->limit(20)
  78. ->get();
  79. $result = [];
  80. foreach ($rankings as $index => $ranking) {
  81. $username = $ranking->user ? $ranking->user->username : null;
  82. $result[] = [
  83. 'rank' => $index + 1,
  84. 'title' => $username ?: "用户{$ranking->user_id}",
  85. 'number' => number_format($ranking->total_quantity) . ' 个',
  86. ];
  87. }
  88. // 如果没有数据,返回空排名提示
  89. if (empty($result)) {
  90. $result[] = [
  91. 'rank' => '-',
  92. 'title' => '暂无' . $materialName . '持有数据',
  93. 'number' => '0 个',
  94. ];
  95. }
  96. return $result;
  97. }
  98. }