<?php
namespace app\weixin\controller;
use think\Controller;
use think\Db;
class Index extends Home{


 
     public function index(){  
      
       if(input('echostr')) {
          if($this->check()){
        	   echo input('echostr');
        	   exit;
          }
       }
	   $GLOBALS = file_get_contents("php://input");;
	   $obj= simplexml_load_string($GLOBALS,'SimpleXMLElement',LIBXML_NOCDATA);
	   $type=$obj->MsgType;
	  
       if($type=='event'){ $this->event($obj); 	$this->saveUser($obj);;}
	   if($type=='text'){ $this->replyKeyword($obj,$obj->Content); }
		
	}


	public function check(){
        $signature = input("signature");
        $timestamp = input("timestamp");
        $nonce = input("nonce");	
        		
		$token = 'yershop';
		$tmpArr = array($token, $timestamp, $nonce);
		sort($tmpArr);
		$tmpStr = implode( $tmpArr );
		$tmpStr = sha1( $tmpStr );
		
		if( $tmpStr == $signature ){
			return true;
		}else{
			return false;
		}
	}
	public function event($obj){
		   $envent=$obj->Event;
		   //用户未关注时，进行关注后的事件推送
           if($envent=='subscribe'){
             $wechat=$obj->ToUserName;
        
                $weixin[]=['wechat','=',$wechat];
                $data = Db::name( 'weixin' )->where($weixin)->find ();
				if(isset($data)){
				    $map["appid"]=$data["appid"];;
			     	$info = Db::name('focus')->where($map)->order('id desc')->find();
			     	//如果没有配置关注回复
					if(isset($info)){ 
						//如果关键词为空，那么就返回content的内容
						if($info ['content']){
							 $this->replyText($obj,$info['content']);
							 
						}
					}else{
						 $this->replyText($obj,'感谢您的关注');
						 
					}
					$this->saveUser($obj);
					
				}
				else{
					 $this->replyText($obj,'感谢您的关注');	
				}
		 }   
		   //用户已关注时的扫码事件推送,扫描带参数二维码
         if($envent=='SCAN'){
				
		 }
		  //3.取消关注事件
		 if($envent=='unsubscribe'){
				
		 }
		 //上报地理位置事件
		 if($envent=='LOCATION'){
				
		 }
		  //点击菜单事件
		 if($envent=='CLICK'){
				 $keyword=$obj->EventKey; 
			     //$this->replyKeyword($obj,$keyword); 
			     $this->replyMenu($obj,$keyword);
		 }
            
    }
    
