<?php
!defined('M_P') && exit('Forbidden');

/**
 * 店铺附件的服务层实现
 * @author 
 */
class PW_DianpuattachService {
	/**
	 * 更新店铺附件信息
	 * @param integer $did 店铺的ID
	 * @param array $attachs 上传的附件信息
	 * @return array array('是否有附件','插入图片的id集合')
	 */
	function updateAttachs($did, $attachs) {
		$_attachDB = $this->_getAttachDB();
		$ifAttach = 0;
		$uploadIds = array();
		foreach ($attachs as $value) {
			if ($value['attname'] != 'delete') $ifAttach = 1;
			if ($value['attname'] == 'replace') {
				$saveData = $this->_cookUploadData($value, $did);
				$_attachDB->update($saveData, $value['id']);
			} elseif ($value['attname'] == 'attachment') {
				$saveData = $this->_cookUploadData($value, $did);
				$temp = $_attachDB->insert($saveData);
				$uploadIds[$value['id']] = $temp;
			} elseif ($value['attname'] == 'update') {
				$_attachDB->update(array('descrip' => $value['descrip']), $value['attachid']);
			} elseif ($value['attname'] == 'delete') {
				$_attachDB->delete($value['attachid']);
			}
		}
		return array($ifAttach, $uploadIds);
	}
	
	/**
	 * 获取店铺的附件信息
	 * @param integer $did 店铺ID
	 * @return array array('字段' => '值')
	 */
	function getAttachsByDianpuId($did) {
		$_attachDB = $this->_getAttachDB();
		$attachs = $_attachDB->getAttachsByDianpuId($did);
		$result = array();
		foreach ($attachs as $key => $value) {
			$value['attachurl'] = $this->_getImageUrl($value['attachurl']);
			$result[$value['attachid']] = $value;
		}
		return $result;
	}
	
	/**
	 * 根据ID获取单个附件信息
	 * @param integer $id 需要获取信息的附件ID
	 * @return array array('字段' => '值')
	 */
	function getAttachById($id) {
		$_attachDB = $this->_getAttachDB();
		$temp = $_attachDB->get($id);
		if (!$temp) return array();
		$temp['attachurl'] = $this->_getImageUrl($temp['attachurl']);
		return $temp;
	}
	
	/**
	 * 组装上传的数据
	 * @access private
	 * @param array $data 传入的数据
	 * @param integer $did  店铺ID
	 * @return array array('字段' => '值')
	 */
	function _cookUploadData($data, $did) {
		global $timestamp;
		return array('name' => $data['name'], 'descrip' => $data['descrip'], 'dianpuid' => $did, 
					'type' => $data['type'], 'size' => $data['size'], 'uploadtime' => $timestamp, 
					'attachurl' => $data['fileuploadurl'], 'ifthumb' => $data['ifthumb']);
	}
	
	/**
	 * 组装获得图片的url
	 * @access private
	 * @param string $path 图片的地址
	 * @return string 图片的存储地址
	 */
	function _getImageUrl($path) {
		$temp = geturl($path);
		return $temp[0];
	}
	
	/**
	 * 获得店铺附件的DAO
	 * @access private
	 * @return PW_Dianpu_AttachDB 
	 */
	function _getAttachDB() {
		return DP::loadDB('dianpu_attach');
	}
}
?>