<?php
// +----------------------------------------------------------------------
// | 贝云cms内容管理系统
// +----------------------------------------------------------------------
// | Copyright (c) 2017 http://www.bycms.cn All rights reserved.
// +----------------------------------------------------------------------
// | 版权申明：贝云cms内容管理系统不是一个自由软件，是贝云网络官方推出的商业源码，严禁在未经许可的情况下
// | 拷贝、复制、传播、使用贝云cms内容管理系统的任意代码，如有违反，请立即删除，否则您将面临承担相应
// | 法律责任的风险。如果需要取得官方授权，请联系官方http://www.bycms.cn
// +----------------------------------------------------------------------
namespace app\admin\controller;
use think\Db;
use think\File;
use think\Validate;
use OSS\OssClient;
use OSS\Core\OssException;
use Qiniu\Auth;
use Qiniu\Storage\UploadManager;
/**
 * 文件控制器
 * 主要用于下载模型的文件上传和下载
 */
class Attachment extends Home{

    public function index(){ 
		
        if($_POST){
			foreach ($_POST as $key=>$value){
				if($value){
					$map[]  = [$key,'like', '%'.$value.'%'];
				 }
			}
        }
		$map=isset($map)?$map:'';
		
        $res=getLists('Attachment',$map,10,'id desc',"");
	    $this->assign('res', $res);
		$this->meta_title="附件资源管理";
		$this->assign('meta_title', $this->meta_title);
	    return $this->fetch(); 
	}


    /* 编辑导航 */
	public function edit($id){   
	    if($_POST){
		   $Attachment = new \app\admin\model\Attachment;
           $res=$Attachment->allowField(true)->validate(true)->save($_POST,['id' => $_POST['id']]);
	       if($res){
			   addUserLog("edit_Attachment",session_uid());
		      $this->success("更新成功！",cookie("__forward__"));
		   }else{
			  $error=$Attachment->getError()?$Attachment->getError():"更新失败！";
			  $this->error($error);
		   } 
	   }
	   else{
		 $map['id']=$id;
		 $info=db("Attachment")->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();
	   }
	}
	 /* 增加导航 */
	public function add($id=""){  
	   if($_POST){
		  $Attachment = new \app\admin\model\Attachment;
            // 过滤post数组中的非数据表字段数据
          $res=$Attachment->validate(true)->allowField(true)->save($_POST);
	      if($res){
			  addUserLog("add_Attachment",session_uid());
		      $this->success("新增成功！",cookie("__forward__"));
		  }else{
			  $error=$Attachment->getError()?$Attachment->getError():"新增失败！";
			  $this->error($error);
		  } 
	 }
	  else{
		  $this->meta_title="新增导航";
		  cookie("__forward__",input('server.HTTP_REFERER'));
		  $this->assign('meta_title', $this->meta_title);
	      return $this->fetch("Attachment/edit");
	  }
	}
	 /* 删除导航*/
	public function del(){   
	    $id=input("id");
	    $map[]=['id',"in",$id];
		if(!$map){
			 $this->error("未选择数据！");
		}
		$res=db("Attachment")->where($map)->delete();
		if($res){
		   addUserLog("del_Attachment",session_uid());
		   $this->success("删除成功！");
		}else{
			 $this->error("删除失败！");
		}
	}
	
	
	  /* 文件上传 */
    public function update(){
		$name=input("name")?input("name"):"file";
		$name="file";
		if ((($_FILES["file"]["type"] == "image/gif")
		|| ($_FILES["file"]["type"] == "image/jpeg")
		|| ($_FILES["file"]["type"] == "image/pjpeg")|| ($_FILES["file"]["type"] == "image/png"))
		){
		   $model="picture";//图片文件
		   $data["type"]=1;
		}
		else if(($_FILES["file"]["type"] == "video/mp4")){
		   $model="media";//媒体文件
		   $data["type"]=2;
		}
		else{
		   $model="attachment";//压缩文件等
		   $data["type"]=3;
		}
		$file = request()->file($name);
        if(!$name){
            $this->error('参数错误！');
        }
      // 移动到框架应用根目录/uploads/ 目录下
        $info =$file->validate(['size'=>300*1024*1024,'ext'=>'zip,rar,mp4,MP4,mp3,flv,jpg,png,gif,doc,pdf,excel,ppt'])->move(ROOT_PATH . 'public/uploads/'.$model);
        if($info){
            // 成功上传后 获取上传信息
              $path="public/uploads/".$model."/".$info->getSaveName();
              $data["path"]='/'.str_replace("\\","/",$path);
			  $data["oldname"]=$_FILES[$name]["name"];
			  $data["exts"]=$info->getExtension();
		      $data["status"]=1;
			  $data["size"]=$_FILES[$name]["size"];
		      $data["create_time"]=time();
			  $id=db('attachment')->insertGetId($data);
				// 返回
			header('content-type:application/json;charset=utf-8');
			$INSTALL_PATH = str_replace('\\','/',dirname($_SERVER['SCRIPT_NAME']));
			if($INSTALL_PATH==="/"){
				  $INSTALL_PATH="";		
			}else{
				$INSTALL_PATH= '/'. trim($INSTALL_PATH,'/').'';
			}
			$data = array('path'=>$INSTALL_PATH.$data["path"],'msg'=>'上传成功','id'=>$id,"status"=>200);
			echo json_encode($data);

        }else{
            // 上传失败获取错误信息
			$msg=$file->getError();
			$data = array('path'=>'','msg'=>$msg,"code"=>0);
			header('Content-Type:application/json; charset=utf-8');
			print_r( json_encode($data,JSON_UNESCAPED_UNICODE));
            //echo json_encode($data);
        }
    }
   
