'萝卜', 3 => '辣椒', 4 => '苹果', 5 => '西瓜', 6 => '草莓', 7 => '南瓜', 8 => '核桃', 9 => '可可', 10 => '人参', 11 => '玫瑰', ]; /** * 初始化卡片内容 */ protected function init() { parent::init(); $this->title('果实每日产出趋势'); $this->dropdown([ '7' => '最近 7 天', '14' => '最近 14 天', '30' => '最近 30 天', '90' => '最近 90 天', ]); } /** * 处理请求 * * @param Request $request * @return mixed|void */ public function handle(Request $request) { $days = (int)$request->get('option', 7); $chartData = $this->getFruitOutputData($days); // 计算总产出数量作为卡片内容 $totalOutput = array_sum(array_map('array_sum', $chartData['data'])); // 卡片内容 $this->withContent(number_format($totalOutput)); // 图表数据 $this->withChart($chartData['series'], $chartData['categories']); } /** * 获取果实产出数据 * * @param int $days * @return array */ protected function getFruitOutputData($days) { // 生成日期范围 $dates = []; for ($i = $days - 1; $i >= 0; $i--) { $dates[] = now()->subDays($i)->format('Y-m-d'); } // 查询每日产出数据 $outputData = ItemTransactionLog::select([ 'item_id', DB::raw('DATE(created_at) as date'), DB::raw('SUM(quantity) as daily_output') ]) ->whereIn('item_id', array_keys($this->fruitItems)) ->where('transaction_type', 1) // 获取类型 ->where('created_at', '>=', now()->subDays($days)) ->groupBy('item_id', DB::raw('DATE(created_at)')) ->get() ->groupBy('item_id'); // 构建图表数据 $series = []; $data = []; foreach ($this->fruitItems as $itemId => $itemName) { $itemData = []; $itemOutputs = $outputData->get($itemId, collect()); foreach ($dates as $date) { $dayOutput = $itemOutputs->where('date', $date)->first(); $quantity = $dayOutput ? (int)$dayOutput->daily_output : 0; $itemData[] = $quantity; } $series[] = [ 'name' => $itemName, 'data' => $itemData, ]; $data[$itemId] = $itemData; } return [ 'series' => $series, 'categories' => $dates, 'data' => $data, ]; } /** * 设置图表数据 * * @param array $series * @param array $categories * @return $this */ public function withChart(array $series, array $categories = []) { return $this->chart([ 'series' => $series, 'xaxis' => [ 'categories' => $categories, ], ]); } /** * 设置卡片内容 * * @param string $content * @return $this */ public function withContent($content) { return $this->content( <<

{$content}

总产出数量 HTML ); } }