<?php


declare (strict_types=1);
namespace library\lib;

class weixinjs {

    private $appId = '';
    private $appSecret = '';

    public function __construct() {
        if(empty($info)) $info = config('weixin');
        $this->appId = $info['APPID'];
        $this->appSecret = $info['APPSECRET'];

    }

    public function getSignPackage() {
        $jsapiTicket = $this->getJsApiTicket();

        // 注意 URL 一定要动态获取，不能 hardcode.
        $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
        $url = "$protocol$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
        //var_dump($url);
        //$url = C('SYS_URL').$_SERVER[REQUEST_URI];
        $timestamp = time();
        $nonceStr = $this->createNonceStr();

        // 这里参数的顺序要按照 key 值 ASCII 码升序排序
        $string = "jsapi_ticket=$jsapiTicket&noncestr=$nonceStr&timestamp=$timestamp&url=$url";

        $signature = sha1($string);

        $signPackage = array(
            "appId" => $this->appId,
            "nonceStr" => $nonceStr,
            "timestamp" => $timestamp,
            "url" => $url,
            "signature" => $signature,
            "rawString" => $string
        );
        return $signPackage;
    }

    public function addrSign($signPackage) {

        $sdata = array(
            'appId' => $signPackage['appId'],
            'url' => $signPackage['url'],
            'timeStamp' => $signPackage['timestamp'],
            'nonceStr' => $signPackage['nonceStr'],
            'accessToken' => $signPackage['access_token']
        );

        ksort($sdata);
        $string = "";
        foreach ($sdata as $k => $v) {
            $string.=strtolower($k) . "=" . $v . '&';
        }

        $string = substr($string, 0, -1);

        return sha1($string);
    }

    /**
     * 获取模板
     */
    public function template($tempId,$openid, $data,$return_url = '') {
        $accessToken = $this->getAccessToken();
        $url = 'https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=' . $accessToken;
        $post_data['touser'] = $openid;
        $post_data['template_id'] =$tempId; //模板订单
        //$_A['sys']['sys_url'] . '/User/order_info?trade_no=' . $trade_no
        if (!empty($return_url))
            $post_data['url'] = $return_url;
        $post_data['topcolor'] = '#FF0000';
        $post_data['data'] = $data;
        $r_data = $this->httpPost($url, $this->Xjson_encode($post_data));

        return $r_data;
    }

    /**
     * 获取验证码
     */
    public function showqrcode($id) {
        $accessToken = $this->getAccessToken();
        $url = 'https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=' . $accessToken;
        $data = $this->httpPost($url, '{"action_name": "QR_LIMIT_STR_SCENE", "action_info": {"scene": {"scene_str": "' . $id . '"}}}');
        $data_json = json_decode($data, true);
        if ($data_json['errcode'] != '40013') {
            $url = $data_json['url'];
            $ticket = $data['ticket'];
            $urlx = 'https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=' . $ticket;
            $this->httpGet($urlx);
            return $url;
        }
        return '';
    }

    /**
     * 发送客服消息
     */
    function sendMsg($openid, $text) {
        $accessToken = $this->getAccessToken();
        $url = 'https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=' . $accessToken;
        $post_data['touser'] = $openid;
        $post_data['msgtype'] = 'text';
        $post_data['text'] = array('content' => $text);

        $data = $this->httpPost($url, $this->Xjson_encode($post_data));
        if ($data['errcode'] == 0) {
            return array('errcode' => 0);
        } else {
            return $data;
        }
    }
    /**
     * 发送图片
     */
    function sendImage( $openid,$media_id) {
        $accessToken = $this->getAccessToken();
        $url = 'https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=' . $accessToken;
        $post_data['touser'] = $openid;
        $post_data['msgtype'] = 'image';
        $post_data['image'] = array("media_id"=>$media_id);

        $data = $this->httpPost($url, $this->Xjson_encode($post_data));

        $data = json_decode($data,true);
        if ($data['errcode'] == 0) {
            return array('errcode' => 0);
        } else {
            return $data;
        }
    }

    /**
     * 上传文件
     * @param type $fielname
     */
    function UpdateImage($path){
        $accessToken = $this->getAccessToken();
        $data = '@'.realpath($path).";type=image/jpeg;filename=".md5(time()).".jpg";
        $datx = $this->uploadFile($data,'image',$accessToken);
        $datx = json_decode($datx, true);
        if($datx['media_id']){
            return $datx;
        } else {
            return null;
        }
    }

    /**
     * 用户信息
     * @param type $openid
     * @return type
     */
    function userinfo($openid) {
        $accessToken = $this->getAccessToken();
        $url = 'https://api.weixin.qq.com/cgi-bin/user/info?access_token=' . $accessToken . '&openid=' . $openid . '&lang=zh_CN';
        $data = $this->httpGet($url);
        $data_json = json_decode($data, true);
        if ($data_json['errcode'] != '40013') {
            return $data_json;
        } else {
            return null;
        }
    }

    /**
     * 设置menu
     * @param type $data
     */
    function SetMenu($data) {
        $accessToken = $this->getAccessToken();
        $url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=" . $accessToken;
        $post_data = $data;
        $datax = $this->httpPost($url, $this->Xjson_encode($post_data));
        return $datax;
    }


