<?php
// 应用公共文件

use Firebase\JWT\JWT;
use think\Exception;
use think\facade\Cache;

/**
     * 获取jwt-token
     */
    function signToken($param)
    {
        $key   = 'Jmjk@886!&*123';          // 这里是自定义的一个随机字串，应该写在config文件中的，解密时也会用，相当    于加密中常用的 盐  salt
        $token = array(
            "iss"   => $key,                // 签发者 可以为空
            "aud"   => '',                  // 面象的用户，可以为空
            "iat"   => time(),              // 签发时间
            "nbf"   => time()+3,            // 在什么时候jwt开始生效  （这里表示生成100秒后才生效）
            "exp"   => time()+600,          // token 过期时间 3天259200
            "data"  => [                    // 记录的userid的信息，这里是自已添加上去的，如果有其它信息，可以再添加数组的键值对
                'param' => $param,
            ]
        );
        $jwt = JWT::encode($token, $key, "HS256");  // 根据参数生成了 token
        return $jwt;
    }


    /**
     * 验证jwt-token
     */
    function checkToken($token)
    {
        $key    = 'Jmjk@886!&*123';
        $status = array("code" => 777);
        try {
            JWT::$leeway = 86400;                                   // 当前时间减去60，把时间留点余地
            $decoded = JWT::decode($token, $key, array('HS256'));   // HS256方式，这里要和签发的时候对应
            $arr = (array)$decoded;

            $res['code'] = 0;
            $res['data'] = $arr['data'];
            return $res;
        } catch(\Firebase\JWT\SignatureInvalidException $e) {       // 签名不正确
            $res['code'] = 101;
            $status['msg']  = "签名不正确";
            return $status;
        } catch(\Firebase\JWT\BeforeValidException $e) {            // 签名在某个时间点之后才能用
            $status['msg']  = "token失效";
            return $status;
        } catch(\Firebase\JWT\ExpiredException $e) {                // token过期
            $status['msg']  = "token失效";
            return $status;
        } catch(Exception $e) {                                     // 其他错误
            $status['msg']  = "未知错误";
            return $status;
        }
    }


    /**
     * authtoken
     */
    function get_authtoken()
    {
        $authtoken = Cache::get('authtoken') ?? '';
        if( ! $authtoken ) {
            $params   = config('translate.user');
            $url      = config('translate.request_url.get_authtoken_url');
            $response = curl_post_request($url , $params);
            if( ! $response) {
                return false;
            }

            $result    = json_decode($response , true);
            $authtoken = $result['data']['authtoken'] ?? '---';
            /**
             * 设置缓存
             */
            Cache::set('authtoken' , $authtoken , config('translate.expire.authtoken_expire'));
            return $authtoken;
        }
        \think\facade\Log::info('Translate-authtoken：'.$authtoken);
        return $authtoken;
    }



    /**
     * curl get 请求
     */
    function curl_get_request($url)
    {
        $authtoken = get_authtoken();
        $curl_con  = curl_init();

        curl_setopt($curl_con, CURLOPT_URL , $url);
        curl_setopt($curl_con, CURLOPT_HEADER, false);
        curl_setopt($curl_con, CURLOPT_CUSTOMREQUEST, 'GET');
        curl_setopt($curl_con, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl_con, CURLOPT_CONNECTTIMEOUT, 5);
        curl_setopt($curl_con, CURLOPT_FOLLOWLOCATION, true);             // 解决curl返回301

        curl_setopt($curl_con, CURLOPT_HTTPHEADER , array(
                "Content-Type: application/json;charset=utf-8",
                "Authorization: Token $authtoken"
            )
        );

        $res    = curl_exec($curl_con);
        $status = curl_getinfo($curl_con);

        curl_close($curl_con);

        if (isset($status['http_code']) && 200 == $status['http_code']) {
            return $res;
        } else {
            return false;
        }
    }


    /**
     * curl post 请求
     */
    function curl_post_request($url , $params , $authtoken = '')
    {
        $data     = json_encode($params , JSON_UNESCAPED_UNICODE);
        $curl_con = curl_init();

        curl_setopt($curl_con, CURLOPT_URL , $url);
        curl_setopt($curl_con, CURLOPT_HEADER, false);
        curl_setopt($curl_con, CURLOPT_CUSTOMREQUEST, 'POST');
        curl_setopt($curl_con, CURLOPT_POSTFIELDS, $data);
        curl_setopt($curl_con, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl_con, CURLOPT_CONNECTTIMEOUT, 5);
        curl_setopt($curl_con, CURLOPT_FOLLOWLOCATION, true);             // 解决curl返回301
        if($authtoken) {
            curl_setopt($curl_con, CURLOPT_HTTPHEADER , array(
                    "Content-Type: application/json;charset=utf-8" ,
                    "Authorization: Token $authtoken"
                )
            );
        } else {
            curl_setopt($curl_con, CURLOPT_HTTPHEADER , array(
                    "Content-Type: application/json;charset=utf-8"
                )
            );
        }

        $res    = curl_exec($curl_con);
        $status = curl_getinfo($curl_con);
        //return $status;
        curl_close($curl_con);

        \think\facade\Log::info(__FUNCTION__.': res='.$res);

        if (isset($status['http_code']) && 200 == $status['http_code']) {
            return $res;
        } else {
            return false;
        }
    }
