<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use App\Lib\JwtService;
/**
 * 不需要校验登录的接口走这里鉴权
 */
class RegisterMiddleware
{
    // 是否启用调试模式
    protected $debug = false;
    // 不参与签名的变量
    protected $not_sign_key = ['sign', 'sign_debug', 'format'];

    public $platformList = [];
    public function handle($request, Closure $next)
    {
        $allParams = $request->all();
        unset($allParams['s']);

        $platform = $allParams['platform'] ?? '';
        $this->platformList = config('config.platform_list');
        if (!array_key_exists($platform, $this->platformList)) {
            $data = [
                'code' => 50002,
                'msg' => '非法请求,请提交正确的platform'
            ];
            return response()->json($data);
        }

        $sign = $allParams['sign'] ?? '';
        if (empty($sign)) {
            $data = [
                'code' => 50002,
                'msg' => '签名信息不存在'
            ];
            return response()->json($data);
        }

        $this->debug = $allParams['sign_debug'] ?? false;

        //获取参数
        $filterParams = [];
        foreach ($allParams as $key => $val) {
            if (in_array($key, $this->not_sign_key) || $val === "" || $val == "undefined") {
                continue;
            } elseif (is_array($allParams[ $key ])) {
                $filterParams[ $key ] = json_encode($allParams[ $key ], JSON_UNESCAPED_UNICODE);
            } else {
                $filterParams[ $key ] = $allParams[ $key ];
            }
        }

        //参数排序
        ksort($filterParams);
        reset($filterParams);

        //参数拼接
        $argStr = '';
        foreach ($filterParams as $key => $val) {
            $argStr .= $key . "=" . trim($val, ' ') . "&";
        }
        $argStr .= $this->platformList[$platform];

        //参数加密
        $serverSign = md5($argStr);

        //获取到的签名和参数生成的签名比较
        if (trim(strtolower($serverSign)) != trim(strtolower($sign))) {
            $data = [
                'code' => 50002,
                'msg' => '签名校验未通过'
            ];

            if ($this->debug) {
                $data['msg'] = '非法请求，签名不正确' . ", 服务器端签名为:$serverSign, 参数字符串：$argStr";
            }

            return response()->json($data);
        }

        $request->attributes->add(['platform' => $platform, 'request_ip' => $request->ip()]);
        return $next($request);
    }


}
