<?php
!defined('P_W') && exit('Forbidden');
require_once MODE . '/base/basehelper.php';

/**
 * 店铺商品相关Helper层实现
 * @author L.iuHu.I
 */
class PW_ProductHelper extends BaseHelper {
	
	/**
	 * 添加店铺商品
	 * @param array $fieldData
	 * @return boolean
	 */
	function insertProduct($fieldData) {
		$productService = $this->getProductService();
		return $productService->addProduct($fieldData);
	}
	
	/**
	 * 根据商品ID更新商品
	 * @param array $fieldData
	 * @param int $productId
	 * @return boolean
	 */
	function updateProduct($fieldData, $productId, $objectId) {
		$productService = $this->getProductService();
		return $productService->updateProduct($fieldData, $productId, $objectId);
	}
	
	/**
	 * 增加商品
	 * @param array $params
	 * @return boolean
	 */
	function addProducts($params) {
		if (!$this->_checkProducts($params['objectid'])) return false; //array(false, $message);
		$module = $this->_setProductModule($params);
		if ($module->get_error()) return false;
		$module->setAttach();
		$module->setCreatedTime($this->_getGlobal('timestamp'));
		$filedData = $this->_setProductParams($module);
		if (!($productId = $this->insertProduct($filedData))) return $this->_addError('商品添加失败');
		$photoId = $this->addPhotos($module->attach, $productId, $params['objectid']);
		$photoId && $this->updateProduct(array('photoid' => $photoId), $productId, $params['objectid']);
		return true;
	}
	
	/**
	 * 检查店铺组的商品个数限制
	 * @param int $dianpuId
	 * @return boolean
	 */
	function _checkProducts($dianpuId) {
		$dianpuService = $this->getDianpuService();
		if (!($dianpu = $dianpuService->getDianpu($dianpuId))) return $this->_addError('店铺不存在');
		$groupHelper = DP::loadClass('groupshelper', 'helper');
		$group = $groupHelper->getGroupInfo($dianpu->groupid);
		if (!$group) return $this->_addError('店铺没有分组');
		if (!isset($group['configinfo']['maxproduct'])) return true;
		$productService = $this->getProductService();
		$total = $productService->countProductsByObjectId($dianpuId);
		if ($group['configinfo']['maxproduct'] && ($total + 1) > $group['configinfo']['maxproduct']) return $this->_addError('店铺商品数最多为' . $group['configinfo']['maxproduct']);
		return true;
	}
	
	/**
	 * 编辑商品
	 * @param array $params
	 * @param int $productId
	 * @param int $objectId
	 * @return boolean
	 */
	function editProducts($params, $productId, $objectId) {
		$productId = intval($productId);
		$objectId = intval($objectId);
		$cover = ($params['cover'] > 0) ? intval($params['cover']) : 0;
		$module = $this->_setProductModule($params);
		if (!$productId || $module->get_error() || !$objectId) return false; //return array(true, '数据有误');
		$module->setAttach();
		$filedData = $this->_setProductParams($module);
		if (!$this->updateProduct($filedData, $productId, $objectId)) return $this->_addError('商品编辑失败');
		$photoId = $this->addPhotos($module->attach, $productId, $objectId);
		if (!$cover) $cover = $photoId;
		($cover > 0) && $this->updateProduct(array('photoid' => $cover), $productId, $objectId);
		return true;
	}
	
	/**
	 * 增加商品图片
	 * @param array $attach
	 * @param int $objectId
	 * @return boolean
	 */
	function addPhotos($attach, $objectId, $belongId) {
		$objectId = intval($objectId);
		$belongId = intval($belongId);
		if (!$attach || !S::isArray($attach) || $objectId < 1 || $belongId < 1) return $this->_addError('添加商品图片失败');
		$fieldDatas = array();
		foreach ($attach as $a) {
			$tmp['belongid'] = $belongId;
			$tmp['objectid'] = $objectId;
			$tmp['typeid'] = 1;
			$tmp['filename'] = trim($a['name']);
			$tmp['path'] = trim($a['fileuploadurl']);
			$tmp['createdtime'] = $this->_getGlobal('timestamp');
			$fieldDatas[] = $tmp;
		}
		$service = $this->getPhotossService();
		return $service->addPhotos($fieldDatas);
	}
	
