<?php

namespace App\Http\Middleware;

use Closure, Constants;

class CheckSign
{

    protected $except = [
    ];

    /**
     * Handle an incoming request.
     * @param $request
     * @param Closure $next
     * @return mixed
     */

    public function handle($request, Closure $next)
    {


        $params = $request->all();

//        $secretKey = config('api.sign.secret_key');
//
//        $dealSign = md5('secret='.$secretKey.'&t='.$params['t']);
//        var_dump($dealSign);

        if (isset($params['debug_http']) && $params['debug_http'] == 911){
            return $next($request);
        }

        //参数规范性校验
        if(empty($params['t'])){
           return Response()->json(['code' => Constants::PARAMETER_ERROR, 'msg' => '参数错误，请检查传入参数的时间！', 'params' => $params]);
        }

        if(empty($params['sign'])){
            return Response()->json(['code' => Constants::PARAMETER_ERROR, 'msg' => '参数错误，请检查传入参数的签名！', 'params' => $params]);
        }

        //参数合法性校验
        $diff = time() - $params['t'];
        if($diff > 600){
            return Response()->json(['code' => Constants::PARAMETER_ERROR, 'msg' => '参数错误，时间戳已过期！', 'params' => $params]);
        }


        $secretKey = config('api.sign.secret_key');
        if(empty($secretKey)){
            return Response()->json(['code' => Constants::PARAMETER_ERROR, 'msg' => '参数错误，后台密钥丢失', 'params' => $params]);
        }

        $dealSign = md5('secret='.$secretKey.'&t='.$params['t']);
      //  var_dump($dealSign);exit();

        if($dealSign != $params['sign']){
            return Response()->json(['code' => Constants::PARAMETER_ERROR, 'msg' => '签名错误', 'params' => $params]);
        }

        return $next($request);
    }


}
