<?php

namespace Wechat;

use Wechat\Lib\Cache;
use Wechat\Lib\Tools;

class_exists('Wechat\Loader', FALSE) OR require __DIR__ . DIRECTORY_SEPARATOR . 'Loader.php';

/**
 * 公众号第三方平台SDK
 * 
 * @version 1.0
 * @author Anyon <zoujingli@qq.com>
 * @date 2016/10/18 00:35:55
 * 
 * @usage:
 * $options = array(
 *    'component_token'           =>'token',          // 公众号消息校验Token
 *    'component_appid'           =>'appid',          // 填写高级调用功能的appid
 *    'component_appsecret'       =>'appsecret',      // 填写高级调用功能的appsecret
 *    'component_verify_ticket'   =>'ticket',         // 微信服务推送的ticket
 *    'component_encodingaeskey'  =>'encodingaeskey', // 公众号消息加解密Key
 * );
 * $service = new WechatService($options);
 * $service->getAuthorizationInfo();     //获取服务号的授权信息
 * $service->refreshAccessToken();       //刷新授权方操作Token
 * $service->getWechatInfo();            //获取公众号的帐号信息
 * $service->getAuthorizerOption();      //获取公众号的授权项的值
 * $service->setAuthorizerOption();      //设置公众号的授权项的值
 * 
 */
class WechatService {

    const URL_PREFIX = 'https://api.weixin.qq.com/cgi-bin/component';
    // 获取服务access_token
    const COMPONENT_TOKEN_URL = '/api_component_token';
    // 获取（刷新）授权公众号的令牌
    const REFRESH_ACCESS_TOKEN = '/api_authorizer_token';
    // 获取预授权码
    const PREAUTH_CODE_URL = '/api_create_preauthcode';
    // 获取公众号的授权信息
    const QUERY_AUTH_URL = '/api_query_auth';
    // 获取授权方的账户信息
    const GET_AUTHORIZER_INFO_URL = '/api_get_authorizer_info';
    // 刷新授权令牌
    const REFRESH_AUTHORIZER_TOKEN = './api_authorizer_token';
    // 获取授权方的选项设置信息
    const GET_AUTHORIZER_OPTION_URL = '/api_get_authorizer_option';
    // 设置授权方的选项信息
    const SET_AUTHORIZER_OPTION_URL = '/api_set_authorizer_option';

    // 微信后台推送的ticket 每十分钟更新一次
    protected $component_verify_ticket;
    // 服务appid
    protected $component_appid;
    // 服务appsecret
    protected $component_appsecret;
    // 公众号消息校验Token
    protected $component_token;
    // 公众号消息加解密Key
    protected $component_encodingaeskey;
    // 服务令牌
    protected $component_access_token;
    // 授权方appid
    protected $authorizer_appid;
    // 授权方令牌
    protected $authorizer_access_token;
    // 刷新令牌
    protected $authorizer_refresh_token;
    // 预授权码
    protected $pre_auth_code;
    // Wechat对象缓存
    protected $wechat = array();
    // JSON数据
    protected $data;
    // 错误代码
    public $errCode;
    // 错误消息
    public $errMsg;

    /**
     * SDK初始化构造方法
     * 
     * @param type $options
     */
    public function __construct($options = array()) {
        $options = Loader::config($options);
        $this->component_encodingaeskey = !empty($options['component_encodingaeskey']) ? $options['component_encodingaeskey'] : '';
        $this->component_verify_ticket = !empty($options['component_verify_ticket']) ? $options['component_verify_ticket'] : '';
        $this->component_appsecret = !empty($options['component_appsecret']) ? $options['component_appsecret'] : '';
        $this->component_token = !empty($options['component_token']) ? $options['component_token'] : '';
        $this->component_appid = !empty($options['component_appid']) ? $options['component_appid'] : '';
    }

