<?php


namespace App\Services;


use App\Log;
use Exception;
use Illuminate\Support\Facades\Redis;
use App\Traits\ServiceAppAop;


class LogService
{
    use ServiceAppAop;
    protected $modelClass=Log::class;
    static public function log($class, $method, $description, $id_user = null,$type='log')
    {
        $passingMethods=config('logging.passing_methods');
        foreach ($passingMethods as $passingMethod){
            if($passingMethod==$method)return;
        }
        if (!$id_user) {
            $id_user = '';
            $user = auth()->user();
            if ($user) $id_user = $user['id'];
        }
        $log=new Log([
            'class' => $class,
            'method' => $method,
            'description' => $description,
            'id_user' => $id_user,
            'ip' => request()->ip(),
            'type' => $type,
        ]);
        try {
            Redis::LLEN('LOGS');
        } catch (Exception $e) {
            //redis出现异常直接保存到数据库中
            $log->save();
            return;
        }
        $date = date('Y-m-d H:i:s');
        $log['created_at']=$date;
        $log['updated_at']=$date;
        Redis::LPUSH('LOGS', $log);
    }

    public static function syncRedisLogs()
    {

        try {
            Redis::LLEN('LOGS');
        } catch (Exception $e) {
            session()->flash('danger', 'Redis服务异常无法正常同步，最新日志已直接保存到数据库中，但已缓存的日志无法同步，请检查Redis是否正常，然后再尝试同步');
            return;
        }
        $data = [];
        $length = 0;
        while (Redis::LLEN('LOGS') > 0) {
            $log = Redis::LPOP('LOGS');
            $arr = json_decode($log);
            $description = (is_string($arr->description)?$arr->description:json_encode($arr->description))??'';
            if ($length + strlen($description) > 1024 * 512) {
                Log::query()->insert($data);
                $length = 0;
                $data = [];
            }
            $length = $length + strlen($description);
            $data[] = [
                'class' => $arr->class,
                'id_user' => $arr->id_user,
                'ip' => $arr->ip,
                'method' => $arr->method,
                'description' => $description,
                'created_at' => $arr->created_at,
                'updated_at' => $arr->updated_at,
            ];
        }
        if ($data) {
            Log::query()->insert($data);
        }
    }
}
