<?php

namespace App\Http\Middleware;

use Closure;
use Cookie;

class AlipayAuth
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $test = 0;
        if ($request->has('test') && $request->input('test') == 'bonan') {
            $test = 1;
        }

        $uid_cookie = Cookie::get(env('COOKIE_AUTH_WEB_WECHAT'));
        $h5_scheme = env('H5_SCHEME', 'https');
        $params = $request->except('_url');
        $url = str_replace('http://', $h5_scheme . '://', url()->current() . '?' . http_build_query($params));

        $send_order_id = $request->input('send_order_id');
        if($send_order_id){
            Cookie::queue('send_order_id',$send_order_id, env('U_COOKIE_EXPIRE'), null, null, false, false);
        }
        $distribution_channel_id = str_replace('site', '', explode('.', _domain())[0]);
        if(!is_numeric($distribution_channel_id)){
            $distribution_channel_id = decodeDistributionChannelId($distribution_channel_id);
        }
        if(!$distribution_channel_id){
            return response()->error('WAP_SYS_ERROR');
        }

        if (!$uid_cookie && $test == 0) {
            $uri = $request->input('_url');

            if(strpos($uri,'/yun/') !== false){
                $uri_send_order_id = (int)str_ireplace('/yun/','',$uri);
                Cookie::queue('send_order_id', $uri_send_order_id, env('U_COOKIE_EXPIRE'), null, null, false, false);
            }
            Cookie::queue('auth_redirect', urlencode($url), env('U_COOKIE_EXPIRE'));
            $redirect = $this->getAuthUrl();
            return redirect()->to($redirect);
        }

        $response = $next($request);

        if ($request->has('fromtype') && $request->input('fromtype')) {
            try {
                $from = $request->input('fromtype', 'main');
                Cookie::queue('from', $from);
                Redis::sadd('push:distribution_channel_id:' . $distribution_channel_id . 'from:' . $from . ':date:' . date('Y-m-d'), $uid_cookie);
                Redis::hincrby('customer:push:click:distribution_channel_id:' . $distribution_channel_id . 'from:' . $from, date('Y-m-d'), 1);
                Redis::sadd('wap_from_stats'.date('Y-m-d'),$distribution_channel_id.'-'.$from);
            } catch (\Exception $e) {

            }
        }
        return $response;
    }

    /**
     * @return string
     */
    public function getAuthUrl():string{
        $url = 'https://openauth.alipay.com/oauth2/publicAppAuthorize.htm?';
        $data = [
            'app_id'=>'2018081461071404',
            'scope'=>'auth_base',
            'redirect_uri'=>env('ALI_AUTH_URL')
        ];
        $url = $url.http_build_query($data);
        return $url;
    }
}
