<?php
/**
 * Created by PhpStorm.
 * User: zhl
 * Date: 2025/7/4
 * Time: 11:14
 */
namespace App\Console\Commands\Statistics;

use App\Models\Project\ProjectFlow;
use App\Services\UpyunService;
use Illuminate\Console\Command;
use Illuminate\Support\Str;

class Flow extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'project_flow_statistics';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '项目流量统计';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct(); // 确保调用父类构造函数
    }

    public function handle()
    {
        $this->cdnStatistics();
        return true;
    }

    public function cdnStatistics()
    {
        $class = new UpyunService();

        list($start_at, $end_at) = $this->getTime();
        $date = date('Y-m-d', strtotime($end_at));
        echo 'start_at: ' . $start_at . PHP_EOL;
        echo 'end_at: ' . $end_at . PHP_EOL;
        $result = $class->realTimeStatistics($start_at, $end_at);

        file_put_contents(storage_path('logs/flow/' . date('YmdHis', strtotime($start_at)) . '.json'), $result);
//        $result = file_get_contents(storage_path('logs/flow/' . date('YmdHis', strtotime($start_at)) . '.json'));
        $result = json_decode($result, true);
        $flow = [];
        if (FALSE == empty($result['data']) && is_array($result['data'])) {
            // 结算 所有项目 流量
            foreach ($result['data'] as $item) {
                if (Str::startsWith($item['key'], '/upload/p/')) {
                    $tmp = explode('/', $item['key']);
                    $flow[$tmp[3]] = FALSE == empty($flow[$tmp[3]]) ? $flow[$tmp[3]] + $item['val'] : $item['val'];
                }
            }
        }

        ksort($flow);
        $total_flow = 0;
        foreach ($flow as $project_id=>$val) {
            ProjectFlow::flowInsert($project_id, $date, $val, $end_at);
            $total_flow += $val;
        }
        echo 'total project: ' . count($flow) . PHP_EOL;
        echo 'total flow: ' . $total_flow . PHP_EOL;
        return true;
    }

    /**
     * @return array
     */
    public function getTime()
    {
        $last_at_log = ProjectFlow::orderBy('last_at', 'desc')->first();
        $today = date('Y-m-d 00:00:00');
        $start_at = $last_at_log ? $last_at_log->last_at : $today;
        if (strtotime($start_at) < strtotime($today))
            $start_at = $today;
        $end_at = date('Y-m-d H:i:s', time() - 1);
        return [$start_at, $end_at];
    }
}