    /**
     * 接收公众平台推送的 Ticket 
     * @return boolean
     */
    public function getComonentTicket() {
        $receive = new WechatReceive(array(
            'appid'          => $this->component_appid,
            'appsecret'      => $this->component_appsecret,
            'encodingaeskey' => $this->component_encodingaeskey,
            'token'          => $this->component_token,
            'cachepath'      => Cache::$cachepath
        ));
        # 会话内容解密状态判断
        if (false === $receive->valid()) {
            $this->errCode = $receive->errCode;
            $this->errMsg = $receive->errMsg;
            Tools::log("Get Wechat Push ComponentVerifyTicket Faild. {$this->errMsg} [$this->errCode]", 'Err');
            return false;
        }
        $data = $receive->getRev()->getRevData();
        if ($data['InfoType'] === 'component_verify_ticket' && !empty($data['ComponentVerifyTicket'])) {
            # 记录推送日志到微信SDK
            Tools::log("Get Wechat Push ComponentVerifyTicket Success. ");
            Tools::setCache('component_verify_ticket', $data['ComponentVerifyTicket']);
        }
        return $data;
    }

    /**
     * 获取或刷新服务AccessToken
     * @return type
     */
    public function getComponentAccessToken() {
        $cacheKey = 'wechat_component_access_token';
        $this->component_access_token = Tools::getCache($cacheKey);
        if (empty($this->component_access_token)) {
            $data = array();
            $data['component_appid'] = $this->component_appid;
            $data['component_appsecret'] = $this->component_appsecret;
            $data['component_verify_ticket'] = $this->component_verify_ticket;
            $url = self::URL_PREFIX . self::COMPONENT_TOKEN_URL;
            $result = Tools::httpPost($url, Tools::json_encode($data));
            if (($this->component_access_token = $this->_decode($result, 'component_access_token')) === false) {
                Tools::log("Get getComponentAccessToken Faild. {$this->errMsg} [$this->errCode]", 'ERR');
                return false;
            }
            Tools::setCache($cacheKey, $this->component_access_token, 7200);
        }
        return $this->component_access_token;
    }

    /**
     * 获取预授权码
     * 
     * @return type
     */
    public function getPreauthCode() {
        empty($this->component_access_token) && $this->getComponentAccessToken();
        if (empty($this->component_access_token)) {
            return false;
        }
        $data = array();
        $data['component_appid'] = $this->component_appid;
        $url = self::URL_PREFIX . self::PREAUTH_CODE_URL . "?component_access_token={$this->component_access_token}";
        $result = Tools::httpPost($url, Tools::json_encode($data));
        $this->pre_auth_code = $this->_decode($result, 'pre_auth_code');
        if (empty($this->pre_auth_code)) {
            Tools::log("Get getPreauthCode Faild. {$this->errMsg} [$this->errCode]", 'ERR');
        }
        return $this->pre_auth_code;
    }

    /**
     * 获取（刷新）授权公众号的令牌
     * @注意1. 授权公众号访问access token2小时有效
     * @注意2. 一定保存好新的刷新令牌
     * @param type $authorizer_appid 授权方APPID
     * @param type $authorizer_refresh_token 授权方刷新令牌
     * @return type
     */
    public function refreshAccessToken($authorizer_appid, $authorizer_refresh_token) {
        empty($this->component_access_token) && $this->getComponentAccessToken();
        if (empty($this->component_access_token)) {
            return false;
        }
        $data = array();
        $data['component_appid'] = $this->component_appid;
        $data['authorizer_appid'] = $authorizer_appid;
        $data['authorizer_refresh_token'] = $authorizer_refresh_token;
        $url = self::URL_PREFIX . self::REFRESH_ACCESS_TOKEN . "?component_access_token={$this->component_access_token}";
        $result = Tools::httpPost($url, Tools::json_encode($data));
        if (($result = $this->_decode($result)) === false) {
            Tools::log("Get getAuthorizerOption Faild. {$this->errMsg} [$this->errCode]", 'ERR');
        }
        return $result;
    }

