<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/*
 * 微信sdk
 */

class Wechat_model extends ZC_Model {

	
	//微信公众号配置信息
	public $wechat_config = array();
	public $postobj;
	public function __construct() {
		parent::__construct();
	}

	/**
	 * 设置微信配置信息
	 * @param  [array] $config [微信公众号的配置信息如tokeng]
	 * @return [type]         [description]
	 */
	public function init_wechat_config($config) {
		if(!empty($config)) {
			$this->wechat_config = $config;
		}
	}

	/**
	 * 验证签名
	 * @param  [type] $echostr   [description]
	 * @param  [type] $signature [description]
	 * @param  [type] $timestamp [description]
	 * @param  [type] $nonce     [description]
	 * @return [type]            [description]
	 */
	public function valid($echostr, $signature, $timestamp, $nonce) {
		$token = $this->wechat_config['plc_token'];
		$tmpArr = array($token, $timestamp, $nonce);
		sort($tmpArr);
		$tmpStr = implode($tmpArr);
		$tmpStr = sha1($tmpStr);
		if($tmpStr == $signature){
			echo $echostr;
		}
	}

	//响应消息
	public function response_msg($poststr) {
		if (!empty($poststr)){
			$this->logger("R ".$poststr);
			$postobj = simplexml_load_string($poststr, 'SimpleXMLElement', LIBXML_NOCDATA);
			$this->postobj = $postobj;
			//获取消息类型
			$RX_TYPE = trim($postobj->MsgType);
			//更具类型调用不同的方法
			$func_name = 'receive_'. $RX_TYPE;
			if(method_exists($this, $func_name)) {
				//event  text image location voice video link
				$result = $this->$func_name($postobj);
			} else {
				$result = "unknown msg type: ".$RX_TYPE;
			}
			$this->logger("T ".$result);
			return $result;
		}else {
			return "";
		}
	}

	//接收事件消息
	protected function receive_event($object) {
		$content = "";
		//调用事件类型对应的方法
		$func_name = $object->Event. '';
		if(method_exists($this, $func_name)) {
			//subscribe  unsubscribe SCAN CLICK LOCATION VIEW  MASSSENDJOBFINISH
			$content = $this->$func_name($object);
		} else {
			$content = "receive a new event: ".$object->Event;
		}
		//格式化文本消息
		$result = $this->format_data_by_receivetext($content, $object);

		return $result;
	}

	/**
	 * 用户关注时执行的方法
	 * @param  [object] $object [微信返回的消息的xml对象]
	 * @return [string]         [处理后返回给微信的消息]
	 */
	protected function subscribe($object) {
		$return = "欢迎Lcy博客 ";
		$return .= (!empty($object->EventKey))?("n来自二维码场景 ".str_replace("qrscene_","",$object->EventKey)):"";
		return $return;
	}

	/**
	 * 用户取消关注时执行的方法
	 * @param  [object] $object [微信返回的消息的xml对象]
	 * @return [string]         [处理后返回给微信的消息]
	 */
	protected function unsubscribe($object) {
		$return = '~~不要取消关注嘛';
		return $return;
	}

	/**
	 * 用户扫描场景时执行的方法
	 * @param  [object] $object [微信返回的消息的xml对象]
	 * @return [string]         [处理后返回给微信的消息]
	 */
	protected function scan($object) {
		$return = "扫描场景 ".$object->EventKey;
		return $return;
	}

	/**
	 * 用户点击菜单时执行的方法
	 * @param  [object] $object [微信返回的消息的xml对象]
	 * @return [string]         [处理后返回给微信的消息]
	 */
	protected function click($object) {
		switch($object->EventKey) {
			case "COMPANY":
				$return = array();
				$return[] = array("Title"=>"多图文1标题", "Description"=>"", "PicUrl"=>"http://discuz.comli.com/weixin/weather/icon/cartoon.jpg", "Url" =>"http://m.cnblogs.com/?u=txw1958");
				break;
			default:
				$return = "点击菜单:".$object->EventKey;
				break;
		}
		return $return;
	}

	/**
	 * 用户发送位置信息时执行的方法
	 * @param  [object] $object [微信返回的消息的xml对象]
	 * @return [string]         [处理后返回给微信的消息]
	 */
	protected function location($object) {
		$return = "上传位置:纬度 ".$object->Latitude.";经度 ".$object->Longitude;
		return $return;
	}

	/**
	 * 用户点击自定义菜单跳转链接时执行的方法
	 * @param  [object] $object [微信返回的消息的xml对象]
	 * @return [string]         [处理后返回给微信的消息]
	 */
	protected function view($object) {
		$return = "跳转链接 ".$object->EventKey;
		return $return;
	}

