<?php
class CategoryModel extends DBModel {
	public function init(){
	}
	public function Add($POST){
		if (is_array($POST)){
			if (empty($POST['category'])){
				$this->error = _('请填写分类名!');
				return false;
			}
			$select = $this->_DB->select();
			$sql = $select->from(VODCMS_CATEGORY)->where('parentid='.$POST['parentid'])->order('sort DESC')->limit(1)->toString();
			$rs  = $this->_DB->fetRow($sql);
			$POST['sort'] = $rs['sort']+1;
			$POST['link'] = trim($POST['link']);
			unset($rs,$sql);
			$rows = $this->_DB->insert(VODCMS_CATEGORY, $POST);
			$id = $this->_DB->lastInsertId();
			$select = $this->_DB->select();
			$sql = $select->from(VODCMS_CATEGORY)->where('id='.$POST['parentid'])->order('sort ASC')->limit(1)->toString();
			$rs  = $this->_DB->fetRow($sql);
			$lable = $rs['lable'] ? $rs['lable'].','.$id : $id;
			$sql = "UPDATE ".VODCMS_CATEGORY." SET lable = '".$lable."' WHERE id=$id";
			$this->_Response->setCookie('forget_categoryid', $POST['parentid']);	//设置记住分类
			$this->_DB->Exec($sql);
			$this->setCache();
			$this->updateNodes();	//更新节点数
			Easy_Cache::clear(); //清理缓存
			return $id;
		}else{
			$this->error = _('传入添加分类方法不正确!传入值不是一个数组!');
			return false;
		}
	}
	/*获取所有
	*/
	public function getAll($where=null){
		$select = $this->_DB->select();
		$select->from(VODCMS_CATEGORY)->where($where)->order('sort ASC ,id DESC');
		$sql = $select->tostring();
		return $this->_DB->fetAll($sql);
	}
	/*
	建立下拉菜单
	*/
	public function CreateOption($parentid, $id, $prefix=''){
		$select = $this->_DB->select();
		$sql = $select->from(VODCMS_CATEGORY)->where('parentid='. (int)$parentid.' AND link=\'\'')->order('sort ASC ,id DESC')->toString();
		//echo $sql;
		$all = $this->_DB->fetAll($sql);
		$data = '';
		foreach ($all as $row){
			if ($id == $row['id']){
				$data.='<option value="'.$row['id'].'" selected="selected" >'.$prefix.$row['category'].'</option>';
			}else{
				$data.='<option value="'.$row['id'].'" >'.$prefix.$row['category'].'</option>';
			}
			$data.= $this->CreateOption($row['id'], $id, $prefix.'&nbsp;&nbsp;');
		}
		return $data;
	}
	/*创建不允许选择父分类的列表*/
	public function CreateOptions($parentid, $id, $prefix=''){
		$select = $this->_DB->select();
		$sql = $select->from(VODCMS_CATEGORY)->where('link = \'\' and  parentid='. (int)$parentid)->order('sort,id DESC')->toString();
		//echo $sql;
		$all = $this->_DB->fetAll($sql);
		$data = '';
		foreach ($all as $row){
			if ($id == $row['id']){
				if ($row['nodes'] > 0){
					$data.='<optgroup label="'.$row['category'].'" >'.$this->CreateOption($row['id'], $id).'</optgroup>';
				}else{
					$data.='<option value="'.$row['id'].'" selected="selected" >'.$prefix.$row['category'].'</option>'.$this->CreateOption($row['id'], $id);
				}
			}else{
				if ($row['nodes'] > 0){
					$data.='<optgroup label="'.$row['category'].'" >'.$this->CreateOption($row['id'], $id).'</optgroup>';
				}else{
					$data.='<option value="'.$row['id'].'" >'.$prefix.$row['category'].'</option>'.$this->CreateOption($row['id'], $id);
				}
			}
		}
		return $data;
	}
	/*
	更新分类子类个数
	*/
	public function updateNodes($where=null){
		$select = $this->_DB->select();
		$sql = $select->from(VODCMS_CATEGORY)->where($where)->order('sort ASC,id DESC')->toString();
		$all = $this->_DB->fetAll($sql);
		foreach ($all as $row){
			$sql = "SELECT * FROM ".VODCMS_CATEGORY." WHERE lable like '".$row['lable'].",%'";
			$total = $this->_DB->getCount($sql);
			$this->_DB->update(VODCMS_CATEGORY, array('nodes'=>$total), 'id='.$row['id']);
		}
		unset($all);
	}
	/*
	获取指定条件的参数
	*/
	public function getRow($where=null){
		$select = $this->_DB->select();
		$select->from(VODCMS_CATEGORY)->where($where)->limit(1);
		$sql = $select->toString();
		return $this->_DB->fetRow($sql);
	}
	/*
	修改分类信息
	$POST 必须包括分类的ID
	*/
	public function modify($POST){
		if (is_array($POST)){
			if (empty($POST['category'])){
				$this->error = _('请填写分类名!');
				return false;
			}
			if ($POST['id'] == $POST['parentid']){
				$this->error = _('不能选择自身作为父分类!');
				return false;
			}
			$select = $this->_DB->select();
			$sql = $select->from(VODCMS_CATEGORY)->where('parentid='.$POST['parentid'])->order('sort DESC')->limit(1)->toString();
			$rs  = $this->_DB->fetRow($sql);
			unset($rs,$sql);
			$POST['link'] = trim($POST['link']);
			$rows = $this->_DB->update(VODCMS_CATEGORY, $POST, 'id='.$POST['id']);
			$select = $this->_DB->select();
			$sql = $select->from(VODCMS_CATEGORY)->where('id='.$POST['parentid'])->order('sort DESC')->limit(1)->toString();
			$rs  = $this->_DB->fetRow($sql);
			$lable = $rs['lable'] ? $rs['lable'].','.$POST['id'] : $POST['id'];
			$sql = "UPDATE ".VODCMS_CATEGORY." SET lable = '".$lable."' WHERE id=".$POST['id'];
			$row = $this->_DB->Exec($sql);
			$this->setCache();
			$this->updateNodes();	//更新节点数
			return $row;
		}else{
			$this->error = _('传入添加分类方法不正确!传入值不是一个数组!');
			return false;
		}
	}
	/*
	反转分类状态
	*/
	public function locked($id){
		$sql = 'UPDATE '.VODCMS_CATEGORY.' SET locked = not(locked) WHERE id='.$id;
		$row = $this->_DB->Exec($sql);
		$this->setcache();
		$this->updateNodes();	//更新节点数
		return $row;
	}
	/*
	删除指定编号的分类
	删除时需判断是否有影片
	删除时判断是否有子类
	*/
	public function delete($id){
		$select = $this->_DB->select();
		$sql = $select->from(VODCMS_CATEGORY)->where('id='.$id)->toString();
		$row = $this->_DB->fetRow($sql);
		if ($row['nodes']>0){
			$this->error = _('该分类尚有'.$row['nodes'].'个子类.必须先删除子类才能删除!');
			return false;
		}
		if ($row['moviecount'] > 0){
			$this->error = _('该分类尚有'.$row['moviecount'].'个节目.必须先转移分类节目或者删除节目才能删除!');
			return false;
		}
		$row =  $this->_DB->delete(VODCMS_CATEGORY, 'id='.$id);
		$this->setcache();
		$this->updateNodes();	//更新节点数
		return $row;
	}
	/*
	根据传入ID返回该分类的路径数组
	*/
	public function getLocation($id){
		$select = $this->_DB->select();
		$sql = $select->from(VODCMS_CATEGORY, 'lable')->where('id='.(int)$id)->toString();
		//echo $sql;
		$row = $this->_DB->fetRow($sql);
		if ($row){
			$lable = $row['lable'];
			$select = $this->_DB->select();
			$sql = $select->from(VODCMS_CATEGORY, 'id,category')->where("id in ($lable)")->toString();
			return $this->_DB->fetAll($sql);
		}else{
			return array();
		}
	}
	/*
	根据传入的数组进行更新排序
	*/
	public function sort($array){
		$i=1;
		foreach($array as $val){
			$this->_DB->update(VODCMS_CATEGORY, array('sort'=>$i), 'id='.intval($val));
			$i++;
		}
	}
	/*
	将源分类的影片全部转移到目标分类下
	待完成
	*/
	public function merge($sourceid, $targetid){
		
	}
	/*
	根据ID返回自身以及所有的子类ID
	返回类型为一维数组
	*/
	public function getChilds($id){
		/*if ($id){
			if (intval($id)>0){
				$row = $this->getRow('id='.$id);
			}else{
				$row = $this->getRow(array('category'=> $id));
			}
			$lable = $row['lable'];
			$data = $this->getAll(" lable LIKE '".$lable."%'");
			foreach ($data as $row){
				$ids[]= $row['id'];
			}
			unset($data, $row, $lable);
			return $ids;
		}else{
			return array();
		}*/
		$array = $this->getCache();
		$str = array();
		foreach($array as $row){
			if (in_array($id, explode(',', $row['lable']))){
				$str[]= $row['id'];
			}
		}
		unset($array);
		return $str;
	}
	/*
	合并一个分类或者多个分类到其他分类中
	返回影响记录的行数
	*/
	public function catergoryMerge($src, $target){
		if (is_array($src) === false){
			$src = array($src);
		}
		if (is_array($target) === false){
			$target = array($target);
		}
		$num = 0;
		for ($i=0;$i<count($target);$i++){
				if ($target[$i]){
				 $sql = 'UPDATE '.VODCMS_MCLASSID.' SET category='.$target[$i].' WHERE category='.(int)$src[$i];
				 $num = $num + $this->_DB->exec($sql);
				}
		}
		$mov = new MovieModel();
		$mov->initCategory();	//初始化影片分类
		$mov->initmovie();
		return $num;
	}
	/*设置分类的缓存数据*/
	public function setCache(){
		foreach($this->getAll('locked=0') as $row){
			$data[$row['id']] = $row;
		}
		$data = serialize($data);
		Easy_Cache::set('category', $data);
		unset($data);
	}
	/*
	获取分类的缓存数据
	*/
	public function getCache(){
		if (Easy_Cache::isCache('category')===false){
			$this->setCache();
		}
		return unserialize(Easy_Cache::get('category'));
	}
	/*初始化分类树结构*/
	public function initLable(){
		$data = null;
		foreach($this->getAll() as $row){
			$rs = $this->getRow('id='.$row['parentid']);
			if ($rs['id']){
				$data['lable'] = $rs['lable'].','.$row['id'];
			}else{
				$data['lable'] = $row['id'];
			}
			$data['link'] = $row['link'];
			$this->_DB->update(VODCMS_CATEGORY, $data, array('id'=> $row['id']));
		}
	}
}