<?php
namespace app\common\utils;
use think\Controller;
use app\common\utils\HttpHelper;
use app\common\model\RobotContact as RobotContactModel;
use app\common\model\Keyword as KeywordModel;
use app\common\model\Message as MessageModel;

use app\common\utils\RedisHelper;

/**
* 微信公众号发送消息
*/
class WXSendMessage
{   
	/*
     * 获取acc_token，有效期2小时
     */
    public static function access_token()
    {
        $redis = RedisHelper::getInstance()->getRedis();
        $key = "access_token";
        $access_token = false;
        // 存在access_token
        if ($redis->get($key)) {
            $access_token = $redis->get($key);
        }else{
            //更换成自己的APPID和APPSECRET
            $appid = config("wechat.appid");
            $appsecret = config("wechat.appsecret");
            
            $token_url="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appid."&secret=".$appsecret;
            
            $json = file_get_contents($token_url);
            $result = json_decode($json);

            $access_token = $result->access_token;

            // 存入，7000秒过期
            $redis->set($key, $access_token);
            $redis->expire($key, 7000);
        }

        return $access_token;
    }

    /*
     * 网络请求
     */
    public static function https_curl_post($url='', $postdata='', $options=array()){
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);

        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
        curl_setopt($ch, CURLOPT_TIMEOUT, 5);
        if (!empty($options)){
            curl_setopt_array($ch, $options);
        }
        $data = curl_exec($ch);
        curl_close($ch);
        return $data;
    }

    /*
     *  调用客服消息接口 -- 从而给用户发送消息，可以支持多条消息回复！
     *  客服回复消息文本类型
     */
    public static function send_text($touser, $content, $kf_account){
        $data = false;
        // 如果设置某个客服账号发消息
        if ($kf_account) {
             $data = '{
                "touser":"'.$touser.'",
                "msgtype":"text",
                "text":
                {
                    "content":"'.$content.'"
                },
                "customservice":
                {
                    "kf_account": "'.$kf_account.'"
                }
            }';
        }else{
            $data = '{
                "touser":"'.$touser.'",
                "msgtype":"text",
                "text":
                {
                    "content":"'.$content.'"
                }
            }';
        }
        
        $access_token = WXSendMessage::access_token();
        $url = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=".$access_token;
        $result = WXSendMessage::https_curl_post($url, $data);
        $final = json_decode($result);
        sleep( 0.5 );
        return $final;
    }

    /*
     *  客服回复消息图片类型
     */
    public static function send_image($touser, $media_id, $kf_account)
    {
        $data = false;
        // 如果设置某个客服账号发消息
        if ($kf_account) {
             $data = '{
                "touser":"'.$touser.'",
                "msgtype":"image",
                "image":
                {
                  "media_id":"'.$media_id.'"
                },
                 "customservice":
                {
                    "kf_account": "'.$kf_account.'"
                }
            }';
        }else{
            $data = '{
                "touser":"'.$touser.'",
                "msgtype":"image",
                "image":
                {
                  "media_id":"'.$media_id.'"
                }
            }';
        }

        $access_token = WXSendMessage::access_token();
        $url = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=".$access_token;
        $result = WXSendMessage::https_curl_post($url, $data);
        $final = json_decode($result);
        return $final;
    }

    /*
     *  客服回复消息语音类型
     */
    public static function send_voice($touser, $media_id, $kf_account)
    {
        $data = false;
        // 如果设置某个客服账号发消息
        if ($kf_account) {
             $data = '{
                "touser":"'.$touser.'",
                "msgtype":"voice",
                "voice":
                {
                  "media_id":"'.$media_id.'"
                },
                 "customservice":
                {
                    "kf_account": "'.$kf_account.'"
                }
            }';
        }else{
            $data = '{
                "touser":"'.$touser.'",
                "msgtype":"voice",
                "voice":
                {
                  "media_id":"'.$media_id.'"
                }
            }';
        }

        $access_token = WXSendMessage::access_token();
        $url = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=".$access_token;
        $result = WXSendMessage::https_curl_post($url, $data);
        $final = json_decode($result);
        return $final;
    }

    /*
     *  客服回复消息视频类型
     */
    public static function send_video($touser, $media_id, $kf_account, $title, $desc)
    {
        $data = false;
        // 如果设置某个客服账号发消息
        if ($kf_account) {
             $data = '{
                "touser":"'.$touser.'",
                "msgtype":"video",
                "video":
                {
                  "media_id":"'.$media_id.'",
                  "thumb_media_id":"'.$media_id.'",
                  "title":"'.$title.'",
                  "description":"'.$desc.'"
                },
                 "customservice":
                {
                    "kf_account": "'.$kf_account.'"
                }
            }';
        }else{
            $data = '{
                "touser":"'.$touser.'",
                "msgtype":"video",
                "video":
                {
                  "media_id":"'.$media_id.'",
                  "thumb_media_id":"'.$media_id.'",
                  "title":"'.$title.'",
                  "description":"'.$desc.'"
                }
            }';
        }

        $access_token = WXSendMessage::access_token();
        $url = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=".$access_token;
        $result = WXSendMessage::https_curl_post($url, $data);
        $final = json_decode($result);
        return $final;
    }

    /*
     *  获取用户信息
     */
    public static function get_user($openid){
        $access_token = WXSendMessage::access_token();
        $url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=".$access_token."&openid=".$openid."&lang=zh_CN";
        $user = HttpHelper::get_json_decode($url);
        return $user;
    }

    /*
     *  获取素材列表
     */
    public static function get_media_list(){
        $data = '{
            "type":"image",
            "offset":0,
            "count":20
        }';
        $access_token = WXSendMessage::access_token();
        $url = "https://api.weixin.qq.com/cgi-bin/material/batchget_material?access_token=".$access_token;
        $data = WXSendMessage::https_curl_post($url, $data);
        return $data;
    }

    /*
     *  添加永久素材
     */
    public static function add_media($image_path, $type){
        $access_token = WXSendMessage::access_token();
        //上传图片
        $type = "image";
        // print_r($filedata); exit;
        $url = "https://api.weixin.qq.com/cgi-bin/material/add_material?access_token=$access_token&type=$type";

        $result = self::https_request($url, $image_path);
        $res = json_decode($result, true);
        if (isset($res["media_id"]) && isset($res["url"])) {
            unlink($image_path);
            return $res["media_id"];    
        }else{
            return false;
        }
    }

    /*
     *  网络请求微信添加素材
     */
    private static function https_request($url, $source)
    {
        $curl = curl_init();
        
        if (class_exists('\CURLFile')) {// 这里用特性检测判断php版本
            curl_setopt($curl, CURLOPT_SAFE_UPLOAD, true);

            $filename = strrchr($source, "/");
            $filename = ltrim($filename, "/");
            // 更改上传的文件名
            $curlfile = new \CURLFile(realpath($source));
            $curlfile->postname = $filename;
            $data = array('media' => $curlfile);//>=5.5
        } else {
            if (defined('CURLOPT_SAFE_UPLOAD')) {
                curl_setopt($curl, CURLOPT_SAFE_UPLOAD, false);
            }
            $data = array('media' => '@' . realpath($source));//<=5.5
        }
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_POST, 1 );
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_USERAGENT, "TEST");
        $result = curl_exec($curl);
        $error = curl_error($curl);

        return $result;
    }
}