<?php

namespace App\Http\Middleware;

use App\Lib\JwtService;

use App\Models\FrontUserModel;
use App\Models\AdminUserModel;
use Closure;
use Illuminate\Support\Facades\Redis;
use Symfony\Component\HttpFoundation\Response;
use App\Models\LoginCacheModel;

class VerifyTokenMiddleware
{
    protected $platformList = [];

    protected $notCheckStoreStatus = [
        'business/info', // 获取商家信息
        'business/apply', // 商家申请开店
        'business/apply/info', // 查看商家开店申请的信息
        'file/getOssAccessToken', // 获取阿里云oss临时上传凭证
        'area/list', // 获取省市区乡地址联动
        'logout', // 退出登录
    ];

    /**
     * Handle an incoming request.
     *
     * @param \Illuminate\Http\Request $request
     * @param \Closure $next
     */
    public function handle($request, Closure $next)
    {
        $result = [
            'code' => 0,
            'msg' => '成功',
            'data' => null,
        ];

        $this->platformList = config('config.platform_list');
        $platform = $request->input('platform', '');
        if (!array_key_exists($platform, $this->platformList)) {
            $result['code'] = 50002;
            $result['msg'] = '非法请求';
            return response()->json($result);
        }

        $userModel = new AdminUserModel();
        $debug = $request->input('debug', '');
        if ($debug == 'yihuoapi.eoffcn.com.debug') {
            // debug模式快速传参定位问题
            $inputUserId = $request->input('id', 1);
            $userInfo = $userModel->findDataWithField(['id' => $inputUserId]);
            if (empty($userInfo)) {
                return response()->json(['code' => 50001, 'msg' => '用户不存在']);
            }
        } else {
            $token = $request->header('Authorization');
            if (!$token) {
                return response()->json(['code' => 50001, 'msg' => '请先登录~']);
            }

            //校验登录信息,解密出用户信息，供后台使用。
            $verifyRet = JwtService::verifyToken($token, $platform);
            if (false == $verifyRet) {
                return response()->json(['code' => 50001, 'msg' => '请先登录~']);
            }
            if ($verifyRet->id == 0) {
                return response()->json(['code' => 50001, 'msg' => '请先登录~']);
            }

            $type = $platform == 'web' ? 1 : 2;

            $LoginCacheModel = new LoginCacheModel();
            $ret = $LoginCacheModel->findData(['uid'=>$verifyRet->id, 'type'=>$type]);
            if(empty($ret)){
                return response()->json(['code' => 50001, 'msg' => '请先登录~']);
            }

//            $userInfo['id'] = $verifyRet->id;
//            $userInfo['phone'] = $verifyRet->phone;

            $userInfo = $userModel->findDataWithField(['id' => $verifyRet->id]);
            if (empty($userInfo)) {
                return response()->json(['code' => 50001, 'msg' => '用户不存在']);
            }
        }
        // 信息注册
        $request->attributes->add(['user_info' => $userInfo]);

        return $next($request);
    }

    /**
     * @param $request
     * @param $platform
     */
    protected function verify_token($request, $platform)
    {
        $result = [
            'res' => false,
            'msg' => '',
            'data' => null,
        ];

        $token = $request->header('Authorization', '');
        if ($token === '') {
            $result['msg'] = '无token信息';
            return $result;
        }

        $secret = config('config.platform_login_secret');
        $tokenInfo = (array)JWTService::verifyToken($token, $secret[$platform]);
        if (empty($tokenInfo) || empty($tokenInfo['id'])) {
            $result['msg'] = '已过期,请重新登录';
            return $result;
        }

        if (!empty($request->input('id')) && ($tokenInfo['id'] != $request->input('id'))) {
            $result['msg'] = '非法请求,用户身份有误,请重新登录';
            return $result;
        }

        // 登录状态获取
        $cacheKey = 'token:' . $platform . ':' . $tokenInfo['id'];
        $tokenCache = Redis::get($cacheKey);
        $tokenCache = json_decode($tokenCache, true);

        // 登录状态验证, 缓存不存在或catch的iat和token的iat不对等, 重新登录
        if (!$tokenCache || $tokenCache['iat'] < $tokenInfo['iat']) {
            $result['msg'] = '已退出,请重新登录';
            return $result;
        }

        // 登录互踢
        if ($tokenCache['iat'] > $tokenInfo['iat']) {
            $result['msg'] = '用户在新设备登录,当前状态已失效';
            return $result;
        }

        $result['res'] = true;
        $result['data'] = $tokenInfo;
        return $result;
    }

}


