<?php

namespace components;


class ApiHandler
{

    protected static $_instance = null;

    static function getInstance()
    {
        if (is_null(self::$_instance)) {
            self::$_instance = new self;
        }

        return self::$_instance;
    }

    /**
     * @param string $message
     */
    public function log($message)
    {
        if (false) {
            //Log::info($message);
        }
    }

    public function get($uri, $params = array())
    {
        return $this->_do_request($uri, $params);
    }

    public function post($uri, $params)
    {
        return $this->_do_request($uri, $params, true);
    }

    /**
     * 生成签名
     *
     * @return array
     */
    private function _generate_signature()
    {
        $timestamp = time();

        app()->configure('key');
        $private_key = config('key.apiAuthPrivateKey');
        $openssl_util = new OpensslAuth();
        $sig = $openssl_util->generate_signature($timestamp, $private_key);

        return [$timestamp, $sig];
    }

    /**
     * 订单流程唯一 key
     */
    private function _get_user_unique_key()
    {
        if(isset($_COOKIE["trade_user_unique_key"])) {
            $session_id = $_COOKIE["trade_user_unique_key"];
        } else {
            $session_id = md5(time());
            setcookie('trade_user_unique_key', $session_id, 0, '/');
        }

        return $session_id;
    }

    /**
     * 生成url
     *
     * @param $uri
     * @return string
     */
    private function _generate_url($uri)
    {
        $host = 'https://doc.33.cn';

        $url = rtrim($host, '/') . '/' . ltrim($uri, '/');

        //调试使用
        $this->log("call api: {$url}");

        return $url;
    }

    /**
     * 请求接口
     *
     * @param $uri
     * @param $params
     * @param bool $is_post
     * @return mixed
     * @throws ErrorException
     * @throws NotFoundException
     * @throws ParamException
     * @throws UserException
     * @throws UserLoglessException
     */
    private function _do_request($uri, $params, $is_post = false)
    {
        $url = $this->_generate_url($uri);

        var_dump('url:---'.$url);

        if (!$is_post) {
            if ($params) {
                $p_str = '';
                $comma = '';
                foreach ($params as $k => $v) {
                    $p_str .= $comma . $k . '=' . $v;
                    $comma = '&';
                }

                $url = $url . '?' . $p_str;
            }
        }

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

        if ($is_post) {
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($params));
        }
        $output = curl_exec($ch);


        return $output;
    }

}