<?php

class CategoryAction extends CommonAction {
	
	//分類列表
	public function index() {

		//CategoryView 視圖模型
		$cate = D('CategoryView')->nofield('content')->order('category.sort,category.id')->select();
		//$cate = getCategory();
		import('Class.Category', APP_PATH);
		$this->cate = Category::toLevel($cate, '&nbsp;&nbsp;&nbsp;&nbsp;', 0);
		$this->display();
	}

	//添加分類
	public function add() {
	
		if (IS_POST) {
			$this->addPost();
			exit();
		}
		$this->pid = I('pid', 0, 'intval');
		$cate = M('category')->order('sort')->select();
		import('Class.Category', APP_PATH);
		$this->cate = Category::toLevel($cate, '---',0);
		$this->mlist = M('model')->where(array('status' => 1))->order('sort')->select();
		$this->groupList = M('membergroup')->order('rank')->select();
		$this->roleList = M('role')->order('id')->select();//管理員組
		$this->styleListList = getFileFolderList(APP_PATH . C('APP_GROUP_PATH') . '/Home/Tpl/' .C('cfg_themestyle') , 2, 'List_*');
		$this->styleShowList = getFileFolderList(APP_PATH . C('APP_GROUP_PATH') . '/Home/Tpl/' .C('cfg_themestyle') , 2, 'Show_*');
		$this->display();
	}

	//添加分類處理

	public function addPost() {

		$data = I('post.', '');
		$acc_groupid = I('acc_groupid', '');//會員組權限
		$acc_roleid = I('acc_roleid', '');//管理組權限

		
		$data['name'] = trim($data['name']);
		$data['ename'] = trim($data['ename']);		
		$data['type'] = empty($data['type'])? 0 : intval($data['type']);
		$pic = $data['catpic'] = I('catpic', '', 'htmlspecialchars,trim');

		if (isset($data['type']) && $data['type'] ==1 ) {
			$data['modelid'] = 0;
		}
		//M驗證
		if (empty($data['name'])) {
			$this->error('欄目名稱不能為空！');
		}


		if (empty($data['ename'])) {
			$data['ename'] = get_pinyin(iconv('utf-8','GBK//ignore',$data['name']),0);
		}elseif ($data['type'] == 0) {
			if (!ctype_alnum($data['ename'])) {
				$this->error('別名只能由字母和數字組成，不能包含特殊字符！');
			}
		}	
	

		if ($id = M('category')->add($data)) {
			//管理員組權限
			if (!empty($acc_roleid)) {
				$access = array();
				foreach ($acc_roleid as $v) {
					$tmp = explode(',', $v);
					$access[] = array(
							'catid' => $id,
							'roleid' => $tmp[1],
							'action' => $tmp[0],
							'flag' => 1,
							);
				}

				M('categoryAccess')->addAll($access);
			}

			//會員組權限
			if (!empty($acc_groupid)) {
				$access = array();
				foreach ($acc_groupid as $v) {
					$tmp = explode(',', $v);
					$access[] = array(
							'catid' => $id,
							'roleid' => $tmp[1],
							'action' => $tmp[0],
							'flag' => 0,
							);
				}
				M('categoryAccess')->addAll($access);
			}


			//更新上傳附件表
			if (!empty($pic)) {

				$pic = preg_replace('/!(\d+)X(\d+)\.jpg$/i', '', $pic);//清除縮略圖的!200X200.jpg後綴
				$attid = M('attachment')->where(array('filepath' => $pic))->getField('id');
				if($attid){
					M('attachmentindex')->add(array('attid' => $attid,'arcid' => $id, 'modelid' => 0, 'desc' => 'category'));
				}
			}

			getCategory(0,1);//清除欄目緩存
			getCategory(1,1);//清除欄目緩存
			getCategory(2,1);//清除欄目緩存
			$this->success('添加欄目成功<script type="text/javascript" language="javascript">window.parent.get_cate();</script>',U(GROUP_NAME. '/Category/index'));
		}else {
			$this->error('添加欄目失敗');
		}
		
	}


	//修改分類
	public function edit() {

		if (IS_POST) {
			$this->editPost();
			exit();
		}
		$id = I('id', 0, 'intval');
		$data = M('category')->find($id);
		if (!$data) {
			$this->error('記錄不存在');
		}
		$this->data = $data;
		$cate = M('category')->order('sort')->select();
		import('Class.Category', APP_PATH);
		$this->cate = Category::toLevel($cate, '---',0);
		$this->mlist = M('model')->where(array('status' => 1))->order('sort')->select();			
		$this->groupList = M('membergroup')->order('rank')->select();
		$this->roleList = M('role')->order('id')->select();//管理員組	

		$this->styleListList = getFileFolderList(APP_PATH . C('APP_GROUP_PATH') . '/Home/Tpl/' .C('cfg_themestyle') , 2, 'List_*');
		$this->styleShowList = getFileFolderList(APP_PATH . C('APP_GROUP_PATH') . '/Home/Tpl/' .C('cfg_themestyle') , 2, 'Show_*');
		
		$this->display();
	}



	//修改分類處理

