<?php
namespace common\helpers\http;

use yii\base\BaseObject;
use yii\httpclient\Client;

class LingYunGongApi {

    const CACHE_TOKEN_KEY = 'cashTokenKey_%s';

    /**
     * 请求方法
     */
    const HTTP_METHOD_POST = 'post';
    const HTTP_METHOD_GET = 'get';

    /**
     * http client
     * @var null
     */
    private static $_client = null;


    /**
     * 获取http client 对象
     * @return null|Client
     */
    public static function client(){
        if(is_null(self::$_client)){
            self::$_client = new Client();
        }
        return self::$_client;
    }

    /**
     * request
     * @return \yii\httpclient\Request
     */
    public static function request(){
        return self::client()->createRequest();
    }

    /**
     * POST请求
     * @param $url
     * @param $data
     * @param array $headers
     * @return mixed
     */
    public static function post($url, $data, array $headers=[]){
        $query = self::request()
            ->setMethod(self::HTTP_METHOD_POST);
        if( $headers ) {
            $query->addHeaders($headers);
        }

        $query->setFormat(Client::FORMAT_JSON);
        $query->setUrl($url)
            ->setData($data);
        unset($data);
        return $query->send();
    }

    /**
     * GET请求
     * @param $url
     * @param array $data
     * @param array $headers
     * @return \yii\httpclient\Response
     */
    public static function get($url, array $data = [], array $headers=[]){
        $query = self::request()
            ->setMethod(self::HTTP_METHOD_GET);
        if( $headers ) {
            $query->addHeaders($headers);
        }
        $query->setUrl($url);
        if($data){
            $query->setData($data);
        }
        unset($data);
        return $query->send();
    }

    /**
     * 获取token
     * @return mixed|string
     */
    public static function getAuthToken() {
        $authTokenClientId = \Yii::$app->params['http']['lingYunGongApi']['authToken']['clientId'];
        $cacheKey = sprintf(self::CACHE_TOKEN_KEY, $authTokenClientId);
        $cache = \Yii::$app->cache;
        $token = $cache->get($cacheKey);
        if( $token ) return $token;

        $tokenData = self::_apiAuthToken();
        if ( !$tokenData ) return '';

        $token = $tokenData['access_token'] ?? '';
        $expiresIn = $tokenData['expires_in'] ?? 0;
//        $tokenType = $tokenData['token_type'];
        $cacheTime  = $expiresIn - 60;
        if( $cacheTime > 0 && $token ) {
            \Yii::$app->cache->set($cacheKey, $token, $cacheTime);
        }
        return $token;
    }


    /**
     * api接口获取token
     * @return false
     */
    private static function _apiAuthToken() {
        $host = \Yii::$app->params['http']['lingYunGongApi']['host'];
        $authTokenPath = \Yii::$app->params['http']['lingYunGongApi']['authToken']['path'];
        $authTokenClientId = \Yii::$app->params['http']['lingYunGongApi']['authToken']['clientId'];
        $requestUrl = $host . $authTokenPath;

        $data = [
            'grant_type' => 'client_credential',
            'client_secret' => 'secret!',
            'client_id' => $authTokenClientId,
        ];


        $response = self::post($requestUrl, $data, ['content-type' => 'application/json']);
        if($response->isOk){
            return $response->data;
        } else {
            return false;
        }
    }

    /**
     * 判断是否上传了身份证信息
     * @param string $idCard
     */
    public static function hasIdCardInfo(string $idCard) {
        $token = self::getAuthToken();
        if( !$token ) return false;

        $host = \Yii::$app->params['http']['lingYunGongApi']['host'];
        $authTokenPath = \Yii::$app->params['http']['lingYunGongApi']['hasIdCardInfoPath'];
        $requestUrl = $host . sprintf($authTokenPath, $idCard);

        $response = self::get($requestUrl, [], [
            'Authorization' => sprintf('Bearer %s', $token)
        ]);
        if($response->isOk){
            return $response->data;
        } else {
            return false;
        }
    }
}