<?php
namespace wstmart\common\model;
use think\Db;
/**
 * 标签业务处理类
 */
class Shopping extends Base{
	/**
	 * 获取助微吧商铺列表
	 * @return [type] [description]
	 */
	public function getHelpShops(){
		$page = (int)input('page',1);
		$rs = cache('QLG_HELP_SHOPS_'.$page);
		if(!$rs){
			$pageSize = input("post.pageSize/d",10);
			$goodsSize = input("post.goodsSize/d",3);
			$lat = input("post.lat",0);
			$lng = input("post.lng",0);
			$where['s.dataFlag'] = 1;
			$where['s.shopStatus'] = 1;
            $where['s.status'] = 1;
            $field = 's.shopId,s.shopImg,s.shopName,s.shopLevel,ROUND(12756.276*ASIN(SQRT(POW(SIN(('.$lat.'*0.0174532925-lat*0.0174532925)/2),2)+
                        COS('.$lat.'*0.0174532925)*COS(lat*0.0174532925)*POW(SIN(('.$lng.'*0.0174532925-lng*0.0174532925)/2),2)))*1000) AS distance';
			$order = 's.shopLevel ASC';
			$rs = Db::name('shops s')
							->where($where)
							->field($field)
							->order($order)
							//->cache(true,86400)
							->paginate($pageSize)
							->toArray();
            //dump($this->getLastSql());
			if(count($rs['Rows']) == 0){
				return WSTReturn('',1,$rs);
			}
			$goods_field = 'g.goodsImg,g.shopPrice,g.goodsId,g.saleTime,g.discountRate';
			foreach ($rs['Rows'] as &$v) {
				$v['goods'] = $this->getShopGoods($v['shopId'],$goodsSize,$goods_field,2);
				foreach ($v['goods'] as &$val) {
					$val['goodsImg'] = WSTImg($val['goodsImg'],3);
				}
			}
			cache('QLG_HELP_SHOPS_'.$page,$rs,60);
		}
		return WSTReturn('',1,$rs);
	}
    public function getHelpSaleShops(){
        $page = (int)input('page',1);
        $rs = cache('QLG_HELP_SALE_SHOPS_'.$page);
        if(!$rs){
            $pageSize = input("post.pageSize/d",10);
            $goodsSize = input("post.goodsSize/d",3);
            $lat = input("post.lat",0);
            $lng = input("post.lng",0);
            $where['s.dataFlag'] = 1;
            $where['s.shopStatus'] = 1;
            $where['s.status'] = 1;
            $field = 's.shopId,s.shopImg,s.shopName,s.shopLevel,ROUND(12756.276*ASIN(SQRT(POW(SIN(('.$lat.'*0.0174532925-lat*0.0174532925)/2),2)+
                        COS('.$lat.'*0.0174532925)*COS(lat*0.0174532925)*POW(SIN(('.$lng.'*0.0174532925-lng*0.0174532925)/2),2)))*1000) AS distance';
            $order = 's.shopLevel ASC';
            $rs = Db::name('shops s')
                ->where($where)
                ->field($field)
                ->order($order)
                //->cache(true,86400)
                ->paginate($pageSize)
                ->toArray();
            //dump($this->getLastSql());
            if(count($rs['Rows']) == 0){
                return WSTReturn('',1,$rs);
            }
            $goods_field = 'g.goodsImg,g.shopPrice,g.goodsId,g.saleTime,g.discountRate';
            foreach ($rs['Rows'] as $k=>&$v) {
                $v['goods'] = $this->getShopGoods($v['shopId'],$goodsSize,$goods_field,3);
                if(sizeof($v['goods'])==0){
                    unset($rs['Rows'][$k]);
                }
                foreach ($v['goods'] as &$val) {
                    $val['goodsImg'] = WSTImg($val['goodsImg'],3);
                }
            }
            cache('QLG_HELP_SALE_SHOPS_'.$page,$rs,60);
        }
        return WSTReturn('',1,$rs);
    }
    /**
	 * 获取列表
	 */
	public function searchHelpGoods($goodsCatIds = []){
		//查询条件
		$keyword = input('keyword');
		$brandId = input('brandId/d');
		$where = $where2 = [];
		$where['goodsStatus'] = 1;
		$where['g.dataFlag'] = 1;
		$where['isSale'] = 1;
		$where['discountRate'] = ['>=',dataConf('discountRateGtToHelp')];
		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 = ['discountRate','saleNum','shopPrice','visitNum','saleTime'];
		$pageOrder = ['desc','asc'];
		if(!empty($goodsCatIds))$where['goodsCatIdPath'] = ['like',implode('_',$goodsCatIds).'_%'];
		$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;
	}
	/**
	 * 获取逛商铺轮播
	 * @return [type] [description]
	 */
	public function getCarousel(){
        return WSTReturn('',1,listAds('ads-qlgshopping',6,86400));
	}
	/**
	 * 获取助微吧轮播
	 * @return [type] [description]
	 */
	public function getHelpCarousel(){
        return WSTReturn('',1,listAds('ads-qlghelp',6,86400));
	}
	/**
	 * 获取助购吧轮播
	 * @return [type] [description]
	 */
	public function getHelpShopCarousel(){
        return WSTReturn('',1,listAds('ads-qlghelpshop',6,86400));
	}

	/**
	 * 获取逛商铺商铺列表
	 * @return [type] [description]
	 */
	public function getShops(){
		$page = (int)input('page',1);
		$rs = cache('QLG_SHOPPING_SHOPS_'.$page);
		if(!$rs){
			$pageSize = input("post.pageSize/d",10);
			$goodsSize = input("post.goodsSize/d",3);
			$lat = input("post.lat",0);
			$lng = input("post.lng",0);
			//通过获取4个点,从而获取到经度的最大值与最小值已经纬度的最大最小值,通过数据库查询获取到在此范围内的数据

			//获取该用户所在的地区附近的4个点
			$start = $this->returnSquarePoint($lng,$lat,500);
			$where['s.dataFlag'] = 1;
			$where['s.shopStatus'] = 1;
			//$where['s.shopType'] = input("post.shopType/d",1);;
            $where['s.status'] = 1;
            $field = 's.shopId,s.shopImg,s.shopName,
                        ROUND(12756.276*ASIN(SQRT(POW(SIN(('.$lat.'*0.0174532925-lat*0.0174532925)/2),2)+
                        COS('.$lat.'*0.0174532925)*COS(lat*0.0174532925)*POW(SIN(('.$lng.'*0.0174532925-lng*0.0174532925)/2),2)))*1000) AS distance';
//                      ROUND(6378.138*2*ASIN(SQRT(POW(SIN(('.$lat.'*PI()/180-lat*PI()/180)/2),2)+
//                      COS('.$lat.'*PI()/180)*COS(lat*PI()/180)*POW(SIN(('.$lng.'*PI()/180-lng*PI()/180)/2),2)))*1000) AS distance';
			$order = 'distance ASC';
            //纬度
			//$where['s.lat']=array('between',array($start['left-bottom']['lat'],$start['left-top']['lat']));
			//经度
			//$where['s.lng']=array('between',array($start['left-bottom']['lng'],$start['right-bottom']['lng']));
			$rs = Db::name('shops s')
							->where($where)
							->field($field)
							->order($order)
							//->cache(true,86400)
							->paginate($pageSize)
							->toArray();
            //dump($this->getLastSql());
			if(count($rs['Rows']) == 0){
				return WSTReturn('',1,$rs);
			}
//			foreach ($rs['Rows'] as &$v){
//                $v['distance'] = $this->getDistance($lat, $lng, $v['lat'], $v['lng']);
//            }
			$goods_field = 'g.goodsImg,g.shopPrice,g.goodsId,g.saleTime,g.discountRate';
			foreach ($rs['Rows'] as &$v) {
				$v['goods'] = $this->getShopGoods($v['shopId'],$goodsSize,$goods_field,1);
				foreach ($v['goods'] as &$val) {
					$val['goodsImg'] = WSTImg($val['goodsImg'],3);
				}
				// if($v['goods']){
				// 	$v['newTime'] = $v['goods']['0']['saleTime'];
				// }else{
				// 	$v['goods'] = [];
				// 	$v['newTime'] = date('Y-m-d');
				// }
			}
			cache('QLG_SHOPPING_SHOPS_'.$page,$rs,10);
		}
		return WSTReturn('',1,$rs);
	}
	/**
	 * 获取逛商都推荐商品
	 */
	public function getGoods(){
		$page = (int)input('page',1);
		$type = (int)input('type',1);//1逛商都2助微吧
		if(1 == $type){
			$scale = dataConf('discountRateGtToShopping');
		}elseif(2 == $type){
			$scale = dataConf('discountRateGtToHelp');
		}else{
            $scale = dataConf('discountRateGtToHelpShopping');
        }
		$cacheData = cache('QLG_SHOPPING_GOODS_'.$type.'_'.$page);
		if($cacheData)return $cacheData;
		$rs = Db::name('goods')
			->where(['isSale'=>1,'dataFlag'=>1,'goodsStatus'=>1,'discountRate'=>['>=',$scale]])
			->field('goodsId,goodsName,goodsImg,shopPrice,saleNum,discountRate')
			->order('discountRate DESC,goodsId DESC')
			->paginate(input('pageSize/d',10))->toArray();
		cache('QLG_SHOPPING_GOODS_'.$type.'_'.$page,$rs,3600);
		return $rs;
	}
	/**
     * 获取店铺商品
     */
    public function getShopGoods($shopId,$num,$field,$type){
    	$order='saleNum DESC';
    	$where['g.shopId'] = $shopId;
    	$where['g.dataFlag'] = 1;
    	$where['g.goodsStatus'] = 1;
        $where['g.isSale'] = 1;
        $scale = 0;
        if(1 == $type){
            $scale = dataConf('discountRateGtToShopping');
        }elseif(2 == $type){
            $scale = dataConf('discountRateGtToHelp');
        }else{
            $scale = dataConf('discountRateGtToHelpShopping');
        }
    	$rs = Db::name('shops')->alias('s')
	    	->join('__GOODS__ g','s.shopId=g.shopId','inner')
	    	->field($field)
	    	->where($where)
	    	->where(['discountRate'=>['>=',$scale]])
	    	->limit($num)
	    	->order($order)
	    	//->cache(true,600)
	    	->select();
    	return $rs;
    }
	/**
 * 计算某个经纬度的周围某段距离的正方形的四个点
 *
 * @param
 *            radius 地球半径 平均6371km
 * @param
 *            lng float 经度
 * @param
 *            lat float 纬度
 * @param
 *            distance float 该点所在圆的半径,该圆与此正方形内切,默认值为50千米
 * @return array 正方形的四个点的经纬度坐标
 */
