<?php

class MembergroupAction extends CommonAction {
	
	public function index() {
					
		//分頁
		import('Class.Page', APP_PATH);
		$count = M('membergroup')->count();

		$page = new Page($count, 10);
		$page->rollPage = 7;
		$page->setConfig('theme','%totalRow% %header%  %first% %upPage% %linkPage% %downPage% %end% %nowPage%/%totalPage% 頁');
		$limit = $page->firstRow. ',' .$page->listRows;
		$list = M('membergroup')->order('rank,id')->limit($limit)->select();

		$this->page = $page->show();
		$this->vlist = $list;
		$this->type = '會員組列表';

		$this->display();
	}
	//添加
	public function add() {
		//當前控制器名稱		
		$actionName = strtolower($this->getActionName());
		if (IS_POST) {
			$this->addPost();
			exit();
		}
		$this->display();
	}

	//
	public function addPost() {
		//M驗證
		$validate = array(
			array('name','require','會員組名必須填寫！'), 
			array('name','','會員組名已經存在！',0,'unique',1), 
		);
		$db = M('membergroup');
		if (!$db->validate($validate)->create()) {
			$this->error($db->getError());
		}
		if($id = M('membergroup')->add()) {
			$this->success('添加成功',U(GROUP_NAME. '/Membergroup/index'));
		}else {
			$this->error('添加失敗');
		}
	}

	//編輯文章
	public function edit() {
		//當前控制器名稱
		$id = I('id', 0, 'intval');
		$actionName = strtolower($this->getActionName());

		if (IS_POST) {
			$this->editPost();
			exit();
		}
		
		$this->vo = M($actionName)->find($id);
		$this->display();
	}


	//修改文章處理
	public function editPost() {

		$name = I('name', '', 'trim');
		$id = I('id', 0, 'intval');
		if (empty($name)) {
			$this->error('會員組名必須填寫！');
		}
		
		if (M('membergroup')->where(array('name' => $name, 'id' => array('neq', $id)))->find()) {
			$this->error('會員組名已經存在！');
		}

		if (false !== M('membergroup')->save($_POST)) {
			$this->success('修改成功', U(GROUP_NAME. '/Membergroup/index', array('pid' => $pid)));
		}else {

			$this->error('修改失敗');
		}
		
	}



	//徹底刪除文章
	public function del() {

		$id = I('id',0 , 'intval');
		$batchFlag = intval($_GET['batchFlag']);
		//批量刪除
		if ($batchFlag) {
			$this->delBatch();
			return;
		}
		
		if (M('membergroup')->delete($id)) {
			$this->success('徹底刪除成功', U(GROUP_NAME. '/Membergroup/index'));
		}else {
			$this->error('徹底刪除失敗');
		}
	}


	//批量徹底刪除文章
	public function delBatch() {

		$idArr = I('key',0 , 'intval');		
		if (!is_array($idArr)) {
			$this->error('請選擇要徹底刪除的項');
		}
		$where = array('id' => array('in', $idArr));

		if (M('membergroup')->where($where)->delete()) {
			$this->success('徹底刪除成功', U(GROUP_NAME. '/Membergroup/index'));
		}else {
			$this->error('徹底刪除失敗');
		}
	}




}



?>