<?php
declare (strict_types = 1);

namespace app\txx\middleware;

use app\txx\common\Sign;
use think\facade\Db;
use think\facade\Log;
use think\Response;

class CheckAuth
{
    /**
     * 处理请求
     *
     * @param \think\Request $request
     * @param \Closure       $next
     * @return Response
     */
    public function handle($request, \Closure $next)
    {
    	$request->isCx=0;
    	$request->uid=0;
    	$request->uname='';
        $param = $request->post();
	    $header = $request->header();
	    $check =$this->check($header,$param);
	    Log::write("IPAddr:".$request->server("REMOTE_ADDR"),"info");
	    Log::write("Action:".$request->server("REQUEST_URI"),"info");
	    Log::write("param:".json_encode($param),"info");
	    Log::write("header:".json_encode($header),"info");
	    if($check['code']==1){
	    	return json_show(104,$check['msg']);
		}
		$response = $next($request);
	    return $response;


    }
	//请求结束的回调(如果返回数据用的是app_show/error_show,即直接echo,则不会触发该方法)
	public function end(Response $response)
	{
		Log::info("response:{data}",["data"=>json_encode($response->getContent(),JSON_UNESCAPED_UNICODE)]);
	}
	/**数据接口签名验证
	* @param $data
	* @param $param
	 * @return array
	 */
    private  function check($data,$param){
        //check sign
        if (!isset($data['appid']) || !$data['appid']) {
            return ['code'=>1,'msg'=>'发送的应用参数不存在'];
        }
        $appinf =Db::name("act_company")->where(["app_id"=>$data['appid'],"is_del"=>0,"status"=>1])->findOrEmpty();
        if(empty($appinf)){
        	  return ['code'=>1,'msg'=>'发送的应用参数错误'];
        }
		$mege=["appid"=>$data['appid'],"noce"=>$data['noce']??'',"sign"=>$data['sign']??'',"timestamp"=>$data['timestamp']??''];
        $value =array_merge($mege,$param);
        $Sign=new Sign($appinf['app_id'],$appinf['app_key']);
        $result =$Sign->verifySign($value);
        return $result;
    }
}