       //保存用户名
	public function saveUser($obj){  
		$openid=$obj-> FromUserName;
	  	$wechat=$obj->ToUserName;
        
        $weixin[]=['wechat','=',$wechat];
        $info = Db::name( 'weixin' )->where($weixin)->find ();
		   if (cache('S_accessToken')) {
			 $access_token=cache('S_accessToken');
			 
		   }
			else{  
			  
			   $state = 'a-zA-Z0-9';
			 
			   $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=' . $info ['appid'] . '&secret=' . $info ['secret'];	
			   $ch1 = curl_init ();
			   $timeout = 5;
			   curl_setopt ( $ch1, CURLOPT_URL, $url );
			   curl_setopt ( $ch1, CURLOPT_RETURNTRANSFER, 1 );
			  curl_setopt ( $ch1, CURLOPT_CONNECTTIMEOUT, $timeout );
			   curl_setopt ( $ch1, CURLOPT_SSL_VERIFYPEER, FALSE );
			   curl_setopt ( $ch1, CURLOPT_SSL_VERIFYHOST, false );
			   $accesstxt = curl_exec ( $ch1 );
				curl_close ( $ch1 );
				$access = json_decode ( $accesstxt, true );//取得access_token
				if (empty ( $access ['access_token'] )) {
			   	addUserLog ( "获取access_token失败,请确认AppId和Secret配置是否正确,然后再重试：" .  var_export($res, true ) ,1 );
				}else{
					$access_token=$access ['access_token'];
				    cache('S_accessToken',$access_token,7200);//2小时过期
				}
			}
		
				 // 拉取用户信息(需scope为 snsapi_userinfo)
				//$data= $this->get_user_info($access_token , $open_id ); 
			 $url = 'https://api.weixin.qq.com/cgi-bin/user/info?access_token=' . $access_token . '&openid=' . $openid . '&lang=zh_CN';
              
             $ch1 = curl_init ();
		     $timeout = 5;
		     curl_setopt ( $ch1, CURLOPT_URL, $url );
		     curl_setopt ( $ch1, CURLOPT_RETURNTRANSFER, 1 );
		     curl_setopt ( $ch1, CURLOPT_CONNECTTIMEOUT, $timeout );
		     curl_setopt ( $ch1, CURLOPT_SSL_VERIFYPEER, FALSE );
		     curl_setopt ( $ch1, CURLOPT_SSL_VERIFYHOST, false );
		     $data = curl_exec ( $ch1 );
		     curl_close ( $ch1 );
		      $user = json_decode ( $data, true );//取得access_token
		       if($user["subscribe"]){
		       	$save["openid"]=$user["openid"];
		       	if(!Db::name( 'Follow' )->where($save)->find()){
			        $save["nickname"]=$user["nickname"];
			        $save["headimgurl"]=$user["headimgurl"];
			     	 $save["openid"]=$user["openid"];
			     	 $save["language"]=$user["language"];
			     	 $save["nickname"]=$user["nickname"];
			     	 $save["city"]=$user["city"];
					 //保存微信用户粉丝信息
					 $save["appid"]=$info["appid"];
					 $save["status"]=1; 
					 $save["openid"]=$user["openid"];
					 $save["subscribe_time"]=$user["subscribe_time"];
					 $id = Db::name( 'Follow' )->insertGetId($save); 
					 addUserLog ( "yhu：" . $id ,1 );
		         }
		     
		       }
				 //$user=Db::name( 'Follow' )->where ($map )->getField('uid');
				 //$result=Db::name('UcenterDb::nameember')->where("id=$user[uid]")->setField('username',$data['nickname']);
				 				
        }
    public function replyMenu($obj,$keyword=''){
     
	  
        //$where[]=['appid','=',$obj->ToUserName];
        $wechat=$obj->ToUserName;
        
        $weixin[]=['wechat','=',$wechat];
        $data = Db::name( 'weixin' )->where($weixin)->find ();
        if($data){
        	$appid=$data["appid"];
        }
        else{
             $this->replyText($info['content'], "配置错误");	
        }
        $where[]=['keyword','=', $keyword];
        $where[]=['appid','=',$appid];
        $info = Db::name('news')->where($where)->find();
      
							  $src= get_cover($info["cover_id"],'path');
							  
							  $url=root_url().url('weixin/news/detail?id='.$info['id']);
							  
							   $articles['title']= $info['title'];
                               $articles['description']=$info['des'];
                               $articles['picUrl']=$src;
                               $articles['url']=$url;
						
							   $this->replyNews($obj,$articles); 
    	
    } 
    
