<?php
// 栏目管理模型
class CategoryModel extends Model {
	private $categoryArray = array();
	private $categoryArrayAll = array();
	/**
	 * 删除分类及子分类
	 *
	 * @param int $catid
	 * @access public
	 */
	public function del() {
		$selids = explode(',', R('selids'));
		$del = array();
		foreach($selids as $catid) {
			$category = $this -> childAll($catid, true);
			foreach($category as $tmp) {
				FileUtil :: del(JXCMS_ROOT . $tmp['dir']);
				$del[] = $tmp['catid'];
			}
		}
		if (!empty($del)) {
			$where = count($del) > 1?'catid IN (' . implode(', ', $del) . ')':'catid=' . current($del);
			$this -> where($where) -> delete();
			return $this -> getAffectedRows();
		}
		return false;
	}
	/**
	 * 得到子级数组
	 *
	 * @param int $catid
	 * @param int $type 9全部,0内部,1单网页,2外部链接
	 * @param mix $module 0全部模型,>0对应的模型
	 * @return array
	 */
	public function child($catid, $type = 9, $module = 0) {
		$catid = intval($catid);
		$module = is_numeric($module)?intval($module):get_module($module, 'id');
		$categoryArray = get_category();
		$rs = array();
		if (is_array($categoryArray)) {
			foreach($categoryArray as $tmp) {
				if ($module && $module != $tmp['moduleid'])continue;
				if ($tmp['pid'] == $catid) {
					if ($type == 9) $rs[] = $tmp;
					elseif ($type == $tmp['type']) $rs[] = $tmp;
				}
			}
		}
		return $rs;
	}
	/**
	 * 获取全部子分类数组
	 *
	 * @param int $catid
	 * @param int $containParent 包含父级分类
	 * @param int $onlyId 仅返回ID
	 * @param mix $module flase:不分模块,true:catid对应的模块,数字:模块ID,字符串:模块名称
	 * @param string $catrule 分类规则 例如 name:news
	 * @access public
	 */
	public function childAll($catid, $containParent = false, $onlyId = false, $module = false, $catrule = '') {
		$catid = intval($catid);
		if (!is_numeric($module) && is_string($module)) $module = get_module($module, 'id');
		if ($catrule) {
			$catrule = explode(':', $catrule, 2);
		}
		if (empty($catrule[1])) $useRule = 0;
		else {
			$useRule = 1;
			$isDir = $catrule[0] == 'dir'?1:0;
		}
		$start = false;
		$startLevel = 0;
		$rs = array();
		$categoryArray = get_category();
		foreach($categoryArray as $k => $v) {
			if (!$start) {
				if ($v['catid'] == $catid or $catid == 0) {
					$start = true;
					if ($catid) {
						if ($module === true) $module = $v['moduleid'];
						$startLevel = $v['level'];
					} else {
						$startLevel = -1;
						if ($module === true) $module = false;
					}
					$rs[] = $onlyId?$v['catid']:$v;
				}
			} else {
				if ($v['level'] > $startLevel) {
					if ($module && $module != $v['moduleid']) continue;
					if ($useRule) {
						$tmpVal = $isDir?end(explode('/', $v['dir'])):$v[$catrule[0]];
						if ($tmpVal != $catrule[1]) {
							continue;
						}
					}
					$rs[] = $onlyId?$v['catid']:$v;
				} else break;
			}
		}
		if ($catid && !$containParent && count($rs) > 1) unset($rs[0]);
		return $rs;
	}
	/**
	 * 生成顺序正确的分类数组，并添加每个分类的层级和是否是父分类
	 *
	 * @param boolean $isCache 是否生成缓存
	 * @param int $catid
	 * @param string $addDir 附加目录
	 * @param int $level 分类深度
	 * @access private
	 */
	private function _categoryFormat($isCache = true, $catid = 0, $addDir = '', $level = 0) {
		if (isset($this -> categoryArray[$catid])) {
			$total = count($this -> categoryArray[$catid]);
			foreach($this -> categoryArray[$catid] as $k => $v) {
				$v['level'] = $level;
				if ($addDir)$v['dir'] = $addDir . '/' . $v['dir'];
				$v['subnum'] = isset($this -> categoryArray[$k])?count($this -> categoryArray[$k]):0;
				if ($v['type'] == 2)$v['dir'] = '';
				elseif ($isCache) Cache :: write('category', $v, $v['catid']);
				$this -> categoryArrayAll[$v['catid']] = array('catid' => $v['catid'], 'pid' => $v['pid'], 'name' => $v['name'], 'style' => $v['style'], 'showtype' => $v['showtype'], 'showmode' => $v['showmode'], 'dir' => $v['dir'], 'type' => $v['type'], 'moduleid' => $v['moduleid'], 'orderid' => $v['orderid'], 'listnum' => $v['listnum'], 'linkurl' => $v['linkurl'], 'subnum' => $v['subnum'], 'level' => $level);
				$v['subnum'] && $this -> _categoryFormat($isCache, $k, $v['istransfer']?$v['dir']:$addDir, $level + 1);
			}
		}
		return $this -> categoryArrayAll;
	}
	/**
	 * 获取顺序正确的分类数组
	 *
	 * @param  $isCache 是否生成缓存
	 * @access private
	 */
	private function categoryFormat($isCache = true) {
		$data = $this -> order(array('orderid', 'catid')) -> select();
		if (is_array($data)) {
			$this -> categoryArray = array();
			// 将父类catid相同的分类合并,产生二维数组$categoryArray
			foreach($data as $v) {
				$this -> categoryArray[$v['pid']][$v['catid']] = $v;
			}
		}
		return $this -> _categoryFormat($isCache);
	}
	/**
	 * 根据模块获取分类数组
	 *
	 * @param  $module mixed 模块ID或名称
	 * @access public
	 */
	public function categoryModule($module) {
		$module = is_numeric($module)?intval($module):get_module($module, 'id');
		if ($module < 1) return false;
		$category = get_category();
		$pid = 0;
		$rs = array();
		while ($category) {
			$tmp = array_pop($category);
			if ($tmp['moduleid'] == $module || ($pid && $pid == $tmp['catid'])) {
				$pid = $tmp['pid'];
				$rs[$tmp['catid']] = $tmp;
			}
		}
		$this -> categoryArray = array_reverse($rs, true);
		return $this -> categoryArray;
	}
	// 获取栏目属性
	public function config($catid, $index) {
		$category = get_category();
		$pid = $catid;
		while ($tmp = array_pop($category)) {
			if ($tmp['catid'] == $pid) {
				if ($tmp[$index])return $tmp[$index];
				$pid = $tmp['pid'];
			}
		}
		$category = get_category($catid);
		if ($category['type']) {
			$config = C($index);
		} else {
			$module = get_module($category['moduleid'], 'name');
			$config = C($index, 0, $module['name']);
		}
		return $config;
	}
	/**
	 * 得到当前位置
	 *
	 * @param int $catid
	 * @return array
	 */
	public function position($catid) {
		$catid = intval($catid);
		$array = array();
		if (!$catid) return $array;
		$categoryArray = get_category();
		$cnt = count($categoryArray);
		if ($cnt == 0) return false;
		$parentid = 0;
		while ($categoryArray) {
			$tmpArr = array_pop($categoryArray);
			if ($tmpArr['catid'] == $catid) {
				$tmpArr['url'] = Url :: getListUrl($catid);
				$array[] = array('catid' => $tmpArr['catid'], 'name' => $tmpArr['name'], 'moduleid' => $tmpArr['moduleid'], 'url' => $tmpArr['url']);
				if ($tmpArr['pid']) {
					$parentid = $tmpArr['pid'];
					continue;
				} else {
					return $array;
				}
			}
			if ($parentid && $tmpArr['catid'] == $parentid) {
				$tmpArr['url'] = Url :: getListUrl($parentid);
				$array[] = array('catid' => $tmpArr['catid'], 'name' => $tmpArr['name'], 'moduleid' => $tmpArr['moduleid'], 'url' => $tmpArr['url']);
				if ($tmpArr['pid']) $parentid = $tmpArr['pid'];
				else break;
			}
		}
		return array_reverse($array);
	}
	/**
	 * 得到非跳转(显示)的子分类
	 *
	 * @param int $catid
	 * @return mix
	 */
	public function categoryChildShow($catid, $index = '') {
		$categoryArray = get_category();
		$level = -1;
		$array = array();
		foreach($categoryArray as $tmp) {
			if ($tmp['catid'] == $catid) {
				$level = $tmp['level'];
				$array = $tmp;
				continue;
			}
			if ($level >= 0) {
				if ($tmp['showmode'] != 3 || !$tmp['subnum']) {
					$array = $tmp;
					break;
				}
				if ($tmp['level'] <= $level) break;
			}
		}
		if ($level == -1) return false;
		return $index?$array[$index]:$array;
	}
	public function cache() {
		Cache :: write('category', $this -> categoryFormat(true));
	}
}