<?php

namespace App\Http\Middleware;

use App\Cache\Push\PushCache;
use App\Modules\Push\Services\PushService;
use App\Modules\Report\Services\ReportService;
use App\Modules\SendOrder\Services\SendOrderService;
use App\Modules\User\Services\QappUserService;
use App\Modules\User\Services\UserService;
use Closure;
use Exception;
use Illuminate\Http\Request;
use Tymon\JWTAuth\Exceptions\JWTException;
use Tymon\JWTAuth\Exceptions\TokenExpiredException;
use Tymon\JWTAuth\Middleware\BaseMiddleware;

class QuickAppGetUserFromToken extends BaseMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param \Illuminate\Http\Request $request
     * @param \Closure                 $next
     * @return mixed
     */
    public function handle(Request $request, Closure $next)
    {
        // 获取头部信息
        $package     = $request->header('x-package', '');
        $provider    = $request->header('x-provider', '');
        $regId       = $request->header('x-regid', '');
        $pushId      = $request->header('x-pushid', 0);
        $sendOrderId = $request->header('send-order-id', 0);

        // 判断是否登录
        if (!$token = $this->auth->setRequest($request)->getToken()) {
            return response()->error('QAPP_NOT_LOGIN');
        }
        try {
            $user = $this->auth->authenticate($token);
            if ($sendOrderId) {
                try {
                    $result = SendOrderService::recordUserSendOrder($user->id, $sendOrderId);
                    if($result){
                        UserService::setUserSendOrder($user->id, $sendOrderId);
                    }
                } catch (\Exception $e) {
                    myLog('QuickAppGetUserFromToken-sendOrderId')->error($e);
                }
            }

            // 设置全局信息
            (new QappUserService)->setGolableUser($user->id, $package);
        } catch (TokenExpiredException $e) {
            return response()->error('QAPP_TOKEN_ERROR');
        } catch (JWTException $e) {
            return response()->error('QAPP_TOKEN_ERROR');
        } catch (Exception $e) {
            myLog('QuickAppGetUserFromToken')->info($e->getMessage());
            return response()->error('QAPP_NOT_LOGIN');
        }

        // 更新用户reg_id
        $uid = $user->id;
        PushService::setUserRegId($uid, $regId, $provider, $package);

        // 推送pv、uv统计
        if ($pushId) {
            PushCache::incrPushPv($pushId, date('Ymd'));
            PushCache::zAddPushUv($pushId, date('Ymd'), $uid);
        }

        // 头条次留回传
        ReportService::reportActive($uid);

        return $next($request);
    }
}