public function returnSquarePoint($lng, $lat, $distance = 50, $radius = 6371)
{
    $dlng = 2 * asin(sin($distance / (2 * $radius)) / cos(deg2rad($lat)));
    $dlng = rad2deg($dlng);

    $dlat = $distance / $radius;
    $dlat = rad2deg($dlat);

    return array(
        'left-top' => array(
            'lat' => $lat + $dlat,
            'lng' => $lng - $dlng
        ),
        'right-top' => array(
            'lat' => $lat + $dlat,
            'lng' => $lng + $dlng
        ),
        'left-bottom' => array(
            'lat' => $lat - $dlat,
            'lng' => $lng - $dlng
        ),
        'right-bottom' => array(
            'lat' => $lat - $dlat,
            'lng' => $lng + $dlng
        )
    );
}


/**
 *  @desc 根据两点间的经纬度计算距离
 *  @param float $lat 纬度值
 *  @param float $lng 经度值
 */
function getDistance($lat1, $lng1, $lat2, $lng2)
{
    $earthRadius = 6371000;
    $lat1 = ($lat1 * pi() ) / 180;
    $lng1 = ($lng1 * pi() ) / 180;

    $lat2 = ($lat2 * pi() ) / 180;
    $lng2 = ($lng2 * pi() ) / 180;

    $calcLongitude = $lng2 - $lng1;
    $calcLatitude = $lat2 - $lat1;
    $stepOne = pow(sin($calcLatitude / 2), 2) + cos($lat1) * cos($lat2) * pow(sin($calcLongitude / 2), 2);  $stepTwo = 2 * asin(min(1, sqrt($stepOne)));
    $calculatedDistance = $earthRadius * $stepTwo;
    return round($calculatedDistance);
}

}