    /**
     * 获取公众号的授权信息
     * 
     * @param type $authorization_code
     * @return array
     */
    public function getAuthorizationInfo($authorization_code) {
        empty($this->component_access_token) && $this->getComponentAccessToken();
        if (empty($this->component_access_token)) {
            return false;
        }
        $data = array();
        $data['component_appid'] = $this->component_appid;
        $data['authorization_code'] = $authorization_code;
        $url = self::URL_PREFIX . self::QUERY_AUTH_URL . "?component_access_token={$this->component_access_token}";
        $result = Tools::httpPost($url, Tools::json_encode($data));
        $authorization_info = $this->_decode($result, 'authorization_info');
        if (empty($authorization_info)) {
            Tools::log("Get getAuthorizationInfo Faild. {$this->errMsg} [$this->errCode]", 'ERR');
            return false;
        }
        $authorization_info['func_info'] = $this->_parseFuncInfo($authorization_info['func_info']);
        return $authorization_info;
    }

    /**
     * 获取授权方的账户信息
     * @param type $authorizer_appid
     * @return boolean
     */
    public function getWechatInfo($authorizer_appid) {
        empty($this->component_access_token) && $this->getComponentAccessToken();
        $data = array();
        $data['component_access_token'] = $this->component_access_token;
        $data['component_appid'] = $this->component_appid;
        $data['authorizer_appid'] = $authorizer_appid;
        $url = self::URL_PREFIX . self::GET_AUTHORIZER_INFO_URL . "?component_access_token={$this->component_access_token}";
        $result = Tools::httpPost($url, Tools::json_encode($data));
        $authorizer_info = $this->_decode($result, 'authorizer_info');
        if (empty($authorizer_info)) {
            Tools::log("Get WechatInfo Faild. {$this->errMsg} [$this->errCode]", 'ERR');
            return false;
        }
        $author_data = array_merge($authorizer_info, $this->data['authorization_info']);
        $author_data['service_type_info'] = $author_data['service_type_info']['id'];
        $author_data['verify_type_info'] = $author_data['verify_type_info']['id'];
        $author_data['func_info'] = $this->_parseFuncInfo($author_data['func_info']);
        $author_data['business_info'] = json_encode($author_data['business_info']);
        return $author_data;
    }

    /**
     * 获取授权方的选项设置信息
     * @param type $authorizer_appid
     * @param type $option_name
     * @return boolean
     */
    public function getAuthorizerOption($authorizer_appid, $option_name) {
        empty($this->component_access_token) && $this->getComponentAccessToken();
        if (empty($this->authorizer_appid)) {
            return false;
        }
        $data = array();
        $data['component_appid'] = $this->component_appid;
        $data['authorizer_appid'] = $authorizer_appid;
        $data['option_name'] = $option_name;
        $url = self::URL_PREFIX . self::GET_AUTHORIZER_OPTION_URL . "?component_access_token={$this->component_access_token}";
        $result = Tools::httpPost($url, Tools::json_encode($data));
        if (($result = $this->_decode($result)) === false) {
            Tools::log("Get getAuthorizerOption Faild. {$this->errMsg} [$this->errCode]", 'ERR');
        }
        return $result;
    }

    /**
     * 设置授权方的选项信息
     * @param type $authorizer_appid
     * @param type $option_name
     * @param type $option_value
     * @return boolean
     */
    public function setAuthorizerOption($authorizer_appid, $option_name, $option_value) {
        empty($this->component_access_token) && $this->getComponentAccessToken();
        if (empty($this->authorizer_appid)) {
            return false;
        }
        $data = array();
        $data['component_appid'] = $this->component_appid;
        $data['authorizer_appid'] = $authorizer_appid;
        $data['option_name'] = $option_name;
        $data['option_value'] = $option_value;
        $url = self::URL_PREFIX . self::SET_AUTHORIZER_OPTION_URL . "?component_access_token={$this->component_access_token}";
        $result = Tools::httpPost($url, Tools::json_encode($data));
        if (($result = $this->_decode($result)) === false) {
            Tools::log("Get setAuthorizerOption Faild. {$this->errMsg} [$this->errCode]", 'ERR');
        }
        return $result;
    }