	/**
	 * 群发任务结束时执行的方法
	 * @param  [object] $object [微信返回的消息的xml对象]
	 * @return [string]         [处理后返回给微信的消息]
	 */
	protected function MASSSENDJOBFINISH($object) {
		$return = "消息ID:".$object->MsgID.",结果:".$object->Status.",粉丝数:".$object->TotalCount.",过滤:".$object->FilterCount.",发送成功:".$object->SentCount.",发送失败:".$object->ErrorCount;
		return $return;
	}
	
	//接收文本消息
	protected function receive_text($object) {
		$keyword = trim($object->Content);
		//多客服人工回复模式
		if (strstr($keyword, "您好") || strstr($keyword, "你好") || strstr($keyword, "在吗")){
			$result = $this->transmit_service($object);
		}
		//自动回复模式
		else{
			if (strstr($keyword, "文本")){
				$content = "这是个文本消息";
			}else if (strstr($keyword, "单图文")){
				$content = array();
				$content[] = array("Title"=>"单图文标题",  "Description"=>"单图文内容", "PicUrl"=>"http://discuz.comli.com/weixin/weather/icon/cartoon.jpg", "Url" =>"http://m.cnblogs.com/?u=txw1958");
			}else if (strstr($keyword, "图文") || strstr($keyword, "多图文")){
				$content = array();
				$content[] = array("Title"=>"多图文1标题", "Description"=>"", "PicUrl"=>"http://discuz.comli.com/weixin/weather/icon/cartoon.jpg", "Url" =>"http://m.cnblogs.com/?u=txw1958");
				$content[] = array("Title"=>"多图文2标题", "Description"=>"", "PicUrl"=>"http://d.hiphotos.bdimg.com/wisegame/pic/item/f3529822720e0cf3ac9f1ada0846f21fbe09aaa3.jpg", "Url" =>"http://m.cnblogs.com/?u=txw1958");
				$content[] = array("Title"=>"多图文3标题", "Description"=>"", "PicUrl"=>"http://g.hiphotos.bdimg.com/wisegame/pic/item/18cb0a46f21fbe090d338acc6a600c338644adfd.jpg", "Url" =>"http://m.cnblogs.com/?u=txw1958");
			}else if (strstr($keyword, "音乐")){
				$content = array();
				$content = array("Title"=>"最炫民族风", "Description"=>"歌手:凤凰传奇", "MusicUrl"=>"http://121.199.4.61/music/zxmzf.mp3", "HQMusicUrl"=>"http://121.199.4.61/music/zxmzf.mp3");
			}else{
				$content = date("Y-m-d H:i:s",time())."n技术支持 方倍工作室";
			}
			
			$result = $this->format_data_by_receivetext($content, $object);
		}

		return $result;
	}

	//格式化文本消息
	protected function format_data_by_receivetext($content, $object) {
		if(is_array($content)){
			if (isset($content[0]['PicUrl'])){
				$result = $this->transmit_news($object, $content);
			}else if (isset($content['MusicUrl'])){
				$result = $this->transmit_music($object, $content);
			}
		}else{
			$result = $this->transmit_text($object, $content);
		}
		return $result;
	}

	//接收图片消息
	protected function receive_image($object) {
		$content = array("MediaId"=>$object->MediaId);
		$result = $this->transmit_image($object, $content);
		return $result;
	}

	//接收位置消息
	protected function receive_location($object) {
		$content = "你发送的是位置,纬度为:".$object->Location_X.";经度为:".$object->Location_Y.";缩放级别为:".$object->Scale.";位置为:".$object->Label;
		$result = $this->transmit_text($object, $content);
		return $result;
	}

	//接收语音消息
	protected function receive_voice($object) {
		if (isset($object->Recognition) && !empty($object->Recognition)){
			$content = "你刚才说的是:".$object->Recognition;
			$result = $this->transmit_text($object, $content);
		}else{
			$content = array("MediaId"=>$object->MediaId);
			$result = $this->transmit_voice($object, $content);
		}

		return $result;
	}

	//接收视频消息
	protected function receive_video($object) {
		$content = array("MediaId"=>$object->MediaId, "ThumbMediaId"=>$object->ThumbMediaId, "Title"=>"", "Description"=>"");
		$result = $this->transmit_video($object, $content);
		return $result;
	}

	//接收链接消息
	protected function receive_link($object) {
		$content = "你发送的是链接,标题为:".$object->Title.";内容为:".$object->Description.";链接地址为:".$object->Url;
		$result = $this->transmit_text($object, $content);
		return $result;
	}

