<?php
namespace app\admin\controller;
use think\Controller;
use think\Db;
/**
 * 后台微信自定义菜单控制器
 */
class Menu extends Common{
     /* 微信自定义菜单查询首页 */
	public function index(){     
     	$where[]=['appid','=',session("appid")];
        $info = Db::name( 'menu' )->where($where)->find ();
      
        if(isset($info)){
        	$info["saveurl"]=url('edit');
        	
        } else{
        		$info["saveurl"]=url('add');
        	
        }
        $list= Db::name( 'news' )->where($where)->field('keyword,cover_id,des,title,create_time')->select ();
        $this->assign('list', $list);
      
        $this->assign('info', $info);
		$this->meta_title="微信自定义菜单管理";
		$this->assign('meta_title', $this->meta_title);
	    return $this->fetch("menu/index"); 
	}


    /* 编辑微信自定义菜单 */
	public function edit($id){   
	    if($_POST){
		   $Menu = new \app\admin\model\Menu;$this->send();
           $res=$Menu->allowField(true)->validate(true)->save($_POST,['id' => $_POST['id']]);
	       if($res){
	       	
	       	
			   addUserLog("edit_menu",session_uid());
		      $this->success("更新成功！",cookie("__forward__"));
		   }else{
			  $error=$Menu->getError()?$Menu->getError():"更新失败！";
			  $this->error($error);
		   } 
	   }
	   else{
		 $map['id']=$id;
		 $info=db("Menu")->where($map)->find();
	     $this->assign('info', $info);
		
		   cookie("__forward__",input('server.HTTP_REFERER'));
		 $this->meta_title="编辑微信自定义菜单";
		 $this->assign('meta_title', $this->meta_title);
	     return $this->fetch("menu/edit");
	   }
	}
	 /* 增加微信自定义菜单 */
	public function add($id=""){  
	   if($_POST){
		  $Menu = new \app\admin\model\Menu;
		  $this->send();
            // 过滤post数组中的非数据表字段数据
          $res=$Menu->validate(true)->allowField(true)->save($_POST);
	      if($res){
			  addUserLog("add_menu",session_uid());
		      $this->success("新增成功！",cookie("__forward__"));
		  }else{
			  $error=$Menu->getError()?$Menu->getError():"新增失败！";
			  $this->error($error);
		  } 
	 }
	  else{
		
		  $this->meta_title="新增微信自定义菜单";
		    cookie("__forward__",input('server.HTTP_REFERER'));
		  $this->assign('meta_title', $this->meta_title);
	      return $this->fetch("menu/edit");
	  }
	}
	
	
// 发送菜单到微信
function send() {
	
	    $str=$_POST["content"];
	 
	    $data=str_replace('{"menu":','',$_POST["content"]);
	    $data=substr($data,0,-1);
	    
	    //$data=str_replace('}]}]}}','}]}]}',$_POST["content"]);
	 
		$map ['appid'] = session("appid");
		$info = Db::name( 'weixin' )->where ( $map )->find ();
		$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'] )) {
			$this->error ( '获取access_token失败,请确认AppId和Secret配置是否正确,然后再重试。' );
		}
		
		//先删除已有的自定义菜单
		file_get_contents ( 'https://api.weixin.qq.com/cgi-bin/menu/delete?access_token=' . $access ['access_token'] );
		//需要提交的url	
		$url = 'https://api.weixin.qq.com/cgi-bin/menu/create?access_token=' . $access ['access_token'];
		$header [] = "content-type: application/x-www-form-urlencoded; charset=UTF-8";		
		$ch = curl_init ();
		curl_setopt ( $ch, CURLOPT_URL, $url );
		curl_setopt ( $ch, CURLOPT_CUSTOMREQUEST, "POST" );
		curl_setopt ( $ch, CURLOPT_SSL_VERIFYPEER, FALSE );
		curl_setopt ( $ch, CURLOPT_SSL_VERIFYHOST, FALSE );
		curl_setopt ( $ch, CURLOPT_HTTPHEADER, $header );
		curl_setopt ( $ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)' );
		
		curl_setopt ( $ch, CURLOPT_AUTOREFERER, 1 );
		curl_setopt ( $ch, CURLOPT_POSTFIELDS,  $data);
		curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, true );
		$res = curl_exec ( $ch );
		curl_close ( $ch );
		$res = json_decode ( $res, true ); 
		if ($res ['errcode'] == 0) {
		   //	$this->success ( '发送菜单成功' );n
		   return 1;
		} else {
			$this->error ( '发送菜单失败，错误的返回码是：' . $res ['errcode'] . ', 错误的提示是：' . $res ['errmsg'] );
			exit();
		}
	}	
	
}
