<?php
!defined('M_P') && exit('Forbidden');
/**
 * 商家导航店铺组DB实现
 * @author yishuo
 */
class PW_Dianpu_GroupsDB extends BaseDB {
	var $_tableName = "pw_dianpu_groups";
	var $_primaryKey = 'groupid';
	
	/**
	 * 根据店铺组ID批量删除店铺组
	 * @param Array $gids
	 * @return boolean
	 */
	function deleteGroupsByIds($gids) {
		if (!is_array($gids) || empty($gids)) return false;
		$_sql = "DELETE FROM " . $this->_tableName . " WHERE " . $this->_primaryKey . " IN (" . pwImplode($gids) . ") ";
		$this->_db->update($_sql);
		return $this->_db->affected_rows();
	}
	
	/**
	 * 根据店铺组ID删除店铺组
	 * @param int $gid
	 * @return boolean
	 */
	function deleteGroupById($gid) {
		return $this->_delete($gid);
	}
	
	/**
	 * 根据店铺组ID获得店铺组信息
	 * @param int $gid
	 * @return boolean
	 */
	function getGroupById($gid) {
		$_tmp = $this->_get($gid);
		$_tmp = $this->_unserializeData($_tmp);
		return $_tmp;
	}
	
	/**
	 * 获得所有店铺组
	 * @param int $start
	 * @param int $perpage
	 * @return array
	 */
	function getGroupsByPages($start = '0', $perpage = '0') {
		if (!is_numeric($start)) $start = '0';
		if (!is_numeric($perpage)) $perpage = '0';
		$_order = " ORDER BY groupid ASC ";
		$_limit = $perpage == '0' ? '' : " LIMIT " . $start . "," . $perpage;
		$_sql = "SELECT * FROM " . $this->_tableName . " WHERE  state != '0' " . $_order . $_limit;
		$_query = $this->_db->query($_sql);
		$_tmp = array();
		while ($rt = $this->_db->fetch_array($_query)) {
			$rt = $this->_unserializeData($rt);
			$_tmp[$rt['groupid']] = $rt;
		}
		return $_tmp;
	}
	
	/**
	 * 获得店铺组总条数
	 * @return int
	 */
	function getGroupCount() {
		return $this->_count();
	}
	
	/**
	 * 添加店铺组
	 * @param Array $data {'filed' => 'value'}
	 * @return boolean
	 */
	function insertGroup($data) {
		$data = $this->_serializeData($data);
		$data = $this->_checkAllowField($data, $this->getStruct());
		return $this->_insert($data);
	}
	
	/**
	 * 更新用户组
	 * @param array $data
	 * @param int $id
	 * @return boolean
	 */
	function updateGroup($data, $id) {
		$data = $this->_serializeData($data);
		$data = $this->_checkAllowField($data, $this->getStruct());
		return $this->_update($data, $id);
	}
	
	/**
	 * 序列化数据值
	 * @param array $data
	 * @return array
	 */
	function _serializeData($data) {
		if (is_array($data) && $data['configinfo']) $data['configinfo'] = $this->_serialize($data['configinfo']);
		if (is_array($data) && $data['styles']) $data['styles'] = $this->_serialize($data['styles']);
		return $data;
	}
	
	/**
	 * 反序列化数据值
	 * @param array $data
	 * @return array
	 */
	function _unserializeData($data) {
		if (is_array($data) && $data['configinfo']) $data['configinfo'] = $this->_unserialize($data['configinfo']);
		if (is_array($data) && $data['styles']) $data['styles'] = $this->_unserialize($data['styles']);
		return $data;
	}
	
	/**
	 * 获得店铺组数据结构信息
	 * @return array()
	 */
	function getStruct() {
		return array('groupid', 'title', 'state', 'styles' ,'createtime', 'configinfo');
	}
}
?>