<?php

namespace App\Admin\Metrics\Statistics;

use Dcat\Admin\Widgets\Metrics\Line;
use Illuminate\Http\Request;
use App\Models\PrescriptionModel;
use Dcat\Admin\Admin;
use Dcat\Admin\Widgets\Metrics\Bar;
use Illuminate\Support\Facades\DB;
use Carbon\Carbon;
use Illuminate\Support\Facades\Log;
class PrescriptionChart extends Bar
{
    /**
     * 初始化卡片内容
     *
     * @return void
     */
    protected function init()
    {
        parent::init();
        $date = date('Y-m-d',strtotime('-1 day'));
        $this->title($date .'开方数量');
    }

    /**
     * 处理请求
     *
     *
     * @return mixed|void
     */
    public function handle(Request $request)
    {
        // $query_time = date('Y-m-d 23:59:59');
        // $prescription_total = PrescriptionModel::where('created_at','<=',$query_time)->count();

        $yesterdayEnd = Carbon::yesterday()->endOfDay(); // 昨天的23:59:59
        // Log::info('参数：' . $yesterdayEnd->format('Y-m-d H:i:s')); // 输出日志信息

        $eightDaysAgoStart = clone $yesterdayEnd;
        $eightDaysAgoStart->subDays(7)->startOfDay(); // 八天前的00:00:00
        
        // 创建包含过去7天日期的完整数组
        $datesRange = [];
        for ($date = clone $eightDaysAgoStart; $date->lte($yesterdayEnd); $date->addDay()) {
            $datesRange[$date->format('Y-m-d')] = 0; // 初始化所有日期为0
        }

        $prescriptionCounts = DB::table('prescription')
            ->select(
                DB::raw('DATE(created_at) as date'), // 只获取日期部分
                DB::raw('COUNT(*) as prescriptions_count') // 计算每一天的总数
            )
            ->whereBetween('created_at', [$eightDaysAgoStart, $yesterdayEnd]) // 筛选从昨天23:59:59起过去七天的数据
            ->groupBy('date') // 按日期分组
            ->orderBy('date') // 按日期排序
            ->get(); // 执行查询并获取结果
        
        
        

        // 将查询结果合并到日期范围数组中
        foreach ($prescriptionCounts as $day) {
            if (isset($datesRange[$day->date])) {
                $datesRange[$day->date] = $day->prescriptions_count;
            }
        }

        // Log::info('结果：'.json_encode($datesRange));
        $labels = array_keys($datesRange);
        $data = array_values($datesRange);
        // 卡片内容
        $this->withContent($data[6]);
        // 图表数据
        $this->withChart([
            [
                'name' => '近七日开方量',
                'data' => $data,
            ],
        ]);

           
    }

    /**
     * 设置图表数据.
     *
     *
     * @return $this
     */
    public function withChart(array $data)
    {
        return $this->chart([
            'series' => $data,
        ]);
    }



    /**
     * 设置卡片内容.
     *
     * @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>
    
</div>
HTML
        );
    }
}
