<?php
// +----------------------------------------------------------------------
// | yershop网店管理系统
// +----------------------------------------------------------------------
// | Copyright (c) 2018 http://www.yershop.com All rights reserved.
// +----------------------------------------------------------------------
// | 版权申明：yershop网店管理系统不是一个自由软件，是贝云网络官方推出的商业源码，严禁在未经许可的情况下
// | 拷贝、复制、传播、使用yershop网店管理系统的任意代码，如有违反，请立即删除，否则您将面临承担相应
// | 法律责任的风险。如果需要取得官方授权，请联系官方http://www.yershop.com
// +----------------------------------------------------------------------
namespace app\admin\controller;
use think\Controller;
use think\Db;
/**
 * 后台微信单一图文回复控制器
 */
class News extends Common{
     /* 微信单一图文回复查询首页 */
	public function index(){     
      if($_POST){
			foreach ($_POST as $key=>$value){
				if($value){
					$map[]  = [$key,'like', '%'.$value.'%'];
				 }
			}
        }
        $map=isset($map)?$map:'';
        $res=getLists('News',$map,10,'id desc',"");
	    $this->assign('res', $res);
		$this->meta_title="微信单一图文回复管理";
		$this->assign('meta_title', $this->meta_title);
	    return $this->fetch("news/index"); 
	}


    /* 编辑微信单一图文回复 */
	public function edit($id){   
	    if($_REQUEST){
		   $News = new \app\admin\model\News;
           $res=$News->allowField(true)->validate(true)->save($_REQUEST,['id' => $_REQUEST['id']]);
	       if($res){
			   addUserLog("edit_news",session_uid());
		      $this->success("更新成功！",cookie("__forward__"));
		   }else{
			  $error=$News->getError()?$News->getError():"更新失败！";
			  $this->error($error);
		   } 
	   }
	   else{
		 $map['id']=$id;
		 $info=db("News")->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("news/edit");
	   }
	}
	 /* 增加微信单一图文回复 */
	public function add($id=""){  
	   if($_REQUEST){
		  $News = new \app\admin\model\News;
            // 过滤post数组中的非数据表字段数据
          $res=$News->validate(true)->allowField(true)->save($_REQUEST);
	      if($res){
			  addUserLog("add_news",session_uid());
		      $this->success("新增成功！",cookie("__forward__"));
		  }else{
			  $error=$News->getError()?$News->getError():"新增失败！";
			  $this->error($error);
		  } 
	 }
	  else{
		
		  $this->meta_title="新增微信单一图文回复";
		    cookie("__forward__",input('server.HTTP_REFERER'));
		  $this->assign('meta_title', $this->meta_title);
	      return $this->fetch("news/edit");
	  }
	}
	 /* 删除微信单一图文回复*/
	public function del(){   
	    $id=input("id");
	    $map['id']=["in",$id];
		if(!$map["id"]){
			 $this->error("未选择数据！");
		}
		$model= request()->controller();
		$res=db($model)->where($map)->delete();
		
		if($res){
		   addUserLog("del_news",session_uid());
		   $this->success("删除成功！");
		}else{
	           $this->error("删除失败！");
		}
	}
	public function upload() {
		       $where[]=['appid','=',session("appid")];
               $info = Db::name( 'weixin' )->where($where)->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配置是否正确,然后再重试：");
				}else{
					$access_token=$access ['access_token'];
				  
				}
		$id = input('id');
		$path = get_cover_real($id,'path');
	
		//dump($access_token);
		$token = session("token");
        $url="https://api.weixin.qq.com/cgi-bin/media/upload?access_token={$access_token}&type=image";
		  $ch1 = curl_init ();
		  $timeout = 5;
		  $real_path="{$_SERVER['DOCUMENT_ROOT']}{$path}";$size=filesize($real_path);
		  $real_path=str_replace("/", "\\", $real_path);
		  	 $file_info = array('filename' =>$path, //国片相对于网站根目录的路径
        'content- type' => mime_content_type($real_path), //文件类型
        'filelength' => "{$size}"//图文大小
        );
		
		  $data= array("media"=>"@{$real_path}",'form-data'=>$file_info);
		  
		 $path = new \CURLFile($real_path);
$data = array('media'=>$path);
curl_setopt($ch1, CURLOPT_URL, $url);
curl_setopt($ch1, CURLOPT_POST, 1);
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);
curl_setopt($ch1, CURLOPT_POSTFIELDS, $data);
$result = curl_exec($ch1);
		
		  $result=json_decode($result,true);
		 if(isset($result["media_id"])){
			  $this->success($result["media_id"]);
		  } else {
			$this->error( '上传失败，错误的返回码是：' . $result ['errcode'] . ', 错误的提示是：' .$result ['errmsg'] );
		}
     
	}
}
