<?php
/**
	* @method 购物车
	* @author 许
	* @copyright 2017/8/3
	*/
class B2cCart extends B2cBase
{

	/**
	  * @method 加入购物车
	  * @http  get
	  * @param uid      int [必填]  用户ID
	  * @author soul
	  * @copyright 2019/10/16
	  * @return 
		pro_sale_price:普通销售价   price：实际购买价格  car_add_price：加入购物车时的价格
	  {"status":true,"data":[{"shop_info":{"shop_id":"224467","shop_uid":"224467","shop_name":"\u83f2\u5c14\u5954\u5b9d","shop_domain":"https:\/\/www.paojd.cn\/shop224467\/"},"items":[{"car_add_price":"140.00","car_checked":"1","car_count":"1","car_prpa_id":"0","shop_id":"224467","pro_id":"122202","pro_name":"FREY(\u83f2\u5c14)\u54c1\u724c\u5b9d\u9a6cE36\u524d\u4e0b\u60ac\u6302\u7403\u5934\u5de6\u53f3\u901a\u7528","pro_sale_price":"140.00","price":"140.00","price_type":1,"pic":["https:\/\/file.paojd.cn\/center\/read.php?site=b2c&c=product&f=shop224467\/product\/400\/e4743d18c0fe56a7.jpg&i=f1"]},{"car_add_price":"50.00","car_checked":"1","car_count":"2","car_prpa_id":"0","shop_id":"224467","pro_id":"121319","pro_name":"FREY(\u83f2\u5c14)\u54c1\u724c\u5b9d\u9a6c N45 N46 N40 E90 E46 E83 E81\u673a\u6cb9\u6ee4\u6e05\u5668","pro_sale_price":"50.00","price":"50.00","price_type":1,"pic":["https:\/\/file.paojd.cn\/center\/read.php?site=b2c&c=product&f=shop224467\/product\/400\/f4f3654e2585f172.jpg&i=f1"]}]},{"shop_info":{"shop_id":"230275","shop_uid":"230275","shop_name":"\u8def\u5b9d\u9646\u54c1\u724c\u6613\u635f\u8d85\u5e02","shop_domain":"https:\/\/www.paojd.cn\/shop230275\/"},"items":[{"car_add_price":"280.00","car_checked":"0","car_count":"1","car_prpa_id":"0","shop_id":"230275","pro_id":"132012","pro_name":"\u8def\u5b9d\u9646\uff08KGN\uff09 \u5239\u8f66\u7247 \u6602\u79d1\u96f7 \u540e\u5239\u8f66\u7247 D883","pro_sale_price":"280.00","price":"280.00","price_type":1,"pic":["https:\/\/file.paojd.cn\/center\/read.php?site=b2c&c=product&f=shop230275\/product\/400\/a002118a7dd2cf1f.jpg&i=f1"]}]}],"code":0}
	  */
	public function getCartList($uid) 
	{	
		$arr = [];
		$uid = (int) $uid;
		if($uid < 0) return LibFc::ReturnData(false, '用户ID不存在！');
		$arr = [];
		$filed = ['car_add_price', 'car_checked', 'car_count', 'car_prpa_id', 'shop_id','shop_uid','shop_name', 'shop_logo','shop_domain','pro_id', 'pro_name', 'pro_sale_price', 'pro_promotion_price', 'pro_user_discount', 'pro_promotion_btime', 'pro_promotion_etime', 'pro_price_vip1', 'pro_price_vip2', 'pro_price_vip3', 'pro_price_vip4'];
		$table = 'us_cart right join bc_product on car_pro_id=pro_id right join sh_shop on shop_id=pro_shop_id';
		$where = ' and car_prpa_id=0 and car_uid='.$uid.' and shop_status=1 and pro_status = 1';
		$where .= ' order by car_add_time desc';
		$cres = $this->get($table, $filed, $where);
		if(empty($cres['data'])) return LibFc::ReturnData(true, $arr);
		$proIdArr = array_column($cres['data'], 'pro_id');

		$B2cProduct = new B2cProduct();
		$picRes = $B2cProduct->getProductPic($proIdArr, false);
		$picArr = $picRes['data'];
		foreach($cres['data'] as $v)
		{
			if(empty($arr[$v['shop_id']]))
			{
				$v['shop_logo']=mvc::$cfg['FILE_CENTER']['b2c']['url_get'].'&c=shopLogo&f='.$v['shop_logo'].mvc::$cfg['FILE_CENTER']['b2c']['get_uri'];
				$arr[$v['shop_id']] = [
					'shop_info'=>[
						'shop_id'=>$v['shop_id'],
						'shop_uid'=>$v['shop_uid'],
						'shop_name'=>$v['shop_name'],
						'shop_logo'=>$v['shop_logo'],
						'shop_domain'=>$v['shop_domain']
					],
					'items'=>[]
				];
			}
			unset($v['shop_uid']); unset($v['shop_name']); unset($v['shop_domain']);
			$v['price'] = $v['pro_promotion_price'] > 0 && $v['pro_promotion_btime'] <= time() && $v['pro_promotion_etime'] >= time()? $v['pro_promotion_price']: $v['pro_sale_price'];
			$v['price_type']=$v['pro_promotion_price'] > 0 && $v['pro_promotion_btime'] <= time() && $v['pro_promotion_etime'] >= time()? 2: 1; //价格类型  1：销售价 2 促销价 3 会员价
			if($v['pro_user_discount']=='Y')
			{
				//获取该会员在店铺里的级别
				$table = 'sh_member_link join sh_member on mem_id=meml_mem_id and mem_status=1 and meml_shop_id=mem_shop_id';
				$levelRes = $this->get($table, ['mem_mel_id'], sprintf(" and meml_shop_id=%d and meml_uid=%d", $v['shop_id'], $uid), true);
				if(!empty($levelRes['data']) && $v['pro_price_vip'.$levelRes['data']['mem_mel_id']] > 0 && $v['pro_price_vip'.$levelRes['data']['mem_mel_id']] < $v['price'])
				{
					$v['price'] = $v['pro_price_vip'.$levelRes['data']['mem_mel_id']];
					$v['price_type'] = 3;
				}
			}
			unset($v['pro_promotion_price']);
			unset($v['pro_promotion_btime']);
			unset($v['pro_promotion_etime']);
			unset($v['pro_price_vip1']);
			unset($v['pro_price_vip2']);
			unset($v['pro_price_vip3']);
			unset($v['pro_price_vip4']);
			unset($v['pro_user_discount']);
			$v['pic'] = empty($picArr[$v['pro_id']])? [] : $picArr[$v['pro_id']];
			$arr[$v['shop_id']]['items'][] = $v;
		}
		$arr = array_values($arr);
		return LibFc::ReturnData(true, $arr);
	}



