<?php

namespace App\Http\Middleware;

use App\Consts\SysConsts;
use Closure;

class CheckSign
{
    /**
     * Handle an incoming request.
     * changeLog: 2022-07-13
     * - 新版签名不使用device_info参与
     * - 为了和已经上架的快应用保持兼容，现在，两种签名方法通过一种就可以认为是签名通过
     *
     * @param \Illuminate\Http\Request $request
     * @param \Closure                 $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $key       = 'a!A&AFRWT65Nb3NlklezUiqHyQAA@Z8M';

        \Log::info('[CheckSign]请求的request参数:', $request->all());
        if($this->oldSignPass($request, $key) || $this->newSignPass($request, $key)) {
            return $next($request);
        } else {
            return response()->error('QAPP_SIGN_ERROR');
        }
    }

    private function oldSignPass($request, $key) {
        $params    = $request->except(['_url']);
        $timestamp = $request->post('timestamp', 0);
        $sign      = $request->post('sign', '');
        $backendSign = _sign($params, $key);
//         \Log::info('[CheckSign]旧版校验sign:', [
//             'front_sign' => $sign,
//             'backend_sign' => $backendSign,
//             'device_no' => $request->input('device_no', ''),
//             'X-Version' => $request->header('X-Version', ''),
//             'package' => $request->input('package', ''),
//         ]);
        if ($timestamp && time() - $timestamp <= (SysConsts::ONE_HOUR_SECONDS * 10) && $sign == $backendSign) {
//             \Log::info('[CheckSign]旧版校验通过');
            return true;
        } else {
//             \Log::info('[CheckSign]旧版校验没有通过');
            return false;
        }
    }

    private function newSignPass($request, $key) {
        $params = $request->except(['_url', 'device_info']);
        $timestamp = $request->post('timestamp', 0);
        $sign      = $request->post('sign', '');
        $backendSign = _sign($params, $key);
//         \Log::info('[CheckSign]新版校验sign:', [
//             'front_sign' => $sign,
//             'backend_sign' => $backendSign,
//             'device_no' => $request->input('device_no', ''),
//             'X-Version' => $request->header('X-Version', ''),
//             'package' => $request->input('package', ''),
//         ]);
        if ($timestamp && time() - $timestamp <= (SysConsts::ONE_HOUR_SECONDS * 10) && $sign == $backendSign) {
//             \Log::info('[CheckSign]新版校验通过');
            return true;
        } else {
//             \Log::info('[CheckSign]新版校验没有通过');
            return false;
        }
    }
}