	//回复文本消息
	protected function transmit_text($object, $content) {
		$xmlTpl = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA]></MsgType>
<Content><![CDATA[%s]]></Content>
</xml>";
		$result = sprintf($xmlTpl, $object->FromUserName, $object->ToUserName, time(), $content);
		return $result;
	}

	//回复图片消息
	protected function transmit_image($object, $imageArray) {
		$itemTpl = "<Image>
	<MediaId><![CDATA[%s]]></MediaId>
</Image>";

		$item_str = sprintf($itemTpl, $imageArray['MediaId']);

		$xmlTpl = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[image]]></MsgType>
$item_str
</xml>";

		$result = sprintf($xmlTpl, $object->FromUserName, $object->ToUserName, time());
		return $result;
	}

	//回复语音消息
	protected function transmit_voice($object, $voiceArray) {
		$itemTpl = "<Voice>
	<MediaId><![CDATA[%s]]></MediaId>
</Voice>";

		$item_str = sprintf($itemTpl, $voiceArray['MediaId']);

		$xmlTpl = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[voice]]></MsgType>
$item_str
</xml>";

		$result = sprintf($xmlTpl, $object->FromUserName, $object->ToUserName, time());
		return $result;
	}

	//回复视频消息
	protected function transmit_video($object, $videoArray) {
		$itemTpl = "<Video>
	<MediaId><![CDATA[%s]]></MediaId>
	<ThumbMediaId><![CDATA[%s]]></ThumbMediaId>
	<Title><![CDATA[%s]]></Title>
	<Description><![CDATA[%s]]></Description>
</Video>";

		$item_str = sprintf($itemTpl, $videoArray['MediaId'], $videoArray['ThumbMediaId'], $videoArray['Title'], $videoArray['Description']);

		$xmlTpl = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA]></MsgType>
$item_str
</xml>";

		$result = sprintf($xmlTpl, $object->FromUserName, $object->ToUserName, time());
		return $result;
	}

	//回复图文消息
	protected function transmit_news($object, $newsArray) {
		if(!is_array($newsArray)){
			return;
		}
		$itemTpl = "    <item>
		<Title><![CDATA[%s]]></Title>
		<Description><![CDATA[%s]]></Description>
		<PicUrl><![CDATA[%s]]></PicUrl>
		<Url><![CDATA[%s]]></Url>
	</item>
";
		$item_str = "";
		foreach ($newsArray as $item){
			$item_str .= sprintf($itemTpl, $item['Title'], $item['Description'], $item['PicUrl'], $item['Url']);
		}
		$xmlTpl = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[news]]></MsgType>
<ArticleCount>%s</ArticleCount>
<Articles>
$item_str</Articles>
</xml>";

		$result = sprintf($xmlTpl, $object->FromUserName, $object->ToUserName, time(), count($newsArray));
		return $result;
	}

	//回复音乐消息
	protected function transmit_music($object, $musicArray) {
		$itemTpl = "<Music>
	<Title><![CDATA[%s]]></Title>
	<Description><![CDATA[%s]]></Description>
	<MusicUrl><![CDATA[%s]]></MusicUrl>
	<HQMusicUrl><![CDATA[%s]]></HQMusicUrl>
</Music>";

		$item_str = sprintf($itemTpl, $musicArray['Title'], $musicArray['Description'], $musicArray['MusicUrl'], $musicArray['HQMusicUrl']);

		$xmlTpl = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[music]]></MsgType>
$item_str
</xml>";

		$result = sprintf($xmlTpl, $object->FromUserName, $object->ToUserName, time());
		return $result;
	}

	//回复多客服消息
	protected function transmit_service($object) {
		$xmlTpl = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[transfer_customer_service]]></MsgType>
</xml>";
		$result = sprintf($xmlTpl, $object->FromUserName, $object->ToUserName, time());
		return $result;
	}

	//日志记录
	public function logger($log_content) {
		if(isset($_SERVER['HTTP_APPNAME'])){   //SAE
			sae_set_display_errors(false);
			sae_debug($log_content);
			sae_set_display_errors(true);
		}else if($_SERVER['REMOTE_ADDR'] != "127.0.0.1"){ //LOCAL
			$max_size = 10000;
			$log_filename = "log.xml";
			if(file_exists($log_filename) and (abs(filesize($log_filename)) > $max_size)){unlink($log_filename);}
			file_put_contents($log_filename, date('H:i:s')." ".$log_content."rn", FILE_APPEND);
		}
	}

	
}