<?php
!defined('M_P') && exit('Forbidden');
/**
 * 行业分类服务层
 * @author L.IuHu.I@2010/8/26
 *
 */
class PW_CategoriesService {
	
	/**
	 * 保存行业的DAO服务对象
	 * @access private
	 * @var PW_Dianpu_categoriesDB
	 */
	var $_categoriesDao;
	
	/**
	 * 构造函数（PHP4兼容）
	 */
	function PW_CategoriesService() {
		$this->__construct();
	}
	
	/**
	 * 构造函数（PHP5兼容）
	 */
	function __construct() {
		global $timestamp;
		$this->_categoriesDao = $this->_getCategoriesDao();
		$this->_timestamp = $timestamp;
	}
	
	/**
	 * 添加行业分类
	 * @param array $fieldData array('字段' => '值')
	 * @return mixed boolean (false:失败) | integer 返回插入的ID
	 */
	function addCategory($fieldData) {
		if (!S::isArray($fieldData)) return false;
		if (!$this->_cleanParam($fieldData)) return false;
		return $this->_categoriesDao->insert($fieldData);
	}
	
	/**
	 * 批量添加行业分类
	 * @param array $fieldDatas array(array('字段' => '值'),...)
	 * @return mixed boolean (false:失败) | integer 最后一个插入的ID
	 */
	function addCategories($fieldDatas) {
		if (!S::isArray($fieldDatas)) return false;
		if (!$this->_filterParams($fieldDatas)) return false;
		$fields = array();
		foreach ($fieldDatas as $v) {
			$tmp = array();
			$tmp['parentid'] = ($v['parentid'] > 0) ? intval($v['parentid']) : 0;
			$tmp['name'] = $v['name'];
			$tmp['sort'] = $v['sort'];
			$tmp['createdtime'] = $this->_timestamp;
			$fields[] = $tmp;
		}
		$result = $this->_categoriesDao->addCategories($fields);
		if ($result) $this->refreshCategoryCache();
		return $result;
	}
	
	/**
	 * 更新分类信息
	 * @param array $fieldData array('字段' => '值')
	 * @param integer $id 需要更新的ID
	 * @return mixed boolean (false: 失败) | integer 返回受影响的行数
	 */
	function updateCategory($fieldData, $id) {
		$id = intval($id);
		if (!S::isArray($fieldData) || $id < 1) return false;
		if (!$this->_cleanParam($fieldData)) return false;
		$result = $this->_categoriesDao->update($fieldData, $id);
		if ($result) $this->refreshCategoryCache();
		return $result;
	}
	
	/**
	 * 移动分类信息
	 * @param array $fieldData array('字段' => '值')
	 * @param integer $id 需要转移的ID
	 * @return mixed boolean (false: 失败) | integer 返回受影响的行数
	 */
	function moveCategory($fieldData, $id) {
		$id = intval($id);
		if (!S::isArray($fieldData) || $id < 1) return false;
		if (!$fieldData['parentid']) return false;
		$result = $this->_categoriesDao->update($fieldData, $id);
		if ($result) $this->refreshCategoryCache();
		return $result;
	}
	
	/**
	 * 根据行业的ID更新分类信息
	 * @param array $fieldData  array('字段' => '值')
	 * @param integer $parentId 行业的ID
	 * @return mixed boolean (false:失败信息) | integer 返回受影响的行数
	 */
	function updateByParentId($fieldData, $parentId) {
		$parentId = intval($parentId);
		if (!S::isArray($fieldData) || $parentId < 1) return false;
		if (!$this->_cleanParam($fieldData)) return false;
		$result =  $this->_categoriesDao->updateByParentId($fieldData, $parentId);
		if ($result) $this->refreshCategoryCache();
		return $result;
	}
	
	/**
	 * 获得全部分类信息 是否文件缓存 
	 * @return array array(array('字段' => '值'),...)
	 */
	function getCategories() {
		$dianpu_category_cache = L::config($dianpu_category_cache, 'dianpu_category_cache');
		if (!$dianpu_category_cache) $soruceCategories = $this->refreshCategoryCache();
		return ($dianpu_category_cache) ? $dianpu_category_cache['dianpu_category_cache'] : $soruceCategories;
	}
	
	/**
	 * 刷新分类文件缓存
	 * @return array array(array('字段' => '值'),...)
	 */
	function refreshCategoryCache() {
		$categories = $this->getCategoriesNoCache();
		if (S::isArray($categories)) {
			writeover(D_P . 'data/bbscache/dianpu_category_cache.php', "<?php\r\n\$dianpu_category_cache=" . pw_var_export($categories) . ";\r\n?>");
		}
		return $categories;
	}
	