	/**
	 * 删除商品图片
	 * @param int $photoId
	 * @return boolean
	 */
	function deletephoto($photoId, $belongId) {
		$photoId = intval($photoId);
		$belongId = intval($belongId);
		if (!$photoId || !$belongId) {return array(false, '请选择图片');}
		$service = $this->getPhotossService();
		$photo = $service->getPhoto($photoId);
		if (!$photo) {return array(false, '图片不存在');}
		$photoPath = $this->_getGlobal('db_attachname') . '/' . $photo['path'];
		if (is_file($photoPath)) {
			@unlink($photoPath);
		}
		if (!$service->deleteByPhotoIdAndBelongId($photoId, $belongId)) {return array(false, '删除图片失败');}
		return array(true, '删除图片成功');
	}
	/**
	 * 过滤参数并且返回商品数据模型
	 * @param array $params
	 * @return PW_ProductModule
	 */
	function _setProductModule($params) {
		DP::loadClass('productmodule', 'module', false);
		$module = new PW_ProductModule();
		isset($params['productid']) && $module->setProductId($params['productid']);
		isset($params['objectid']) && $module->setObjectId($params['objectid']);
		isset($params['title']) && $module->setTitle($params['title']);
		isset($params['description']) && $module->setDescription($params['description']);
		isset($params['market_price']) && $module->setMarketPrice($params['market_price']);
		isset($params['member_price']) && $module->setMemberPrice($params['member_price']);
		isset($params['photoid']) && $module->setPhotoId($params['photoid']);
		isset($params['shelf']) && $module->setShelf($params['shelf']);
		isset($params['recommend']) && $module->setRecommend($params['recommend']);
		$module->setModifiedTime($this->_getGlobal('timestamp'));
		return $module;
	}
	
	/**
	 * 获得商品结构数组
	 * @param PW_ProductModule $module
	 * @return array
	 */
	function _setProductParams($module) {
		$params = array();
		(!is_null($module->productid)) && $params['productid'] = $module->productid;
		(!is_null($module->objectid)) && $params['objectid'] = $module->objectid;
		(!is_null($module->title)) && $params['title'] = $module->title;
		(!is_null($module->description)) && $params['description'] = $module->description;
		(!is_null($module->market_price)) && $params['market_price'] = $module->market_price;
		(!is_null($module->member_price)) && $params['member_price'] = $module->member_price;
		(!is_null($module->photoid)) && $params['photoid'] = $module->photoid;
		(!is_null($module->shelf)) && $params['shelf'] = $module->shelf;
		(!is_null($module->recommend)) && $params['recommend'] = $module->recommend;
		(!is_null($module->modifiedtime)) && $params['modifiedtime'] = $module->modifiedtime;
		(!is_null($module->createdtime)) && $params['createdtime'] = $module->createdtime;
		return $params;
	}
	
	/**
	 * 分页获取商品列表
	 * @param int $page
	 * @param int $perpage
	 * @return array
	 */
	function getProducts($page, $perpage = 20) {
		$page = intval($page);
		$page = ($page > 0) ? $page : 1;
		$productService = $this->getProductService();
		$products = $productService->getProducts($page, $perpage);
		if (!$products) {return array();}
		return $this->_buildProducts($products);
	}
	
	/**
	 * 统计所有商品数量
	 * @return int
	 */
	function countProducts() {
		$productService = $this->getProductService();
		return $productService->countProducts();
	}
	
	/**
	 * 根椐关键字与上下架搜索商品
	 * @param int $dianpuid
	 * @param string $keyword
	 * @param int $shelf (-1/1/0)
	 * @param int $page
	 * @param int $perpage
	 * @return array
	 */
	function searchProductsByShelf($dianpuid, $keyword, $shelf, $page, $perpage = 20) {
		$shelf = $this->_checkShelf($shelf);
		$productService = $this->getProductService();
		if ($keyword == '') {
			$total = $productService->countByObjectIdAndShelfs($dianpuid, $shelf);
			$page = $this->_validePage($total, $page, $perpage);
			$total && $products = $productService->searchByShelf($dianpuid, $shelf, $page, $perpage);
		} else {
			$total = $productService->countByShelfAndTitle($dianpuid, $keyword, $shelf);
			$page = $this->_validePage($total, $page, $perpage);
			$total && $products = $productService->searchByShelfAndTitle($dianpuid, $keyword, $shelf, $page, $perpage);
		}
		return ($total) ? array($total, $this->_buildProducts($products)) : array(0, array());
	}
	