 /* 文件上传阿里oss */
   public function insert(){
       // 阿里云主账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维，请登录 https://ram.console.aliyun.com 创建RAM账号。
			$accessKeyId = api("ACCESSID");
			$accessKeySecret =api("ACCESSKEY");
			// Endpoint以杭州为例，其它Region请按实际情况填写。
			$endpoint = api("SERVERURL");//"http://oss-cn-hangzhou.aliyuncs.com";
			// 存储空间名称
			$bucket= "yershop";
			// 文件名称			
			// <yourLocalFile>由本地文件路径加文件名包括后缀组成，例如/users/local/myfile.txt
			
		   $name =$_FILES['file']['name']; 
		   $exts = strrchr($name, '.');	   
		   $object= 'public/uplaod/picture/' . date("Ymd") . '/' . sha1(date('YmdHis', time()) . uniqid()) . $exts;
            if ($file) {
               
                // 尝试执行
                try {
                    $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);
                    //执行阿里云上传获取返回结果
                    $result = $ossClient->uploadFile($bucket, $object, $_FILES['file']['tmp_name']);
					   //将结果返回            
              $data["path"]=$result['info']['url'];
			  $data["oldname"]=$_FILES["file"]["name"];
			  $data["exts"]=$exts;
		      $data["status"]=1;
			  $data["size"]=$_FILES["file"]["size"];
		      $data["create_time"]=time();
			  $id=db('attachment')->insertGetId($data);
				// 返回
			header('content-type:application/json;charset=utf-8');
			$INSTALL_PATH = str_replace('\\','/',dirname($_SERVER['SCRIPT_NAME']));
			if($INSTALL_PATH==="/"){
				  $INSTALL_PATH="";		
			}else{
				$INSTALL_PATH= '/'. trim($INSTALL_PATH,'/').'';
			}
			$data = array('path'=>$INSTALL_PATH.$data["path"],'msg'=>'上传成功','id'=>$id,"status"=>200);
			echo json_encode($data);
                } catch (OssException $e) {
                 
					$msg=$e->getMessage();
			        $data = array('path'=>'','msg'=>$msg,"code"=>0);
                    echo json_encode($data);
                }
             

            }
       
			
    
}
 function upfile()
    {
        $file = request()->file('file');
        $path = $file->getRealPath();
        $ext = pathinfo($file->getInfo('name'), PATHINFO_EXTENSION);
        $key = date('Ymd') . '/' .  sha1(date('YmdHis', time()) . uniqid()) . '.' . $ext;
        $url =  api("QDOMAIN");
        include(ROOT_PATH.'extend/Qiniu/autoload.php');
        $accessKey = api("QACCESSKEY");
        $secretKey = api("QSECRETKEY");
        $auth = new Auth($accessKey, $secretKey);
        $bucket =  api("QBUCKET");
        $token = $auth->uploadToken($bucket);
        $upload = new UploadManager();
        list($ret, $err) = $upload->putFile($token, $key, $path);
        if (!$err) {
			  $data["path"]=$url . '/' . $ret['key'];
			  $data["oldname"]=$_FILES["file"]["name"];
			  $data["exts"]=$exts;
		      $data["status"]=1;
			  $data["size"]=$_FILES["file"]["size"];
		      $data["create_time"]=time();
			  $id=db('attachment')->insertGetId($data);
				// 返回
			header('content-type:application/json;charset=utf-8');
			$INSTALL_PATH = str_replace('\\','/',dirname($_SERVER['SCRIPT_NAME']));
			if($INSTALL_PATH==="/"){
				  $INSTALL_PATH="";		
			}else{
				$INSTALL_PATH= '/'. trim($INSTALL_PATH,'/').'';
			}
			$data = array('path'=>$INSTALL_PATH.$data["path"],'msg'=>'上传成功','id'=>$id,"status"=>200);
           echo json_encode($data);
        }else{
			
			        $data = array('path'=>'','msg'=>"上传失败","code"=>0);
                    echo json_encode($data);
			
		}
    }


}
