<?php
namespace wstmart\app\model;
use wstmart\common\model\Goods as CGoods;
use think\Db;
/**
 * ============================================================================
 * 商品类
 */
class Goods extends CGoods{
	/**
	 * 获取列表
	 */
	public function pageQuery($goodsCatIds = [], $_where=[]){
		//查询条件
		$keyword = input('keyword');
		$brandId = input('brandId/d');
		$where = $where2 = [];
		$where['goodsStatus'] = 1;
		$where['g.dataFlag'] = 1;
		$where['isSale'] = 1;
		if($keyword!='')$where['goodsName'] = ['like','%'.$keyword.'%'];
		if($brandId>0)$where['g.brandId'] = $brandId;
		//排序条件
		$orderBy = input('condition/d',0);
		$orderBy = ($orderBy>=0 && $orderBy<=4)?$orderBy:0;
		$order = (input('desc/d',0)==1)?1:0;
		$pageBy = ['saleNum','shopPrice','visitNum','saleTime'];
		$pageOrder = ['desc','asc'];
		if(!empty($goodsCatIds))$where['goodsCatIdPath'] = ['like',implode('_',$goodsCatIds).'_%'];
        $where = array_merge($where, $_where);
		$list = Db::name('goods')->alias('g')->join("__SHOPS__ s","g.shopId = s.shopId")
		->where($where)
		->field('goodsId,goodsName,saleNum,shopPrice,marketPrice,isSpec,goodsImg,appraiseNum,visitNum,s.shopId,shopName,isSelf,isFreeShipping,gallery')
		->order($pageBy[$orderBy]." ".$pageOrder[$order].",goodsId asc")
		->paginate(input('pagesize/d'))->toArray();
		return $list;
	}
	/**
	 * 获取指定商品销量
	 * @param  [type] $goodsIds [description]
	 * @return [type]           [description]
	 */
	public function getSales($goodsIds){
		if(is_array($goodsIds)){
			$where['og.goodsId']  = array('in',$goodsIds);
		}else{
			$where['og.goodsId']  = $goodsIds;
		}
		$where['o.isPay']  = 1;
		return Db::name('orders')->alias('o')->join('__ORDER_GOODS__ og','o.orderId=og.orderId')->cache(true,3600)->where($where)->sum('goodsNum');
	}
	/**
	 * 获取店铺所有宝贝数量
	 * @param  [type] $shopId [description]
	 * @return [type]         [description]
	 */
	public function getGoodsCount($shopId=0){
		$shopId=$shopId==0?(int)input('shopId'):$shopId;
		$where['shopId']  = $shopId;
		$where['isSale'] = 1;
		$where['dataFlag'] = 1;
		$where['goodsStatus'] = 1;		
		return $this->where($where)->cache(true,3600)->count('goodsId');
	}
	/**
	 * 获取店铺上新宝贝数量,一周内的
	 * @param  [type] $shopId [description]
	 * @return [type]         [description]
	 */
	public function getNewGoodsCount($shopId=0){	
		$shopId=$shopId==0?(int)input('shopId'):$shopId;
		$where['shopId']  = $shopId;
		$where['isSale'] = 1;
		$where['dataFlag'] = 1;
		$where['goodsStatus'] = 1;		
		return $this->where($where)->whereTime('saleTime','last week')->cache(true,3600)->count('goodsId');
	}
	/**
	 * 获取新品
	 * @param  [type] $goodsIds [description]
	 * @return [type]           [description]
	 */
	public function getNew($goodsIds){
		if(is_array($goodsIds)){
			$where['og.goodsId']  = array('in',$goodsIds);
		}else{
			$where['og.goodsId']  = $goodsIds;
		}
		$where['o.isPay']  = 1;
		return Db::name('orders')->alias('o')->join('__ORDER_GOODS__ og','o.orderId=og.orderId')->cache(true,3600)->where($where)->sum('goodsNum');
	}
	/**
	 * 获取商品资料在前台展示
	 */
	public function getBySale($goodsId){
		$key = input('key');
		// 浏览量
		$this->where('goodsId',$goodsId)->setInc('visitNum',1);
		$rs = Db::name('goods')->where(['goodsId'=>$goodsId,'dataFlag'=>1])->find();
		if(!empty($rs)){
			$rs['read'] = false;
			//判断是否可以公开查看
			$viKey = WSTShopEncrypt($rs['shopId']);
			if(($rs['isSale']==0 || $rs['goodsStatus']==0) && $viKey != $key)return [];
			if($key!='')$rs['read'] = true;
			//获取店铺信息
			$rs['shop'] = model('shops')->getBriefShop((int)$rs['shopId']);
			if(empty($rs['shop']))return [];
			//获取商店的授权商店分类和商铺电话信息
			// $goodsCats = Db::name('cat_shops')->alias('cs')->join('__GOODS_CATS__ gc','cs.catId=gc.catId and gc.dataFlag=1','left')->join('__SHOPS__ s','s.shopId = cs.shopId','left')
			// ->where('cs.shopId',$rs['shopId'])->field('cs.shopId,s.shopTel,gc.catId,gc.catName')->select();
			// $rs['shop']['catId'] = $goodsCats[0]['catId'];
			// $rs['shop']['shopTel'] = $goodsCats[0]['shopTel'];

			// $cat = [];
			// foreach ($goodsCats as $v){
			// 	$cat[] = $v['catName'];
			// }
			// $rs['shop']['cat'] = implode(',',$cat);
			// if(empty($rs['shop']))return [];
			$gallery = [];
			$gallery[] = $rs['goodsImg'];

			if($rs['gallery']!=''){//有多个图片就把多个一维图片地址合成一个数组
				$tmp = explode(',',$rs['gallery']);
				$gallery = array_merge($gallery,$tmp);
			}
			
			$rs['gallery'] = $gallery;
			//获取规格值
			$specs = Db::name('spec_cats')->alias('gc')->join('__SPEC_ITEMS__ sit','gc.catId=sit.catId','inner')
			->where(['sit.goodsId'=>$goodsId,'gc.isShow'=>1,'sit.dataFlag'=>1])
			->field('gc.isAllowImg,gc.catName,sit.catId,sit.itemId,sit.itemName,sit.itemImg')
			->order('gc.isAllowImg desc,gc.catSort asc,gc.catId asc')->select();
			$rs['spec']=[];
			//把属于同一个分类的规格整合到一块
			foreach ($specs as $key =>$v){
				$rs['spec'][$v['catId']]['name'] = $v['catName'];
				$rs['spec'][$v['catId']]['list'][] = $v;
			}
			//dump($rs['spec']);die;
			//获取销售规格,商品规格的具体属性
			$sales = Db::name('goods_specs')->where(['goodsId'=>$goodsId,'dataFlag'=>1])->field('id,isDefault,productNo,specIds,marketPrice,specPrice,specStock,initNum,whslePrice')->select();
			if(!empty($sales)){
				//将规格ID格式如:3:4:5:6:7,设为数组键名,与$rs['spec']['catId']['list']['itemId'] 对应
				/*实例
				//$specs转换后$rs['spec']数据
				[11] => array(2) {//11代表规格分类ID
				    ["name"] => string(12) "机身颜色"//规格分类名称
				    ["list"] => array(2) {//当前分类11下的数据
				      [0] => array(6) {
				        ["isAllowImg"] => int(1)
				        ["catName"] => string(12) "机身颜色"
				        ["catId"] => int(11)
				        ["itemId"] => int(5)//这个即代表数据的ID,3:4:(5):6:7就是对应的这个
				        ["itemName"] => string(6) "黄色"
				        ["itemImg"] => string(44) "upload/goods/2017-11/5a0a7e2ee935c_thumb.jpg"
				      }
				      [1] => array(6) {
				        ["isAllowImg"] => int(1)
				        ["catName"] => string(12) "机身颜色"
				        ["catId"] => int(11)
				        ["itemId"] => int(10)
				        ["itemName"] => string(6) "灰色"
				        ["itemImg"] => string(44) "upload/goods/2017-11/5a0a7e3970fed_thumb.jpg"
				      }
				    }
				  }
				//$sales原始数据
				[0] => array(7) {
					    ["id"] => int(3)
					    ["isDefault"] => int(1)
					    ["productNo"] => string(1) "3"
					    ["specIds"] => string(9) "3:4:5:6:7"
					    ["marketPrice"] => string(7) "1070.00"
					    ["specPrice"] => string(7) "1002.00"
					    ["specStock"] => int(0)
				  	}
				//$sales下面转换后数据
				["3:4:5:6:7"] => array(6) {
					    ["id"] => int(3)
					    ["isDefault"] => int(1)
					    ["productNo"] => string(1) "3"
					    ["marketPrice"] => string(7) "1070.00"
					    ["specPrice"] => string(7) "1002.00"
					    ["specStock"] => int(0)
					}*/
				foreach ($sales as $key =>$v){
					$str = explode(':',$v['specIds']);
					sort($str);
					unset($v['specIds']);
					$rs['saleSpec'][implode(':',$str)] = $v;
				}
			}
			//获取商品属性
			$rs['attrs'] = Db::name('attributes')->alias('a')->join('goods_attributes ga','a.attrId=ga.attrId','inner')
			->where(['a.isShow'=>1,'dataFlag'=>1,'goodsId'=>$goodsId])->field('a.attrName,ga.attrVal')
			->order('attrSort asc')->select();
			//获取商品评分
			$rs['scores'] = Db::name('goods_scores')->where('goodsId',$goodsId)->field('totalScore,totalUsers')->find();
			$rs['scores']['totalScores'] = ($rs['scores']['totalScore']==0)?5:WSTScore($rs['scores']['totalScore'],$rs['scores']['totalUsers'],5,0,3);
			WSTUnset($rs, 'totalUsers');
			//关注
			$f = model('Favorites');
			$rs['favShop'] = $f->checkFavorite($rs['shopId'],1);
			$rs['favGood'] = $f->checkFavorite($goodsId,0);
			//$rs['isEct'] = (int)Db::name('goods_pay')->where('goodsId',$goodsId)->value('ectPay');
		}
		//dump($rs);die;
		return $rs;
	}


	public function historyQuery(){
		$ids = cookie("wx_history_goods");
		if(empty($ids))return [];
	    $where = [];
	    $where['isSale'] = 1;
	    $where['goodsStatus'] = 1; 
	    $where['dataFlag'] = 1; 
	    $where['goodsId'] = ['in',$ids];
	    $orderBy = "field(`goodsId`,".implode(',',$ids).")";
        return Db::name('goods')
                   ->where($where)->field('goodsId,goodsName,goodsImg,saleNum,shopPrice')
                   ->order($orderBy)
                   ->paginate((int)input('pagesize'))->toArray();
	}
}