| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137 |
- <?php
- namespace App\Module\Farm\AdminControllers\Metrics;
- use Dcat\Admin\Widgets\Metrics\Line;
- use Illuminate\Http\Request;
- use App\Module\Farm\Models\FarmDailyStats;
- use Carbon\Carbon;
- /**
- * 农场土地类型趋势图 - 多线折线图
- *
- * 参考UCore\DcatAdmin\Metrics\Examples\NewUsersDou实现
- * 每个土地类型一条线,支持时间范围选择
- */
- class FarmLandTrendChart extends Line
- {
- /**
- * 图表默认高度
- *
- * @var int
- */
- protected $chartHeight = 200;
- /**
- * 土地类型名称映射
- */
- protected $landTypeNames = [
- 1 => '普通土地',
- 2 => '红土地',
- 3 => '黑土地',
- 4 => '金色特殊土地',
- 5 => '蓝色特殊土地',
- 6 => '紫色特殊土地',
- ];
- /**
- * 初始化卡片内容
- *
- * @return void
- */
- protected function init()
- {
- parent::init();
- $this->title('土地类型趋势图');
- $this->dropdown([
- '7' => '最近7天',
- '15' => '最近15天',
- '30' => '最近30天',
- ]);
- }
- /**
- * 处理请求,获取数值
- *
- * @param Request $request
- *
- * @return mixed|void
- */
- public function handle(Request $request)
- {
- $days = $request->get('option', '7');
-
- // 获取指定天数的统计数据
- $stats = FarmDailyStats::where('stats_date', '>=', Carbon::now()->subDays($days))
- ->orderBy('stats_date', 'asc')
- ->get();
- if ($stats->isEmpty()) {
- // 如果没有数据,显示提示
- $this->withContent('暂无数据');
- $this->withChart([]);
- return;
- }
- // 准备图表数据
- $chartData = [];
- $totalLands = 0;
- // 遍历每种土地类型
- for ($type = 1; $type <= 6; $type++) {
- $field = "land_type_{$type}";
- $typeData = [];
- $hasData = false;
- foreach ($stats as $stat) {
- $value = $stat->$field ?? 0;
- $typeData[] = $value;
- if ($value > 0) {
- $hasData = true;
- }
- }
- // 只添加有数据的土地类型
- if ($hasData) {
- $chartData[$this->landTypeNames[$type]] = $typeData;
- $totalLands += array_sum($typeData);
- }
- }
- // 计算总土地数(取最新一天的数据)
- $latestStats = $stats->last();
- $currentTotal = 0;
- for ($type = 1; $type <= 6; $type++) {
- $field = "land_type_{$type}";
- $currentTotal += $latestStats->$field ?? 0;
- }
- // 设置卡片内容
- $this->withContent($currentTotal . '块');
-
- // 设置图表数据
- $this->withChart($chartData);
- }
- /**
- * 设置卡片内容
- *
- * @param string $content
- *
- * @return $this
- */
- public function withContent($content)
- {
- return $this->content(
- <<<HTML
- <div class="d-flex justify-content-between align-items-center mt-1" style="margin-bottom: 2px">
- <h2 class="ml-1 font-lg-1">{$content}</h2>
- <span class="mb-0 mr-1 text-80">总土地数</span>
- </div>
- HTML
- );
- }
- }
|