<?php
namespace Our;

use Error\CodeConfigModel;
use Error\ErrorModel;
use Zend\Json\Server\Error;

class WechatCommon
{

    protected $appid;
    protected $secret;
    protected $grantType;

    function __construct()
    {
        $this->appid = ArrayConst::wechatInfo['appid'];
        $this->secret = ArrayConst::wechatInfo['secret'];
        $this->grantType = 'client_credential';
        if ($this->appid == '' || $this->secret == '') {
            ErrorModel::throwException(CodeConfigModel::emptyWxSetting);
        }
    }


    public function init()
    {

    }


    /**
     *  获取access_token
     */
    public function getAccessToken()
    {
//小程序账号
        $memberRedis = \Redis\Db0\MemberRedisModel::getInstance();
        $accessToken = $memberRedis->tableCacheGet('wechatAccessToken');
        if (!$accessToken) {
            $url = Common::format(PathConst::wxTakeAccessUrl, $this->grantType, $this->appid, $this->secret);
            $access_token = $this->httpsRequest($url);
            if (isset($access_token['errcode'])) ErrorModel::throwException(CodeConfigModel::getWxAccessTokenFail);
            $memberRedis->tableCacheSet('wechatAccessToken', $access_token['access_token'], ApiConst::takeAccessTokenLimit);
            return $access_token['access_token'];
        } else {
            return $accessToken;
        }


    }


    /**
     *  不转义中文的json_encode
     */
    protected function myJsonEncode($array)
    {
        if (version_compare(PHP_VERSION, '5.4.0', '<')) {
            foreach ($array as $key => $value) {
                if (!is_array($value)) {
                    $jsonstr[$key] = urlencode($value);
                } else {
                    $jsonstr[$key] = urlencode(my_json_encode($value));
                }
            }
            $jsonstr = urldecode(json_encode($jsonstr));
            $jsonstr = str_replace(']"', ']', str_replace('"[', '[', $jsonstr));
        } else {
            $jsonstr = json_encode($array, JSON_UNESCAPED_UNICODE);  //必须PHP5.4+
        }
        return $jsonstr;
    }


    public function httpsPostJson($url, $data = '', $array = true)
    {
        $curl = curl_init($url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        //类型为json
        curl_setopt($curl, CURLOPT_HTTPHEADER, array(
            'Content-Type: application/json; charset=utf-8'
        ));
        if ($data) {
            $data=json_encode($data);
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($curl);
        curl_close($curl);
        return $array ? json_decode($output, true) : $output;
    }

    /**
     *  https请求，支持get与post
     */
    protected function httpsRequest($url, $data = '', $array = true)
    {
        $curl = curl_init($url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        if ($data) {
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($curl);
        curl_close($curl);
        return $array ? json_decode($output, true) : $output;
    }

    private static $_instance = null;

    /**
     * 获取类实例
     *
     * @return \DAO\UserModel
     */
    public static function getInstance()
    {
        if (!(self::$_instance instanceof self)) {
            self::$_instance = new self();
        }

        return self::$_instance;
    }

}