<?php
namespace Wd;
/**
 * 七牛操作类
 */
class Qiniu{
	
	public function __construct($config=array()){
		vendor("qiniusdk.autoload");
    	foreach ($config as $k => $v) {
    		$this->$k=$v;
    	}
		$this->accessKey=isset($config['accessKey'])?$config['accessKey']:C('QINIU.accessKey');
		$this->secretKey=isset($config['secretKey'])?$config['secretKey']:C('QINIU.secretKey');
    }
	
	/**
	 * @description 抓图远程图片上传
	 * @param url 远程图片路径
	 * @param folder 文件夹
	 * @param key 文件全路径
	 * @return string
	 */
	public function fetch($param){
		$param['folder']=isset($param['folder'])?$param['folder']:'Uploads/'.date('Ym').'/'.date('d').'/';
		$auth = new \Qiniu\Auth($this->accessKey, $this->secretKey);
		$bmgr = new \Qiniu\Storage\BucketManager($auth);
		$bucket = 'chuansong';
		$key = isset($param['key'])?$param['key']:$param['folder'].md5($param['url']);
		list($re,$err) = $bmgr->fetch($param['url'], $bucket, $key);
		return $re;
    }
	
	
	// 管理列表
	public function lists(){
		// 记录当前列表页的cookie
		cookie('lists',U('lists',$_REQUEST));
		
		$m=D($this->model);
		$where=array();
		$order=$this->pk." desc";
		$count=$m->where($where)->count();
		$page       = new \Think\Page($count,20); //3.2
		$nowPage = I("p",1);
		$this->page  = $page->show();
		$this->list=$m->order($order)->where($where)->page($nowPage.','.$page->listRows)->select();
		$this->display();
		
		
    }
	
	
	
	//添加
	public function add(){
		$m = D($this->model);
		if(IS_POST){
			if($m->create() && $m->add()){
				$this->success('添加成功',Cookie('__forward__'));
			}else{
				$this->error($m->getError());
			}
			
		}else{
			$this->display();
		}
	}
	
	//修改
	public function mod($id){
		$m = D($this->model);
		if(IS_POST){
			if($m->create() && $m->save()){
				$this->success('修改成功',Cookie('__forward__'));
			}else{
				$this->error($m->getError());
			}
		}else{
			$this->modval = $m->find($id);
			$this->display();
		}
	}
	
	//删除
	public function del($ids){
		//数据准备
		$m = D($this->model);
		$where[$this->pk]=array('in',$ids);
		$m->where($where)->delete();
		$this->success('删除成功',Cookie('__forward__'));
	}

}