	/**
	 * 验证上下架的合法性
	 * @param int $shelf
	 * @return array 
	 */
	function _checkShelf($shelf) {
		$shelf = in_array($shelf, array('-1', '1', '0')) ? $shelf : 1;
		if ($shelf == '-1') {
			$shelf = array(0, 1);
		} else {
			$shelf = array($shelf);
		}
		return $shelf;
	}
	
	/**
	 * 获取商品信息
	 * @param int $productId
	 * @return boolean
	 */
	function getProduct($productId) {
		$productId = intval($productId);
		if (!$productId) {return false;}
		$productService = $this->getProductService();
		$product = $productService->getProduct($productId);
		if (!$product) {return false;}
		return $this->_buildProduct($product);
	}
	
	/**
	 * 根据商品判断该商品是否上架并返回该商品信息
	 * @param int $productId
	 * @return array(result,message) 
	 */
	function getProductWithShelf($productId) {
		$productId = intval($productId);
		if (!$productId) {return array(false, '请选择商品', '');}
		$productService = $this->getProductService();
		$product = $productService->getProduct($productId);
		if (!$product) {return array(false, '商品不存在', '');}
		if (!$product['shelf']) {return array(false, '商品已经下架', '');}
		return array(true, '', $this->_buildProduct($product));
	}
	
	/**
	 * 构建商品结果集
	 * @param array $product
	 * @return array
	 */
	function _buildProduct($product) {
		if (!S::isArray($product)) return array();
		$service = $this->getPhotossService();
		$photos = $service->getPhotosByObjectId($product['productid']);
		$photonum = ($photos) ? count($photos) : 0;
		$product['photoadd'] = intval(5 - $photonum);
		$product['photonum'] = $photonum;
		$tmp = array();
		foreach ($photos as $photo) {
			$photo['path'] = $this->_getGlobal('db_attachname') . '/' . $photo['path'];
			$tmp[] = $photo;
		}
		$product['photos'] = $tmp;
		return $product;
	}
	
	/**
	 * 搜索商品
	 * 1,关键字为空.2,接店铺搜索.3,按商品名称搜索
	 * @param string $keyword
	 * @param string $type
	 * @param int $page
	 * @param int $perpage
	 * @return array
	 */
	function searchProducts($keyword, $type, $page, $perpage) {
		if ($keyword == "") {
			list($total, $products) = $this->_searchProductsByNormal($page, $perpage);
		} elseif ($type == 1) {
			list($total, $products) = $this->_searchProductsByDianpu($keyword, $page, $perpage);
		} elseif ($type == 2) {
			list($total, $products) = $this->_searchProductsByTitle($keyword, $page, $perpage);
		}
		return ($total) ? array($total, $this->_buildProducts($products)) : array(0, array());
	}
	
	/**
	 * 商品搜索
	 * @access private
	 * @param int $page
	 * @param int $perpage
	 * @return array 
	 */
	function _searchProductsByNormal($page, $perpage) {
		$products = array();
		$productService = $this->getProductService();
		$total = $productService->countProducts();
		$page = $this->_validePage($total, $page, $perpage);
		$total && $products = $this->getProducts($page, $perpage);
		return array($total, $products);
	}
	
	/**
	 * 根据店铺名称检索商品
	 * @param string $keyword
	 * @param int $page
	 * @param int $perpage
	 * @return array 
	 */
	function _searchProductsByDianpu($keyword, $page, $perpage) {
		$products = array();
		$dianpuService = $this->getDianpuService();
		$productService = $this->getProductService();
		$result = $dianpuService->searchForAdmin($keyword);
		if (!$result) return array(0, $products);
		$objectIds = array();
		foreach ($result as $dianpu) {
			$objectIds[] = $dianpu['dianpuid'];
		}
		$total = $productService->countByObjectIds($objectIds);
		$page = $this->_validePage($total, $page, $perpage);
		$total && $products = $productService->getsByObjectIds($objectIds, $page, $perpage);
		return array($total, $products);
	}
	
	/**
	 * 根据商品标题检索商品
	 * @param string $keyword
	 * @param int $page
	 * @param int $perpage
	 * @return array 
	 */
	function _searchProductsByTitle($keyword, $page, $perpage) {
		$products = array();
		$productService = $this->getProductService();
		$total = $productService->countProductsByTitle($keyword);
		$page = $this->_validePage($total, $page, $perpage);
		$total && $products = $productService->searchProductsByTitle($keyword, $page, $perpage);
		return array($total, $products);
	}
	
