<?php 

/**
 * 名称：附件管理控制器
 * 作者：荷塘月色
 * 邮箱：kujiw@qq.com
 * 说明：
 */

namespace Admin\Controller;
class AttachmentController extends CommonController {

	public function index(){
		if (IS_POST) {
			$this -> ajaxReturn($this -> getData());
		}elseif (IS_GET) {
			$this -> display(I('tpl'));
		}
	}

	public function delete(){
		if (IS_POST) {
			$model = CONTROLLER_NAME;
			$ids = I('ids','');
			if (empty($ids)) {
				$this -> error('请选择要删除的数据！','',true);
			}
			if (is_array($ids)) {
				$map['id'] = array('in',$ids);
			} elseif (is_numeric($ids)) {
				$map['id'] = array('eq',$ids);
			}

			$m = M($model);
			$result = $m -> where($map) -> getField('id,savename,savepath,rootpath');
			if (empty($result)) $this -> error('未删除任何可删除的数据',U('index'),true);
			$m -> where($map) -> delete();
			foreach ($result as $key => $val) {
				$pathinfo = pathinfo('.'.$val['rootpath'].$val['savepath'].$val['savename']);
				$fs=glob($pathinfo['dirname'].'/'.$pathinfo['filename']."*.".$pathinfo['extension']);
				foreach ($fs as $k => $v) {
					@unlink($v);
				}
			}
			$this -> success('删除了权限范围内的 '.count($ids).' 条数据');
		}
	}

	public function ueditor(){
		$ueditor = new \Common\Vendor\Ueditor();
		$data = json_decode($ueditor->output(),true);
		$this -> ajaxReturn($data);
	}

	public function upload(){
		C('SHOW_PAGE_TRACE',false);
		C('TOKEN_ON',false);
		// 上传动作
		$config = C('UPLOAD_CONFIG');
		$upload = new \Think\Upload($config);// 实例化上传类
		$info   =   $upload->upload();
		if (!$info) {
			$this -> error($upload->getError(),'',true);
		}else{
			// 上传信息插入到数据库
			$m = D('Attachment','RelationModel');
			if (false === $data = $m -> create($info['file'])) {
				$this -> error($m -> getError(),'',true);
			}else{
				$m -> rootpath = isset($config['rootpath'])?$config['rootpath']:'/Uploads';
				$m -> add();
				$data['id'] = $m -> getLastInsID();
				$this -> success($data,'',true);
			}
		}
	}
}