<?php


namespace app\common\controller;

use Firebase\JWT\JWT;
use Firebase\JWT\Key;
use app\BaseController;
use app\common\util\Result;
use EasyWeChatComposer\EasyWeChat;
use app\common\exception\CatchException;

class JwtBaseController extends BaseController
{

    protected $failException = true;

    /**
     * $key jwt HS256 key
     *
     * @var string
     */
    protected $key;

    /**
     * $table 当前使用的表
     *
     * @var mixed
     */
    protected $table;

    /**
     * $model 当前使用的模型
     *
     * @var \think\Model
     */
    protected $model;

    /**
     * $wechat 微信小程序api实例
     *
     * @var \EasyWeChat\MiniProgram\Application
     */
    private static $_wechat;

    /**
     * 设置jwt密钥
     *
     * @param mixed $key
     * 
     * @return void
     */
    protected function setKey($key) {
        $this->key = $key;
    }

    /**
     * 验证token
     *
     * @return void
     */
    public function valid()
    {
        // 允许 Authorization 头部通过 cors
        $jwt = $this->request->header('Authorization');
        if (empty($jwt)) {
            throw new CatchException("未授权用户", 600);
        }

        $jwt = str_replace('Bearer ', '', $jwt);
        // try decode
        $this->decodeJwt($jwt);
        return Result::rest(true);
    }

    /**
     * 默认参数
     *
     * @return mixed
     */
    protected function params($validator = null, $name = '')
    {
        $params = $this->request->param($name, null, 'trim');
        // 尝试校验
        if (!is_null($validator)) {
            $this->validate($params, $validator);
        }
        return $params;
    }

    protected function only(array $names)
    {
        return $this->request->only($names);
    }

    /**
     * encodeJwt
     *
     * @param array|\stdClass $payload
     *
     * @return string
     */
    protected function encodeJwt($payload)
    {
        return JWT::encode($payload, $this->key, 'HS256');
    }

    /**
     * decodeJwt
     *
     * @param string $jwt
     *
     * @return \stdClass
     */
    protected function decodeJwt($jwt)
    {
        return JWT::decode($jwt, new Key($this->key, 'HS256'));
    }

}