<?php

namespace App\Http\Controllers\Xchengxu;
use Illuminate\Routing\Controller;
use App\Modules\User\Models\Xcxuser;
use JWTAuth;
class BaseController extends Controller
{

    /**
     * 公众号接口签名密钥
     * @var string
     */
    protected $secret_key = 'Uv%vkPI5K8Opqoww';


    protected function checkUid(){
        if(!$this->getAuthenticatedUser()) return false;
        return true;
    }

    public function __get($name)
    {
        static $user =null;
        if(is_null($user)) $user =  $this->getAuthenticatedUser();

        if($name == '_user_info'){
            return $user;
        }
        if($name == 'uid'){
            return $user->id;
        }
        if($name == 'distribution_channel_id'){
            return $user->distribution_channel_id;
        }
        if($name == 'openid'){
            $xcx_user = Xcxuser::where('uid',$user->id)->select('openid')->first();
            return $xcx_user->openid;
        }
        return null;
    }

    public function getAuthenticatedUser(){
        try {
            if (! $user = JWTAuth::parseToken()->authenticate()) {
                return false;
            }
        } catch (\Tymon\JWTAuth\Exceptions\TokenExpiredException $e) {
            return false;
            //return response()->json(['token_expired'], $e->getStatusCode());
        } catch (\Tymon\JWTAuth\Exceptions\TokenInvalidException $e) {
            return false;
            //return response()->json(['token_invalid'], $e->getStatusCode());
        } catch (\Tymon\JWTAuth\Exceptions\JWTException $e) {
            return false;
            //return response()->json(['token_absent'], $e->getStatusCode());
        }

        return $user;
    }

    public function checkSign($param){
        if(!isset($param['sign'])) return false;
        if(empty($param['sign'])) return false;

        return $param['sigin'] == _sign($param,$this->secret_key);
    }
}