    /**
     * 获取客服基本信息
     */

    function getkflist() {
        $accessToken = $this->getAccessToken();
        $url = 'https://api.weixin.qq.com/cgi-bin/customservice/getkflist?access_token=' . $accessToken;
        $data = $this->httpGet($url);
        $data_json = json_decode($data, true);
        return $data_json;
    }
    /**
     * 获取在线客服接待信息
     * @return type
     */
    function getonlinekflist() {
        $accessToken = $this->getAccessToken();
        $url = 'https://api.weixin.qq.com/cgi-bin/customservice/getonlinekflist?access_token=' . $accessToken;
        $data = $this->httpGet($url);
        $data_json = json_decode($data, true);
        return $data_json;
    }
    /**
     * 添加客服账号
     * @param type $data
     * @return type
     */
    function kfaccount_add($data){
        $accessToken = $this->getAccessToken();
        $url = 'https://api.weixin.qq.com/customservice/kfaccount/add?access_token='.$accessToken;
        $post_data = $data;
        $datax = $this->httpPost($url, $this->Xjson_encode($post_data));
        return $datax;
    }
    /**
     * 设置客服信息
     * @param type $data
     * @return type
     */
    function kfaccount_save($data){
        $accessToken = $this->getAccessToken();
        $url = 'https://api.weixin.qq.com/customservice/kfaccount/update?access_token='.$accessToken;
        $post_data = $data;
        $datax = $this->httpPost($url, $this->Xjson_encode($post_data));
        return $datax;
    }

    /**
     * 删除数据
     * @param type $kf_account
     * @return type
     */
    function kfaccount_del($kf_account) {
        $accessToken = $this->getAccessToken();
        $url = 'https://api.weixin.qq.com/customservice/kfaccount/del?access_token=' . $accessToken . '&kf_account=' . $kf_account;
        $data = $this->httpGet($url);
        $data_json = json_decode($data, true);
        return $data_json;
    }

    /**
     *
     * @param type $length
     * @return type
     */
    private function createNonceStr($length = 16) {
        $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        $str = "";
        for ($i = 0; $i < $length; $i++) {
            $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        }
        return $str;
    }

    private function getJsApiTicket() {
        // jsapi_ticket 应该全局存储与更新，以下代码以写入到文件中做示例
        $data = json_decode(cache('weix_jsapi_ticket'),true);

        if ( empty($data) &&  $data['expire_time'] < time()) {
            $accessToken = $this->getAccessToken();
            // 如果是企业号用以下 URL 获取 ticket
            // $url = "https://qyapi.weixin.qq.com/cgi-bin/get_jsapi_ticket?access_token=$accessToken";
            $url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi&access_token=$accessToken";
            $res = json_decode($this->httpGet($url));

            $ticket = $res->ticket;
            if ($ticket) {
                $data['expire_time'] = time() + 7000;
                $data['jsapi_ticket'] = $ticket;
                cache('weix_jsapi_ticket', json_encode($data));
            }
        } else {
            $ticket = $data['jsapi_ticket'];
        }

        return $ticket;
    }

    private function getAccessToken() {
        // access_token 应该全局存储与更新，以下代码以写入到文件中做示例
        $data = [];
        $weixAccessToken = cache('weix_access_token');
        $data = empty($weixAccessToken) ? '' : json_decode($weixAccessToken,true);
        if (empty($data)  || $data['expire_time'] < time()) {
            // 如果是企业号用以下URL获取access_token
            // $url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=$this->appId&corpsecret=$this->appSecret";
            $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$this->appId&secret=$this->appSecret";
            $res = json_decode($this->httpGet($url));
            $access_token = $res->access_token;
            $data = [];
            if (!empty($access_token)) {
                $data['expire_time'] = time() + 7000;
                $data['access_token'] = $access_token;
                cache('weix_access_token', json_encode($data));
            }
        } else {
            $access_token = $data['access_token'];
        }
        return $access_token;
    }

    /* 上传多媒体文件 */

    public function uploadFile($file, $type = 'image', $acctoken = '') {
        $post_data ['type'] = $type; // 媒体文件类型，分别有图片（image）、语音（voice）、视频（video）和缩略图（thumb）
        $post_data ['media'] = $file;

        $url = "http://file.api.weixin.qq.com/cgi-bin/media/upload?access_token=$acctoken&type=image";
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
        ob_start();
        curl_exec($ch);
        $result = ob_get_contents();
        ob_end_clean();

        return $result;
    }

    private function httpGet($url) {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_TIMEOUT, 500);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($curl, CURLOPT_URL, $url);

        $res = curl_exec($curl);
        curl_close($curl);

        return $res;
    }

    private function httpPost($url, $post) {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HEADER, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_NOBODY, true);
        curl_setopt($curl, CURLOPT_POST, true);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $post);
        $return_str = curl_exec($curl);
        curl_close($curl);
        return $return_str;
    }

    function Xjson_encode($input) {
        // 从 PHP 5.4.0 起, 增加了这个选项.
        return json_encode($input, JSON_UNESCAPED_UNICODE);
    }

}