	/**
	 * 根据分类ID来获得分类信息
	 * @param integer $categoryId 分类的ID
	 * @return array array('字段' => '值')
	 */
	function getCategory($categoryId) {
		$categories = $this->getCategories();
		if (!$categories) return $this->_categoriesDao->get($categoryId);
		foreach($categories as $category) {
			if ($category['categoryid'] == $categoryId) return $category;
		}
	}
	
	/**
	 * 根据分类ID删除分类信息
	 * @param integer $categoryId  分类的ID
	 * @return mixed boolean (false:失败) | integer 返回受影响的行数
	 */
	function deleteCategory($categoryId) {
		$categoryId = intval($categoryId);
		if ($categoryId < 1) return false;
		$result = $this->_categoriesDao->delete($categoryId);
		if ($result) $this->refreshCategoryCache();
		return $result;
	}
	
	/**
	 * 根据行业ID来获得该行业下的分类列表
	 * @param integer $parentId 行业ID
	 * @return mixed boolean (false：失败) | array  返回分类列表  array(array('字段' => '值'),...)
	 */
	function getCategoriesByParentId($parentId) {
		$parentId = intval($parentId);
		if ($parentId < 1) return false;
		$categories = $this->getCategories();
		if (!$categories) return $this->_categoriesDao->getsByParentid($parentId);
		$_categories = array();
		foreach($categories as $category) {
			if ($category['parentid'] == $parentId) $_categories[] = $category;
		}
		return $_categories;
	}
	
	/**
	 * 从数据表中读取行业分类列表
	 * @return array  array(array('字段' => '值'),...)返回分类列表  
	 */
	function getCategoriesNoCache() {
		return $this->_categoriesDao->gets();
	}
	
	/**
	 * 根椐分类IDs获取分类与行业名称
	 * @param array $categoryIds 分类数组ID
	 * @return mixed boolean (false:失败) | array array('categoryid' => array('parentName','childName'),...)返回行业分类信息列表
	 */
	function linkCategories($categoryIds) {
		if (!S::isArray($categoryIds)) $categoryIds = array($categoryIds);
		$categories = $this->getCategories();
		if (!$categories) return false;
		$children = $parent = array();
		foreach ($categories as $key => $category) {
			if ($category['parentid'] > 0) {
				$children[] = $category;
			} else {
				$parent[$category['categoryid']] = $category;
			}
		}
		$tmp = array();
		foreach ($children as $c) {
			if ($parent[$c['parentid']] && in_array($c['categoryid'], $categoryIds)) {
				$tmp[$c['categoryid']] = array('parent' => $parent[$c['parentid']]['name'],'child' => $c['name']);
			}
		}
		return $tmp;
	}
	/**
	 * 获取行业与分类
	 * @return mixed boolean (false:失败) 或者<br/> array('0' => array('categoryid' => array('字段'=>'值'),...),//行业类列表 <br/>
	 * 										      '1' => array('parentid' => array(array('字段'=>'值'),...),...),//行业下的子类列表<br/>
	 * 										      '2' => array('categoryid' => array('字段'=>'值'),...)//包括行业和行业下分类列表<br/>
	 * 										 )
	 */
	function getParentAndChild(){
		$categories = $this->getCategories();
		if (!$categories) return false;
		$children = $parent = $all =  array();
		foreach ($categories as $key => $category) {
			if ($category['parentid'] > 0) {
				$children[$category['parentid']][] = $category;
			} else {
				$parent[$category['categoryid']] = $category;
			}
			$all[$category['categoryid']] = $category;
		}
		return array($parent,$children,$all);
	}
	
	/**
	 * 过滤输入的参数
	 * @access private
	 * @param array $params array(array('字段' => '值'),...) 需要过滤的参数列表
	 * @return array array(array('字段' => '值'),...) 过滤后的参数列表
	 */
	function _filterParams($params) {
		$temp = array();
		foreach( $params as $key => $one) {
			$_tmp = $this->_cleanParam($one);
			if (!$_tmp) return $temp;
			$temp[$key] = $_tmp;
		}
		return $temp;
	}
	
	/**
	 * 过滤输入的单个参数
	 * @access private
	 * @param array $param  array('字段' => '值') 需要过滤的参数列表 
	 * @return array array('字段' => '值') 过滤后的参数列表
	 */
	function _cleanParam($param) {
		if (!$param['name']) {
			Error::addError('请输入分类名称！');
			return false;
		}
		if (strlen($param['name']) > 20) {
			Error::addError('分类"<font color="red">' . $param['name'] . '</font>"输入错误，长度不能超过20个字节！');
			return false;
		}
		return $param;
	}
	
	/**
	 * 获取行业DAO服务
	 * @access private
	 * @return PW_Dianpu_categoriesDB 
	 */
	function _getCategoriesDao() {
		return DP::loadDB("dianpu_categories");
	}
}