   public function replyKeyword($obj,$keyword=''){
     
	  
        //$where[]=['appid','=',$obj->ToUserName];
        $wechat=$obj->ToUserName;
        
        $weixin[]=['wechat','=',$wechat];
        $data = Db::name( 'weixin' )->where($weixin)->find ();
        if($data){
        	$appid=$data["appid"];
        }
        else{
             $this->replyText($info['content'], "配置错误");	
        }
        $where[]=['keyword','=', $keyword];
        $where[]=['appid','=',$appid];
        $data = Db::name('answer')->where($where)->find(); 
       if($data){
		   $type = $data['type'];
		   $map[]= ['keyword','=',$keyword];
		   $map[]=['appid','=',$appid];
				switch ($type) {
                
				
				      /**
					 * 文本回复
					 */
					case 'text':
						  $info = Db::name("Text")->where ( $map )->order('id desc')->find ();
						  $this->replyText($obj,$info['content']);
						  //return array($info['content'], 'text');
						  break;
					/**
					 * 单条图文回复
					 */
					case 'news':
					 
							  $info = Db::name ( 'news' )->where ( $map )->order("id desc")->find ();
							  $src= get_cover($info["cover_id"],'path');
							  
							  $url=root_url().url('weixin/news/detail?id='.$info['id']);
							  
							   $articles['title']= $info['title'];
                               $articles['description']=$info['des'];
                               $articles['picUrl']=$src;
                               $articles['url']=$url;
						
							   $this->replyNews($obj,$articles); 
						   
						  break;
					 /**
					 * 多图文
					 */
					case 'images':
						   $images= Db::name('images')->where ( $map )->find ();
						   $map2[]= ['id','in', $images ['content'] ];
						   $list = Db::name ( 'news' )->where ( $map2)->select ();
						 
						   unset($array);
						   $array=array();
						   foreach ( $list as $k => $info ) {
						   	 $src= get_cover($info["cover_id"],'path');
							  
							  $url=root_url().url('weixin/news/detail?id='.$info['id']);
							   $articles=[];
							   $articles['title']= $info['title'];
                               $articles['description']=$info['des'];
                               $articles['picUrl']=$src;
                               $articles['url']=$url;
						   	   //array_push($array, $articles);
							   $array [] = $articles;
								 
							}
							//$this->replyText($obj,$array[0]["picUrl"]);
						   $this->replyImage($obj,$array);
						    break;
				
                        break;
						default:
					  return array($keyword,'text'); 
						break;
				}
        }else{
		
		  
			 
			  $array['title']="无应答回复测试";
               $array['description']="asda";
               $array['picUrl']="https://x0.ifengimg.com/ucms/2019_45/027607c6-23c4-4116-959d-4ce46b3d784e_ADA8B2A1A7BE4DEEC9A132E6D311151EF5B9BCCA_w1024_h682.jpg";
               $array['url']="https://demo.yershop.com/index.php/weixin/news/detail/status/0/id/1.html";
		
			    $this->replyNews($obj,$array);
	 
			 
		}
		
    }
    
          public function replyText($obj,$text){
            $tpl = "<xml>
                <ToUserName><![CDATA[%s]]></ToUserName>
                <FromUserName><![CDATA[%s]]></FromUserName>
                <CreateTime>%s</CreateTime>
                <MsgType><![CDATA[text]]></MsgType>
                <Content><![CDATA[%s]]></Content>
                <FuncFlag>%d</FuncFlag>
                </xml>";
    $result= sprintf($tpl, $obj->FromUserName, $obj->ToUserName, time(), $text, 0);
    echo $result;
}	
      public function replyNews($obj,$array){
   
 $html= "<xml>
                <ToUserName><![CDATA[%s]]></ToUserName>
                <FromUserName><![CDATA[%s]]></FromUserName>
                <CreateTime>%s</CreateTime>
                <MsgType><![CDATA[news]]></MsgType>
                <ArticleCount>1</ArticleCount>
                <Articles>";
$obj1= sprintf($html, $obj->FromUserName, $obj->ToUserName, time());				
$html= "<item>
                <Title><![CDATA[%s]]></Title> 
                <Description><![CDATA[%s]]></Description>
                <PicUrl><![CDATA[%s]]></PicUrl>
                <Url><![CDATA[%s]]></Url>
                </item>";
$title = $array['title'];
$desc = $array['description'];
$picUrl = $array['picUrl'];
$url = $array['url'];
$obj2= sprintf($html, $title, $desc, $picUrl, $url);			
$html = "</Articles>
                <FuncFlag>0</FuncFlag>
                </xml>";
$obj3 =$html;
    echo $obj1.$obj2.$obj3;
}

      public function replyImage($obj,$array){
      
	$n = count($array);	
	$n = $n < 10 ? $n : 10;
if(!is_array($array)){
             return;
         }
        $itemTpl = "    <item>
        <Title><![CDATA[%s]]></Title>
        <Description><![CDATA[%s]]></Description>
         <PicUrl><![CDATA[%s]]></PicUrl>
        <Url><![CDATA[%s]]></Url>
     </item>";

      $item_str = "";
       foreach ($array as $item){
             $item_str .= sprintf($itemTpl, $item['title'], $item['description'], $item['picUrl'], $item['url']);
       }
        $newsTpl = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
 <FromUserName><![CDATA[%s]]></FromUserName>
 <CreateTime>%s</CreateTime>
 <MsgType><![CDATA[news]]></MsgType>
<Content><![CDATA[]]></Content>
300 <ArticleCount>%s</ArticleCount>
 <Articles>
 $item_str</Articles>
 </xml>";
        $result = sprintf($newsTpl, $obj->FromUserName, $obj->ToUserName, time(), count($array));
        
    echo  $result;
}
	
}
