<?php


namespace App\Http\Middleware;


use App\AdminUser;
use Closure;
use Illuminate\Routing\Route;
use App;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;

class AdminLog
{
    /**
     * @param \Illuminate\Http\Request $request
     * @param Closure $next
     */
    public function handle($request, Closure $next)
    {
        $parameters = $request->route()->parameters;

        $admin=$request->session()->get('admin');
        $admin_id = $admin->id;


        //写日志
        $name = $parameters['name'] ?? '';
        if (!empty($name)||$request->isMethod('post')) {
            $id = $parameters['id'] ?? 0;
            $route =  $request->route();
            $current_url = $route->methods[0].":".$route->uri();
            $data = [
                'admin_id' => $admin_id,
                'create_at' => date("Y-m-d H:i:s"),
                'update_at' => date("Y-m-d H:i:s"),
                'content' => json_encode($request->all()),
                'url' => $current_url,
                'explain' => $id
            ];
            DB::table('agent.dbo.admin_log')->insert($data);
        }

        //设置locale
        if (isset($admin->locale)) {
            App::setLocale($admin->locale);
        }

        //定时刷新admin资料
        $adminKey="adminuser_$admin_id";

        if(!Redis::exists($adminKey)){
            $admin = AdminUser::where('id', $admin_id)->first();
            $request->session()->put('admin', $admin);
            Redis::set($adminKey,json_encode($admin));
            Redis::expire($adminKey,600);
        }

        $adminChannels=json_decode($admin->channel,true);
        $request->session()->put('admin_channels', $adminChannels);

        $key='AllChannels2';
        if(!Redis::exists($key)) {
            $Channels = DB::table('QPPlatformDB.dbo.ChannelPackageName')
            ->pluck('Remarks', 'Channel')->toArray();
            Redis::set($key,json_encode($Channels));
            Redis::expire($key, 600);
        }else{
            $Channels=json_decode(Redis::get($key),true);
        }
        $request->session()->put('all_channels', $Channels);

        return $next($request);
    }
}