    /**
     * 获取授权回跳地址
     * @param type $redirect_uri
     * @return boolean
     */
    public function getAuthRedirect($redirect_uri) {
        empty($this->pre_auth_code) && $this->getPreauthCode();
        if (empty($this->pre_auth_code)) {
            return false;
        }
        return "https://mp.weixin.qq.com/cgi-bin/componentloginpage?component_appid={$this->component_appid}&pre_auth_code={$this->pre_auth_code}&redirect_uri={$redirect_uri}";
    }

    /**
     * oauth 授权跳转接口
     * @param type $appid
     * @param type $redirect_uri
     * @param type $scope snsapi_userinfo|snsapi_base
     * @return type
     */
    public function getOauthRedirect($appid, $redirect_uri, $scope = 'snsapi_userinfo') {
        return "https://open.weixin.qq.com/connect/oauth2/authorize?appid={$appid}&redirect_uri=" . urlencode($redirect_uri)
                . "&response_type=code&scope={$scope}&state={$appid}&component_appid={$this->component_appid}#wechat_redirect";
    }

    /**
     * 通过code获取Access Token
     * @param type $appid
     * @return boolean
     */
    public function getOauthAccessToken($appid) {
        $code = isset($_GET['code']) ? $_GET['code'] : '';
        if (empty($code)) {
            return false;
        }
        empty($this->component_access_token) && $this->getComponentAccessToken();
        if (empty($this->component_access_token)) {
            return false;
        }
        $url = "https://api.weixin.qq.com/sns/oauth2/component/access_token?"
                . "appid={$appid}&code={$code}&"
                . "grant_type=authorization_code&"
                . "component_appid={$this->component_appid}&"
                . "component_access_token={$this->component_access_token}";
        $json = $this->parseJson(Tools::httpGet($url));
        if ($json !== false) {
            return $json;
        }
        return false;
    }

    /**
     * 获取关注者详细信息
     * @param string $openid
     * @param boolen $oauthAccessToken
     * @return array {subscribe,openid,nickname,sex,city,province,country,language,headimgurl,subscribe_time,[unionid]}
     * 注意：unionid字段 只有在用户将公众号绑定到公众号第三方平台账号后，才会出现。建议调用前用isset()检测一下
     */
    public function getOauthUserInfo($openid, $oauthAccessToken) {
        $url = "https://api.weixin.qq.com/sns/userinfo?access_token={$oauthAccessToken}&openid={$openid}&lang=zh_CN";
        return $this->parseJson(Tools::httpGet($url));
    }

    /**
     * 解析授权信息，返回以逗号分割的数据
     * @param type $func_info
     * @return type
     */
    private function _parseFuncInfo($func_info) {
        $authorization_list = array();
        foreach ($func_info as $func) {
            foreach ($func as $f) {
                $authorization_list[] = $f['id'];
            }
        }
        return join($authorization_list, ',');
    }

    /**
     * 解析JSON数据

     * @param type $result
     * @param type $field
     * @return type
     */
    private function _decode($result, $field = null) {
        $this->data = json_decode($result, true);
        if (!empty($this->data['errcode'])) {
            $this->errCode = $this->data['errcode'];
            $this->errMsg = $this->data['errmsg'];
            return false;
        }
        if ($this->data && !is_null($field)) {
            if (isset($this->data[$field])) {
                return $this->data[$field];
            } else {
                return false;
            }
        }
        return $this->data;
    }

    /**
     * 解析JSON数据
     * @param type $result
     * @return boolean
     */
    private function parseJson($result) {
        $json = json_decode($result, true);
        if (!empty($json['errcode'])) {
            $this->errCode = $json['errcode'];
            $this->errMsg = $json['errmsg'];
            return false;
        }
        return $json;
    }

}
