| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106 |
- <?php
- namespace App\Module\Farm\AdminControllers\Metrics;
- use App\Module\Farm\Models\FarmCrop;
- use App\Module\GameItems\Models\Item;
- use UCore\DcatAdmin\Metrics\Examples\NumberS2;
- use Illuminate\Http\Request;
- use Illuminate\Support\Facades\DB;
- /**
- * 农场土地产出果实种类统计卡片基类
- * 使用FarmCrop模型统计指定土地等级的产出果实种类
- */
- abstract class BaseLandFruitStatsCard extends NumberS2
- {
- /**
- * 土地类型ID
- * 子类需要重写此属性
- */
- protected int $landType;
- /**
- * 土地类型名称
- * 子类需要重写此属性
- */
- protected string $landTypeName;
- /**
- * 初始化卡片内容
- */
- protected function init()
- {
- parent::init();
- $this->title($this->landTypeName . '产出果实统计');
- // 移除下拉选项,因为产出统计不需要时间范围选择
- $this->dropdown([]);
- }
- /**
- * 处理请求
- *
- * @param Request $request
- * @return mixed|void
- */
- public function handle(Request $request)
- {
- $stats = $this->getLandFruitStats();
- // 转换为NumberS2需要的数据格式
- $dataList = [];
- foreach ($stats as $stat) {
- $dataList[$stat['fruit_name']] = $stat['harvest_count'];
- }
- $this->withContent($dataList);
- }
- /**
- * 获取指定土地类型的果实种类统计数据
- * 包含软删除的数据以提供完整的数据分析
- *
- * @return array
- */
- private function getLandFruitStats(): array
- {
- // 从作物表中统计指定土地等级的产出果实,按果实种类分组
- // 使用withTrashed()包含软删除的数据
- $cropStats = FarmCrop::withTrashed()
- ->where('land_level', $this->landType)
- ->whereNotNull('final_output_item_id')
- ->select('final_output_item_id', DB::raw('COUNT(*) as crop_count'))
- ->groupBy('final_output_item_id')
- ->get();
- if ($cropStats->isEmpty()) {
- return [];
- }
- // 获取物品名称
- $itemIds = $cropStats->pluck('final_output_item_id')->toArray();
- $items = Item::whereIn('id', $itemIds)->get()->keyBy('id');
- $stats = [];
- foreach ($cropStats as $stat) {
- $itemId = (int)$stat->final_output_item_id;
- $item = $items->get($itemId);
- if ($item) {
- $stats[] = [
- 'item_id' => $itemId,
- 'fruit_name' => $item->name,
- 'harvest_count' => (int)$stat->crop_count
- ];
- }
- }
- // 按作物数量降序排列
- usort($stats, function($a, $b) {
- return $b['harvest_count'] - $a['harvest_count'];
- });
- return $stats;
- }
- }
|