<?php

namespace App\Com;

use App\Com\WechatAccessToken;
use App\Models\AccountWechat;
use App\Models\OperatorsUser;
use App\Com\Redis;
use EasySwoole\EasySwoole\Logger;

/**
 * 微信公众号消息模板发送
 */
class WechatMessage
{

	protected $minwechat_appid	= null;		//小程序公众号appid
	protected $url = 'https://api.weixin.qq.com/cgi-bin/message/template/send';
	protected $access_token = null;	//公众号access_token
    protected $redis = null;    //redis实例

    public function __construct($operators_id=0)
    {
    	$at = new WechatAccessToken($operators_id);
		$this->access_token = $at->getAccess_token();
        $set = AccountWechat::create()->get()->toArray();
        if(!$operators_id){
            $this->minwechat_appid = $set['key'];
        }
        else{
            //获取运营商数据
            $operators_res = OperatorsUser::create()->where('id',$operators_id)->get()->toArray();
            $this->minwechat_appid = $operators_res['key']?$operators_res['key']:$set['key'];
        }
        //加载redis
        $this->redis = Redis::getInstance()->getConnect();
    }

    /**
     * @param $openid 公众号openid
     * @param $templateId 消息模板ID
     * @param $jump_path 小程序跳转路径
     * @param $templateBody 消息模板标签内容
     * @return Bool 是否发送成功
     */
    public function send_message($openid,$templateId,$jump_path,$templateBody){
    	//请求数据体
    	$json_Body = Array(
    		'touser' => $openid,
    		'template_id' => $templateId,	//模板ID
    		'miniprogram' => Array(
    			'appid' => $this->minwechat_appid,
    			'pagepath' => $jump_path,
    		),
    		//公众号消息模板
    		'data' => $templateBody,
    	);
    	$res = $this->http_rquest($this->url."?access_token=".$this->access_token,$json_Body);
		//记录微信服务器返回值
        Logger::getInstance()->info('公众号模板消息接口返回值:'.$res);
		$api_res = json_decode($res,true);
        $result['request'] = $json_Body;
        $result['response'] = $api_res;
        return $result;
		//return $result['errcode']!=0?false:true;
    }

    /**
     * http请求
     * @param $url 请求地址
     * @param $jsonBody 数组内容
     * @return String 请求返回原生数据
     */
    protected function http_rquest($url,$jsonBody){
		$opts = array(
    		'http' => array(
        		'method' => 'POST',
        		'heade' => "Content-type:application/json",
        		'content' => json_encode($jsonBody),
    		)
    	);
		$context = stream_context_create($opts);
		$response = file_get_contents($url,false,$context);
		return $response;
    }



}
