<?php
namespace XYCms;
use app\common\model\WechatTemplate as WechatTemplateModel;
use think\facade\Cache;
use think\Exception;
use helper\URL;
use helper\Wechat as WechatHelper;
/**
 * 微信公众号消息推送类
 * @Renloong
 * 2018/09/28
 */
class WechatPush
{
	private $_access_token='';
	private $_first='';
	private $_first_color='';
	private $_remark='';
	private $_remark_color='';
	private $_item_data=[];
	private $_data=[];
	private $_openid='';
	private $_url='';
	private $_tplid='';
	/**
	 * 构造函数，
	 * 读取配置
	 */
	public function __construct()
	{
        $token = WechatHelper::GetWeiXinToken();
        if (empty($token))
			throw new Exception('非常抱歉，TOKEN获取失败');
        if (!empty($token['status']) && $token['status']){
			$this->_access_token=$token['access_token'];
        }else{
			throw new Exception('非常抱歉，TOKEN获取失败');
        }
	}
	public function setTpl($tpl_alias)
	{
        $tpl=Cache::get('WechatTemplate.'.$tpl_alias);
        if (!$tpl)
        	$tpl=WechatTemplateModel::where(['alias'=>$tpl_alias])->find()->toArray();
        if (!$tpl) throw new Exception($tpl_alias.':模板不存在');
    	if ($tpl['status']) {
    		$this->_tplid=$tpl['tplid'];
    		$this->_first=$tpl['first'];
    		$this->_first_color=$tpl['first_color'];
    		$this->_remark=$tpl['remark'];
    		$this->_remark_color=$tpl['remark_color'];
    		$this->_item_data=$tpl['item_data'];
    		$this->_url=$tpl['url'];
    	}else{
        	throw new Exception($tpl_alias.':模板不存在');
    	}
    	return $this;
	}
	public function setOpenid($openid)
	{
		$this->_openid=$openid;
        return $this;
	}
	public function setUrl($url)
	{
		$this->_url=$url;
        return $this;
	}
	public function setData($Data)
	{
		foreach ($Data as $k => $v) {
			if (is_string($v)) {
				$this->_first=str_replace('{'.$k.'}',$v,$this->_first);
				$this->_remark=str_replace('{'.$k.'}',$v,$this->_remark);
			}
		}
		if(!empty($Data['u'])){
			foreach ($Data['u'] as $k => $v) {
				if (is_string($v)) {
					$this->_first=str_replace('{u.'.$k.'}',$v,$this->_first);
					$this->_remark=str_replace('{u.'.$k.'}',$v,$this->_remark);
				}
			}
		}
		$data['first']=[
                "value" => $this->_first,
                "color" => $this->_first_color
            ];
		foreach ($this->_item_data as $k => $v) {
			$data['keyword'.($k+1)]['color']=$v['color'];
			if(strpos($v['value'],'.')){
				$keyArr=explode('.',$v['value']);
				if(!empty($Data[$keyArr[0]][$keyArr[1]])){
					$data['keyword'.($k+1)]['value']=$Data[$keyArr[0]][$keyArr[1]];
				}
			}else{
				$data['keyword'.($k+1)]['value']=empty($Data[$v['value']])?'':$Data[$v['value']];
			}
		}
		$data['remark']=[
                "value" => $this->_remark,
                "color" => $this->_remark_color
            ];
        $this->_data=$data;
        return $this;
	}
	/**
	 * 初始化
	 */
	public function send()
	{
		$pushData=[
            'touser'    	=>  $this->_openid,
            "template_id"	=> 	$this->_tplid,
            'data' 			=> 	$this->_data
		];
		if ($this->_url){
			$pushData['url']=$this->_url;
		}else{
			$pushData['url']=Cache::get('web.wechatmp').'/login';
		}
        if (Cache::get('xycms_message.status_mp')) {
	        //开始推送通知
	        $wxRet=URL::post('https://api.weixin.qq.com/cgi-bin/message/template/send?access_token='.$this->_access_token,json_encode($pushData,JSON_UNESCAPED_UNICODE));
	        if (!empty($wxRet)){
	        	$wxRet=json_decode($wxRet,true);
		        if (!empty($wxRet['errcode']) && $wxRet['errcode']==0)
		            return true;
				throw new Exception($wxRet['errmsg']);
	        }
			throw new Exception('未获取到推送结果');
        }
		throw new Exception('取消推送');
	}
}