	/**
	* @method 删除购物车商品
	* @param  $_POST['PROID']; 商品ID array
	* @param  $userId  用户ID int
	* @author     xu
	* @copyright 2017-08-07
	* @return 成功：{'status':true,'data':'success','code':0} 失败：{'status':false,'data':'error'/'参数错误！','code':0}
	*/
	public function delShoppingCart($proId,$userId) 
	{	
		//参数
		if(!is_array($proId))
			$proId = [$proId];
		if(empty($proId = array_filter($proId)) || !LibFc::Int($userId))
			return LibFc::ReturnData(false,'参数错误！');

		//执行
		$table = "us_cart";
		$where = sprintf(" and car_pro_id in (%s) and car_uid=%d", implode(',',$proId) ,$userId);
		$this->del($table,$where);

		// 返回
		return LibFc::ReturnData(true,"success");	
	}


	/**
	 * @method    添加购物车
	 * @param     [int]     $proId   [产品ID]
	 * @param     [int]     $userId  [用户ID]
	 * @param     integer    $num     [添加的数量]
	 * @param     boolean    $isCheck [是否选中]
	 * @author    xu
	 * @return {"status":true,"data":此产品在购物车的最新数量,"code":0}
	 * @copyright 2017-08-14
	 */
	public function addCart($proId,$userId,$num=1,$isCheck=true)
	{
		if(!LibFc::Int($proId) || (!LibFc::Int($userId)) || !LibFc::Int($num) || $num<=0 ) return LibFc::ReturnData(false,'用户不存在或者产品不存在参数错误');

		// 校验商品上架或者预售
		$res = $this->get('bc_product',['*'],sprintf(" and pro_id=%d and pro_status = 1",$proId),true);
		$product = $res['data'];
		
		if(empty($product)) return LibFc::ReturnData(false,'商品未上架或者已经售完！');

		// 处理售价
		if(!empty($product['pro_promotion_price']) && 
			time()>$product['pro_promotion_btime'] && 
			time()<$product['pro_promotion_etime'] &&
			$product['pro_promotion_price']<$product['pro_sale_price'])
		{
			$price = $product['pro_promotion_price'];
		}
		else
		{
			$price = $product['pro_sale_price'];
		}

		// 校验商品是否当前用户的店铺的
		$res = $this->get('sh_shop',['*'],sprintf(" and shop_uid=%d ",$userId),true);
		if(!empty($res['data']) && ($res['data']['shop_id']==$product['pro_shop_id']))return LibFc::ReturnData(false,'用户不能添加自己的配件至购物车！'); 
		// 判定是否已经存在购物车之中
		$res = $this->get('us_cart',['*'],sprintf(" and car_uid=%d and car_pro_id=%d",$userId,$proId),true);

		if(!empty($res['data']))
		{

			$num = (($num+$res['data']['car_count'])>=$product['pro_count'])?$product['pro_count']:($num+$res['data']['car_count']);

			$temp = array(
					'car_count'=>$num,
					'car_add_time'=>time(),
					'car_add_price'=>$price,
					'car_checked' =>$isCheck
				);
			$this->set("us_cart",$temp,sprintf(" and car_uid=%d and car_pro_id=%d",$userId,$proId));
		}
		else
		{
			$num = ($num >= $product['pro_count']) ? $product['pro_count']:$num;
			$temp = array(
					'car_uid'=>$userId,
					'car_pro_id'=>$proId,
					'car_count'=>$num,
					'car_add_time'=>time(),
					'car_add_price'=>$price,
					'car_checked' =>1
				);
			$this->add("us_cart",$temp);
		}

		return LibFc::ReturnData(true, $num);
	}