	/**
	 * 组装商品输出
	 * @param array $products
	 * @return array
	 */
	function _buildProducts($products) {
		if (!S::isArray($products)) {return array();}
		$objectIds = array();
		foreach ($products as $product) {
			$objectIds[] = $product['objectid'];
		}
		$dianpuService = $this->getDianpuService();
		$dianpus = $dianpuService->getDianpuListByIds($objectIds);
		$dianpuArray = array();
		foreach ($dianpus as $dianpu) {
			$dianpuArray[$dianpu['dianpuid']] = $dianpu['title'];
		}
		$tmp = array();
		foreach ($products as $product) {
			$product['format_createdtime'] = get_date($product['createdtime'], 'Y-m-d H:i');
			$product['dianpu'] = isset($dianpuArray[$product['objectid']]) ? $dianpuArray[$product['objectid']] : '末定义店铺';
			$tmp[] = $product;
		}
		return $tmp;
	}
	
	/**
	 * 商品上下架或删除商品操作
	 * @param array $productIds
	 * @param string $doing
	 * @param int $objectId
	 * @return array
	 */
	function opereateProducts($productIds, $doing, $objectId) {
		if (!($productIds = $this->_checkProductIds($productIds))) {return array(false, '请选择需要操作的商品');}
		if ($doing == 'shelf') {return $this->shelfProducts(array('shelf' => 0), $productIds, $objectId);}
		if ($doing == 'delete') {return $this->deleteProducts($productIds, $objectId);}
	}
	
	/**
	 * 检查商品ID的合法性
	 * @param array $productIds
	 * @return array
	 */
	function _checkProductIds($productIds) {
		if (!S::isArray($productIds)) {return false;}
		$ids = array();
		foreach ($productIds as $productId) {
			$productId = intval($productId);
			($productId > 0) && $ids[] = $productId;
		}
		return $ids;
	}
	
	/**
	 * 根据商品ID上架/下架商品
	 * @param int $shelf (0/1) 上/下架状态
	 * @param int $productId
	 * @param int $objectId
	 * @return array
	 */
	function shelfProduct($shelf, $productId, $objectId) {
		$objectId = intval($objectId);
		$productId = intval($productId);
		$shelf = in_array($shelf, array(0, 1)) ? $shelf : 0;
		if ($productId < 1) {return array(false, '请选择需要操作的商品');}
		return $this->shelfProducts(array('shelf' => $shelf), array($productId), $objectId);
	}
	
	/**
	 * 根据商品ID批量上架商品
	 * @param array $fieldData
	 * @param array $productIds
	 * @param int $objectId
	 * @return array 
	 */
	function shelfProducts($fieldData, $productIds, $objectId) {
		if (!S::isArray($productIds)) {return array(false, '请选择需要删除的商品');}
		$productService = $this->getProductService();
		if (!$productService->updateProducts($fieldData, $productIds, $objectId)) {return array(false, '商品操作失败');}
		return array(true, '商品操作成功');
	}
	
	/**
	 * 根据商品ID删除商品
	 * @param int $productId
	 * @param int $objectId
	 * @return array
	 */
	function deleteProduct($productId, $objectId) {
		$objectId = intval($objectId);
		$productId = intval($productId);
		if ($productId < 1 || $objectId < 1) {return array(false, '请选择需要操作的商品');}
		return $this->deleteProducts(array($productId), $objectId);
	}
	
	/**
	 * 根据商品ID删除商品
	 * @param array $productIds
	 * @param int $objectId
	 * @return array
	 */
	function deleteProducts($productIds, $objectId) {
		if (!S::isArray($productIds) || !$objectId) {return array(false, '请选择需要删除的商品');}
		$productService = $this->getProductService();
		if (!($productService->deleteProducts($productIds, $objectId))) {return array(false, '商品删除失败');}
		return array(true, '商品删除成功');
	}
	
	/**
	 * 仅为超级管理员后台提供
	 * @param array $productIds
	 * @return array
	 */
	function deletesForAdmin($productIds) {
		if (!S::isArray($productIds)) {return array(false, '请选择需要删除的商品');}
		$productService = $this->getProductService();
		if (!($productService->deletesForAdmin($productIds))) {return array(false, '商品删除失败');}
		return array(true, '商品删除成功');
	}
	
