<?php


namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
/**
 * 数据返回中间件
 * Class Response
 * @package SocialBird\Middleware\Middleware
 */
class Response
{
    /**
     * @param Request $request
     * @param Closure $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        //去除请求参数左右两边空格
        $params = $request->all();
        foreach($params as $key=>$value){
            if(!is_array($value)) {
                $params[$key] = trim($value);
            }
        }
        $request->replace($params);
        if($this->mTrans($request)) {
            DB::beginTransaction();
        }
        $response = $next($request);
        if ($response->getStatusCode()==200 && empty($response->exception)) {

            if($this->mTrans($request)) {
                DB::commit();
            }
            if($request->ajax() && !($response instanceof StreamedResponse)) {
//                $content = $this->isJson($content) ? json_decode($content, true) : $content;

               $content = json_encode([
                   'code' => 0,
                   'message' => 'success.',
                   'data' => $response->getOriginalContent()
               ]);

                // $content = json_encode($response->getOriginalContent());
                // $response->setContent($content);
            }

        }else{
            if($this->mTrans($request)) {
                DB::rollBack();
            }
            if(!$request->ajax() && !($response instanceof StreamedResponse)){
                $content = json_decode($response->getContent(),true);
                $response->setContent($content['message']??'');
            }
        }
        if(method_exists($response,'withHeaders')){
            $headersArr=$response->headers->all();
            $withHeadersArr=[
                'Access-Control-Allow-Origin'=>'*',
                'Access-Control-Allow-Credentials'=>'true',
                'Access-Control-Allow-Methods'=>'PUT, GET, POST, DELETE, OPTIONS',
                'Access-Control-Allow-Headers' => 'Content-Type,token,X-Requested-With,Authorization',
                'Access-Control-Expose-Headers' => '*'
            ];
            if(empty($headersArr['content-type'])){
                $withHeadersArr['Content-Type']=$request->ajax()?'application/json;charset:UTF-8':'text/html; charset=UTF-8';
            }
            $response->withHeaders($withHeadersArr);
        }
        return $response;
    }

    /**
     * 是否为json格式的字符串
     * @param $string
     * @return bool
     */
    private function isJson($string)
    {
        json_decode($string);
        return (json_last_error() == JSON_ERROR_NONE);
    }

    /**
     * 是否开启事务
     * @param Request $request
     * @return bool
     */
    private function mTrans($request){
        if(/*strtolower($request->method())!='get' && */config('database.transaction')){
            return true;
        }else{
            return false;
        }
    }

}