	/**
	  * @method 根据购买的产品获取对应的运费【产品必须是同一个店铺内的】
	  * @http  post
	  * @param pros    array [必填]  [['pro_id'=>111, 'buy_count'=>1], ...]
	  * @param pct_ids string [必填]  省市区ID  19,1901,14423
	  * @param style string [选填] 运送方式  快递0  EMS1  默认all(返回所有类型)  
	  * @author soul
	  * @copyright 2019/10/16
	  * @return {"status":true,"data":,"code":0}
	  */
	public function getProFreight($proArr, $pctIds, $uid = 0, $style = 'all')
	{
		$uid = (int) $uid;
		$t = explode(',', $pctIds);
		$cityId = $t[1];
		if($cityId < 1) return LibFc::ReturnData(false, '运费计算失败，提供的省市参数有误！');
		$styleNameArr = [
			0=>'快递',
			1=>'EMS'
		];
		if($style != 'all' && empty($styleNameArr[$style])) return LibFc::ReturnData(false, '运费计算失败，提供的运送方式参数有误！');

		$styleArr = $style == 'all' ? [0, 1]: [(int) $style];
		$tPro = [];
		$baoyou = false;
		foreach($proArr as $v)
		{
			$v['pro_id'] = (int) $v['pro_id'];
			$v['buy_count'] = (int) $v['buy_count'];
			if($v['pro_id'] > 0 && $v['buy_count'] > 0)
			{
				$tPro[$v['pro_id']] = $v;
			}
			else
			{
				return LibFc::ReturnData(false, '运费计算失败，提供的产品参数有误！');
			}
		}

		//产品是不是同一个店铺
		$table = 'bc_product join bc_product_info on pro_id = pri_pro_id';
		$pres = $this->get($table, ['pro_id, pro_count, pro_name, pro_shop_id, pro_count, pri_weight, pri_frt_id'], sprintf(" and pro_id in (%s)", implode(',', array_keys($tPro))));
		if(empty($pres['data'])) return LibFc::ReturnData(false, '计算运费失败，配件不存在！');

		$frtIdArr = array_unique(array_column($pres['data'], 'pri_frt_id'));

		$t = array_unique(array_column($pres['data'], 'pro_shop_id'));
		if(count($t) > 1) return LibFc::ReturnData(false, '运费计算失败，不允许跨店铺计算运费！');
		$shopId = $t[0];
		foreach($pres['data'] as $v)
		{
			$tPro[$v['pro_id']] = array_merge($tPro[$v['pro_id']], $v);
		}
		foreach($tPro as $proId=>$pv)
		{
			if(empty($pv['pro_shop_id'])) return LibFc::ReturnData(false, '计算运费失败，配件ID：'.$proId.'不存在！');
			if($pv['buy_count'] > $pv['pro_count']) return LibFc::ReturnData(false, '计算运费失败，'.$pv['pro_name'].'库存不足！');
			if(empty($pv['pri_frt_id'])) return LibFc::ReturnData(false, '计算运费失败，"'.$pv['pro_name'].'"未指定运费模板！');
		}

		//店铺配件满多少包邮，-1表示不开启
		$res = $this->get('sh_shop', ['shop_baoyou','shop_id'],sprintf(' and shop_id=%d', $shopId), true);
		$shopArr = $res['data'];
		if($shopArr['shop_baoyou'] > 0)
		{
			//获取配件的价格
			$B2cProduct = new B2cProduct();
			$res = $B2cProduct->getAnyProductPrice(array_keys($tPro), $uid);
			$priceArr = $res['data'];
			//var_dump($priceArr);
			$proMoney = 0.00;
			foreach($tPro as $proId=>$pv)
			{
				if(empty($priceArr[$proId]['price']) || $priceArr[$proId]['price'] <= 0)  return LibFc::ReturnData(false, '计算运费失败，"'.$pv['pro_name'].'"价格异常！');
				$proMoney += $priceArr[$proId]['price']*$pv['buy_count'];
			}
			//满足满减
			if($proMoney >= $shopArr['shop_baoyou'])
			{
				$baoyou = true;
			}
		}
		
		//不够满减
		if(!$baoyou)
		{
			$arr = [];
			$where = sprintf(' and frt_shop_id=%d and frt_id in (%s)', $shopId, implode(',', $frtIdArr));
    		$res = $this->get('sh_freight_tpl', ['frt_id', 'frt_is_free','frt_valuation_method'], $where);
			$frtArr = array_column($res['data'], null, 'frt_id');
			
			//运费模板情况
			$filed = ['ftl_frt_id', 'ftl_shipping_method', 'ftl_default','ftl_begin_count','ftl_begin_money','ftl_next_count','ftl_next_money','ftl_cities'];
			$where = sprintf(' and ftl_shipping_method in (%s) and ftl_frt_id in (%s)', implode(',', $styleArr), implode(',', $frtIdArr));
    		$res = $this->get('sh_freight_tpl_link', $filed, $where);
			//根据城市ID确认哪条合适
			foreach($res['data'] as $v)
			{
				$v['ftl_cities'] = explode(',', $v['ftl_cities']);
				
				if(in_array($cityId, $v['ftl_cities']))
				{
					$v['end'] = 1;
					$frtArr[$v['ftl_frt_id']][$v['ftl_shipping_method']] = $v;
				}
				else if(empty($frtArr[$v['ftl_frt_id']][$v['ftl_shipping_method']]['end']) && $v['ftl_default'] == 'Y')
				{
					$frtArr[$v['ftl_frt_id']][$v['ftl_shipping_method']] = $v;
				}
			}

			//剔除不支持的运送方式
			foreach($tPro as $proId=>$pv)
			{
				if(empty($frtArr[$pv['pri_frt_id']])) return LibFc::ReturnData(false, '计算运费失败，"'.$pv['pro_name'].'"运费模板不存在！');
				foreach($styleArr as $tk=>$method)
				{
					if(empty($frtArr[$pv['pri_frt_id']][$method])) unset($styleArr[$tk]);
				}
			}
			
			$frtMoney = [];
			foreach($tPro as $proId=>$pv)
			{
				foreach($styleArr as $method)
				{
					//按重量计算
					if($frtArr[$pv['pri_frt_id']]['frt_valuation_method'] == 1)
					{
						$frtMoney[$method][$pv['pri_frt_id']]['weight'] += $pv['pri_weight']*$pv['buy_count'];
					}
					else
					{
						//按数量计算
						$frtMoney[$method][$pv['pri_frt_id']]['count'] += $pv['buy_count'];
					}
				}
			}
			
			foreach($frtMoney as $method=>$fv)
			{
				$money = 0;
				foreach($fv as $frtid=>$fvv)
				{
					if($frtArr[$frtid]['frt_is_free'] == 'Y') continue;
					$tfrt = $frtArr[$frtid][$method];
					$money += $tfrt['ftl_begin_money'];
					if($frtArr[$frtid]['frt_valuation_method'] == 1 && $fvv['weight'] > $tfrt['ftl_begin_count'])
					{
						$money += ceil(($fvv['weight']- $tfrt['ftl_begin_count'])/$tfrt['ftl_next_count'])*$tfrt['ftl_next_money'];
					}
					else if($frtArr[$frtid]['frt_valuation_method'] != 1 && $fvv['count'] > $tfrt['ftl_begin_count'])
					{
						$money += ceil(($fvv['count']- $tfrt['ftl_begin_count'])/$tfrt['ftl_next_count'])*$tfrt['ftl_next_money'];
					}
				}
				$arr[] = ['baoyou'=>$money > 0? 0: 1, 'yunfei'=>sprintf("%.2f", $money), 'style'=>$method, 'style_name'=>$styleNameArr[$method]];
			}
		}
		else
		{
			$arr = [
				['baoyou'=>1, 'yunfei'=>'0.00', 'style'=>0, 'style_name'=>$styleNameArr[0]]
			];
		}
		return LibFc::ReturnData(true, $arr);
	}
}