	/**
	 * 根椐店铺ID获取店铺商品
	 * @param int $dianpuId
	 * @param int $page
	 * @param int $perpage
	 * @return array(total,products)
	 */
	function getProductsByDianpuId($dianpuId, $page, $perpage) {
		$dianpuId = intval($dianpuId);
		$page = intval($page);
		$productService = $this->getProductService();
		$total = $productService->countProductsByObjectId($dianpuId);
		if ($total) {
			$page = $this->_validePage($total, $page, $perpage);
			$result = $productService->getProductsByObjectId($dianpuId, $page, $perpage);
		}
		return ($total) ? array($total, $this->_buildProducts($result), $page) : array(0, array(), 0);
	}
	
	/**
	 * 分页获得某个店铺已商家商品列表
	 * @param int $dianpuId
	 * @param int $page
	 * @param int $perpage
	 * @return array
	 */
	function getProductsByDianpuIdWithShelf($dianpuId, $page, $perpage) {
		$dianpuId = intval($dianpuId);
		$page = intval($page);
		$productService = $this->getProductService();
		$total = $productService->countByObjectIdWithShelf($dianpuId);
		if ($total) {
			$page = $this->_validePage($total, $page, $perpage);
			$result = $productService->getsByObjectIdWithShelf($dianpuId, $page, $perpage);
		}
		return ($total) ? array($total, $this->_buildProducts($result), $page) : array(0, array(), 0);
	}
	
	/**
	 * 根椐商品ID获取商品图片
	 * @param int $productId
	 * @return array
	 */
	function getPhotosByProductId($productId) {
		$photoService = $this->getPhotossService();
		$photos = $photoService->getPhotosByObjectId($productId);
		if (!$photos) return array();
		$tmp = array();
		foreach ($photos as $v) {
			$v['path'] = $GLOBALS['db_attachname'] . '/' . $v['path'];
			$tmp[] = $v;
		}
		return $tmp;
	}
	
	/**
	 * 组装默认图片数据
	 * @return array
	 */
	function getDefaultPhotos() {
		return array(array('path' => $this->_getDefaultPhoto()));
	}
	
	/**
	 * 获取默认图片
	 * @return string
	 */
	function _getDefaultPhoto() {
		return 'mode/dianpu/images/default.jpg';
	}
	
	/**
	 * 根据商品ID获取商品列表
	 * @param array $productIds
	 * @return array
	 */
	function getProductsByProductIds($productIds) {
		$productService = $this->getProductService();
		return $productService->getProductsByProductIds($productIds, true);
	}
	
	/**
	 * 获取推荐商品
	 * @param int $objectid
	 * @param int $page
	 * @param int $perpage
	 * @return array
	 */
	function getProductsByObjectIdWithRecommend($objectid, $page, $perpage) {
		$productService = $this->getProductService();
		return $productService->getProductsByObjectIdWithRecommend($objectid, $page, $perpage);
	}
	
	/**
	 * 统计推荐商品
	 * @param int $objectid
	 * @return int
	 */
	function countProductsByObjectIdWithRecommend($objectid) {
		$productService = $this->getProductService();
		return $productService->countProductsByObjectIdWithRecommend($objectid);
	}
	
	/**
	 * 分页获得店铺推荐商品
	 * @param int $page
	 * @param int $perpage
	 * @return array
	 */
	function getProductsWithRecommend($page, $perpage) {
		$productService = $this->getProductService();
		return $productService->getProductsWithRecommend($page, $perpage);
	}
	
	/**
	 * 统计店铺商品
	 * @return int
	 */
	function countProductsWithRecommend() {
		$productService = $this->getProductService();
		return $productService->countProductsWithRecommend();
	}
	
	/**
	 * 通过店铺统计获取店铺商品
	 * @param $page
	 * @param $perpage
	 * @return array
	 */
	function getProductsWithHits($page, $perpage) {
		$productService = $this->getProductService();
		return $productService->getProductsWithHits($page, $perpage);
	}
	
	/**
	 * 通过店铺统计统计店铺商品
	 * @return int
	 */
	function countProductsWithHits() {
		$productService = $this->getProductService();
		return $productService->countProductsWithHits();
	}
	
	/**
	 * 商品说明内容转移过滤
	 * @param PW_DianpuModule $dianpu
	 * @return string
	 */
	function _filterContent($contents) {
		include_once R_P . 'require/bbscode.php';
		$contents = showface($contents);
		$contents = str_replace(array("\n", "\r\n"), '<br>', trim($contents, "\r\n \n \r"));
		$contents = convert($contents, $this->_getGlobal('db_windpost'));
		return $contents;
	}

}