	public function editPost() {

		$data = I('post.', '');		
		$id = $data['id'] = intval($data['id']);
		$pid = $data['pid'];		
		
		$acc_groupid = I('acc_groupid', '');//會員組權限
		$acc_roleid = I('acc_roleid', '');//管理組權限
		
		$data['name'] = trim($data['name']);
		$data['ename'] = trim($data['ename']);		
		$data['type'] = empty($data['type'])? 0 : intval($data['type']);
		$pic = $data['catpic'] = I('catpic', '', 'htmlspecialchars,trim');

		if (isset($data['type']) && $data['type'] ==1 ) {
			$data['modelid'] = 0;
		}

		if ($id == $pid) {
			$this->error('失敗！不能設置自己為自己的子欄目，請重新選擇父級欄目');
		}
		//M驗證
		if (empty($data['name'])) {
			$this->error('欄目名稱不能為空！');
		}

		if (empty($data['ename'])) {
			$data['ename'] = get_pinyin(iconv('utf-8','GBK//ignore',$data['name']),0);
		}elseif ($data['type'] == 0) {
			if (!ctype_alnum($data['ename'])) {
				$this->error('別名只能由字母和數字組成，不能包含特殊字符！');
			}
		}
	

		/*
		if (M('category')->where(array('name' => $data['name'], 'id' => array('neq' , $id)))->find()) {
			$this->error('欄目名稱已經存在！');
		}
		*/

		

		if (false !== M('category')->save($data)) {

			$msg = '';
			//判斷oldmodelid 與 modelid是否不變
			if ($data['oldmodelid'] != $data['modelid']) {
				$tablename = M('model')->where(array('id' => $data['oldmodelid']))->getField('tablename');
				if (!empty($tablename) && $tablename != 'page') {
					M($tablename)->where(array('cid' => $id))->delete();
					$msg = '!!!';
				}
			}

			//清除權限
			M('categoryAccess')->where(array('catid' => $id))->delete();
			//管理員組權限
			if (!empty($acc_roleid)) {
				$access = array();
				foreach ($acc_roleid as $v) {
					$tmp = explode(',', $v);
					$access[] = array(
							'catid' => $id,
							'roleid' => $tmp[1],
							'action' => $tmp[0],
							'flag' => 1,
							);
				}

				M('categoryAccess')->addAll($access);
			}

			//會員組權限
			if (!empty($acc_groupid)) {
				$access = array();
				foreach ($acc_groupid as $v) {
					$tmp = explode(',', $v);
					$access[] = array(
							'catid' => $id,
							'roleid' => $tmp[1],
							'action' => $tmp[0],
							'flag' => 0,
							);
				}
				M('categoryAccess')->addAll($access);
			}

			//del
			M('attachmentindex')->where(array('arcid' => $id, 'modelid' => 0, 'desc' => 'category'))->delete();
			//更新上傳附件表
			if (!empty($pic)) {

				$pic = preg_replace('/!(\d+)X(\d+)\.jpg$/i', '', $pic);//清除縮略圖的!200X200.jpg後綴
				$attid = M('attachment')->where(array('filepath' => $pic))->getField('id');
				if($attid){
					M('attachmentindex')->add(array('attid' => $attid,'arcid' => $id, 'modelid' => 0, 'desc' => 'category'));
				}
			}

			getCategory(0,1);//清除欄目緩存
			getCategory(1,1);
			getCategory(2,1);
			$this->success('修改欄目成功'. $msg .'<script type="text/javascript" language="javascript">window.parent.get_cate();</script>',U(GROUP_NAME. '/Category/index'));
		}else {
			$this->error('修改欄目失敗');
		}
		
	}

	//批量更新排序
	public function sort() {
		$sortlist = I('sortlist', array(), 'intval');
		foreach ($sortlist as $k => $v) {
			$data = array(
					'id' => $k,
					'sort' => $v,
				);
			M('category')->save($data);		
		}
		$this->redirect(GROUP_NAME. '/Category/index');
	}


	//修改分類處理

	public function del() {

		$id = I('id', 0, 'intval');

		//查詢是否有子類
		$childnum = M('category')->where(array('pid' => $id))->count();
		if ($childnum) {
			$this->error('刪除失敗：請先刪除本欄目下的子欄目');
		}
		$self = D('CategoryView')->field(array('modelid', 'tablename'))->where(array('category.id'=>$id))->find();
		if (!$self) {
			$this->error('欄目不存在');
		}
		$tablename = $self['tablename'];
		$modelid = $self['modelid'];

		if (M('category')->delete($id)) {
			$msg = '';
			if (!empty($tablename) && $tablename != 'page') {
				//刪除欄目下文檔之前，先刪除文章資源引用
				$arcid = M($tablename)->where(array('cid' => $id))->getField('id', true);
				if (!empty($arcid)) {
					M('attachmentindex')->where(array('modelid' => $modelid, 'arcid' => array('IN', $arcid)))->delete();
					
					M($tablename)->where(array('cid' => $id))->delete();
				}		
				$msg = '!!!';
			}
			M('categoryAccess')->where(array('catid' => $id))->delete();
			
			M('attachmentindex')->where(array('arcid' => $id, 'modelid' => 0, 'desc' => 'category'))->delete();

			//更新欄目緩存
			getCategory(0,1);
			getCategory(1,1);
			getCategory(2,1);
			$this->success('刪除欄目成功'. $msg .'<script type="text/javascript" language="javascript">window.parent.get_cate();</script>',U(GROUP_NAME. '/Category/index'));
		}else {
			$this->error('刪除欄目失敗');
		}		
	}


}




?>