<?php
/**
 *      [XCECP] (C) COLNET Inc.
 *      This is NOT a freeware, use is subject to license terms
 */
if(!defined("IN_QKWEB")){exit("Access Denied");}
class PurchaseAction extends BaseAction{
	function __construct(){
		$act = getgpc("act","P");
		if(ACTION_NAME=='shoppingcart' && ($act=='' || $act=='add' || $act=='del' || $act=='edit')){
		}else{
			//BaseAction::checkLogin();
		}
	}
	function index(){
		
	}
	function shoppingcart(){
		global $db,$_G;
		load_class("purchase");
		$pm = new PurchaseModel();
		$userId = $_SESSION['userId'];
		$act = getgpc("act","P");
		$inajax = getgpc("inajax","P");
		if($inajax==1){
			if($act=="add"){
				$goodsId = getgpc("goodsId","P");
				$pnum =  trim(getgpc("pnum"));
				$spec = addslashes(trim(getgpc('spec')));
				$remark = trim(getgpc('remark',"P"));
				if($pnum && $goodsId && settype($pnum,"integer") && settype($goodsId,"integer")){
					$inventory = $db->getOne("select inventory from `qk_goods` where id='$goodsId'");
					if(!$inventory || !is_numeric($inventory) || $inventory<1 || $inventory<$pnum){exit('{"success":false,"message":"商品库存不足","type":1}');}
					if($userId){
						$sql = "select id from qk_shoppingcart where (userId='$userId' or sessionId='".session_id()."') and goodsId='$goodsId'";
					}else{
						$sql = "select id from qk_shoppingcart where (sessionId='".session_id()."') and goodsId='$goodsId'";
					}
					$res = $db->getOne($sql);
					if($res){
						exit('{"success":true,"message":"'.$_G['lang']['purchase']['cart']['repeat'].'","type":1}');
					}else{
						$sql = "insert into qk_shoppingcart set userId='$userId',sessionId='".session_id()."',pnum='$pnum',spec='$spec',goodsId='$goodsId',remark='$remark',posttime=UNIX_TIMESTAMP()";
						$db->query($sql);
						exit('{"success":true,"message":"'.$_G['lang']['purchase']['cart']['success'].'","type":3}');
					}
				}
			}else if($act=="edit"){
				//print_r($_POST);
				$id = getgpc("id","P");
				$col = getgpc("col","P");
				$val = getgpc("val","P");
				if($id && settype($id,"integer") && in_array($col,array('remark','pnum')) && $val){
					$sql = "update qk_shoppingcart set `$col`='$val' where (userId='$userId' or sessionId='".session_id()."') and id='$id'";
					if($db->query($sql)){
						exit('{"success":true,"message":"修改成功","type":3}');
					}else{
						exit('{"success":false,"message":"修改失败","type":2}');
					}
				}else{
					exit('{"success":false,"message":"修改失败，提交信息不正确","type":2}');
				}
			}else if($act=="del"){
				$id = getgpc("id","P");
				if($id && settype($id,"integer")){
					if($pm->del($id)){
						exit('{"success":true,"message":"success","type":3}');
					}
				}
			}else if($act=="clear"){
				if($pm->clear()){
					exit('{"success":true,"message":"清空购物车成功","type":3}');
				}else{
					exit('{"success":false,"message":"清空购物车失败","type":3}');
				}
			}
		exit('{"success":false,"message":"Error","type":2}');
		}
		load_class("goods");
		$gm = new GoodsModel();
		//print_r($gm->goodsInfo(35));exit;
		$cartInfo = $pm->cartInfo();
		//print_r($cartInfo);exit;
		assign("cartInfo",$cartInfo);
		$pageInfo['title'] = '购物车 - '.$GLOBALS['siteConf']['siteName'];
		assign("pageInfo",$pageInfo);

		load_class("user");
		$um = new UserModel();
		$userInfo = $um->getInfo($userId);
		assign("userInfo",$userInfo);

		display("purchase/shoppingcart");
	}

	function order(){
		BaseAction::checkLogin();
		global $db;
		$userId = $_SESSION['userId'];
		load_class("user");
		load_class("order");
		$om = new OrderModel();
		load_class("goods");
		$gm = new GoodsModel();
		load_class("purchase");
		$pm = new PurchaseModel();
		$cartInfo = $pm->cartInfo();
		assign("cartInfo",$cartInfo);

		$act = getgpc("act");
		$inajax = getgpc("inajax");
		if($inajax==1){
			if($act=="save"){
				$id = getgpc("id","P");
				$addrId = getgpc("addrId","P");
				$shipType = getgpc("shipType","P");
				$remark = getgpc("remark","P");

				if($id && settype($id,"integer")){
					$sql = "update qk_order set ";
					$sqlEnd = " where id='$id'";
				}else{
					$sql = "insert into qk_order set";
					$sqlEnd = ",posttime=UNIX_TIMESTAMP()";
				}
				$sql .= " addrId='$addrId',deliveryTypeId='$shipType',remark='$remark',iStatus=0,userId='$userId'";

				$sql .= $sqlEnd;
				if($db->query($sql)){
					//if($om->finish($_POST)){
						exit('{"success":true,"errno":0,"message":"success","type":3}');
					//}
				}
				exit();
			}else if($act=="confirm"){
				if($om->confirm($_POST)){
					exit('{"success":true,"message":"success","type":3}');
				}else{
					exit('{"success":false,"message":"'.$om->errString.'","type":2}');
				}
			}else if($act=="finish"){
				$orderId = $om->finish($_POST);
				if($orderId && settype($orderId,"integer")){
					$ret = array('success'=>true,'errno'=>0,'message'=>'success','type'=>3,'orderId'=>$orderId,'url'=>$GLOBALS['baseUrl'].'order/pay/orderId/'.$orderId);
					echo json_encode($ret);exit;
				}else{
					exit('{"success":false,"errno":0,"message":"'.$om->errString.'","type":3,"data":{"errCode":-100,"errMsg":"'.$om->errString.'"}}');
				}
			}else if($act=="add"){
				$consignee = getgpc("consignee","P");
				$address = getgpc("address","P");
				$zipcode = getgpc("zipcode","P");
				$mobile = getgpc("mobile","P");
				$phone = getgpc("phone","P");
				$deliveryTypeId = getgpc("deliveryTypeId","P");
				$paytypeId = getgpc("paytypeId","P");
				$invoicetypeId = getgpc("invoicetypeId","P");
				$ftypeId = getgpc("ftypeId","P");
				$invoiceTitle = getgpc("invoiceTitle","P");
				$invoiceContentId = getgpc("invoiceContentId","P");

				$remark = getgpc("remark","P");				

				$deliveryPrice = $db->getOne("select price from qk_delivery where id='$deliveryTypeId'");

				$sql = "select cart.*,goods.price from qk_shoppingcart as cart  left join qk_goods as goods on cart.goodsId=goods.id where userId='$userId' or sessionId='".session_id()."' order by id desc";
				$cartInfo = $db->getAll($sql);

				if(!$cartInfo || count($cartInfo)==0){
					exit('{"success":false,"message":"购物车中无商品，请先选择要购买的商品","type":2}');
				}

				$sql = "insert into qk_order set";
				$sql .= " userId='$userId',consignee='$consignee',address='$address',zipcode='$zipcode',mobile='$mobile',phone='$phone',deliveryTypeId='$deliveryTypeId'";
				$sql .= ",paytypeId='$paytypeId',iStatus=4,invoicetypeId='$invoicetypeId',ftypeId='$ftypeId',invoiceTitle='$invoiceTitle',invoiceContentId='$invoiceContentId'";
				$sql .= ",remark='$remark'";
				$sql .= ",posttime=UNIX_TIMESTAMP()";
				$db->query($sql);
				$orderId = $db->insert_id();
				settype($deliveryPrice,"integer");
				$price = $deliveryPrice;
				foreach($cartInfo as $item){
					settype($item['price'],"float");
					settype($item['pnum'],"integer");
					$price += $item['priceNow']*$item['pnum'];
					if($item['prizePrice']){$price -= $item['prizePrice'];}
					$sql = "insert into qk_order_goods set orderId='$orderId',goodsId='".$item['goodsId']."',pnum='".$item['pnum']."',prizeId='".$item['prizeId']."',posttime=UNIX_TIMESTAMP()";
					if(@$db->query($sql)){
						$sql = "delete from qk_shoppingcart where id='".$item['id']."'";
						$db->query($sql);
					}
				}
				$sql = "update qk_order set amount='$price' where userId='$userId' and id='$orderId'";
				$db->query($sql);
				exit('{"success":true,"message":"","type":3}');
			}else if($act=="listcart"){
				//$cartInfo="";
				$prizePrice = 0;
				$tmp = '{"errno":0,"data":{"invoice":{"isCanVAT":true,"hasNoteBook":0,"contentOpt":["商品明细"]},"items":{"1":{"items":{';
				$i=0;
				$totalAmt = 0;
				$scorePrice = 0;
				foreach($cartInfo as $item){
					$tmp .='"'.$item['goodsId'].'":{"product_id":'.$item['goodsId'].',"buy_count":'.$item['pnum'].',"main_product_id":'.$item['goodsId'].',"price_id":0,"uid":'.$_SESSION['userId'].',"matchNum":'.$item['pnum'].',"name":"'.$item['goodsInfo']['name'].'","size":{"SysNo":597,"Size1SysNo":595,"Size2ID":"913","Size2Name":"专业版","Status":0},"color":"","product_char_id":"01-100-535","pic_num":4,"weight":200,"type":0,"flag":72,"c3_ids":"297","restricted_trans_type":"无限制","market_price":189900,"psystock":1,"canAddToWireLessCart":true,"rushing_buy":false,"canVAT":true,"canUseCoupon":true,"price":'.($item['goodsInfo']['priceNow']*100).',"scorePrice":'.$item['goodsInfo']['scorePrice'].',"cash_back":0,"point":0,"num_limit":999,"array_days":"有货，待备货，2天后配送","gift":[]}';
					$i++;
					if($i<count($cartInfo)){
						$tmp .= ",";
					}
					$pnum = $item['pnum'];
					if($item['prizeId']){$pnum--; $prizePrice += $item['goodsInfo']['priceNow']*100;}
					if($item['goodsInfo']['buyWay']!=2){
						$totalAmt += $item['pnum']*$item['goodsInfo']['priceNow']*100;
					}

					$scorePrice += $item['goodsInfo']['scorePrice'];
					
				}
				$tmp.='},"isVirtual":true,"totalAmt":'.$totalAmt.',"totalCut":0,"totalWeight":1450,"rule_benefits":0}},"totalCut":0,"totalAmt":'.$totalAmt.',"totalWeight":1450,"conflictProducts":[],"promotion":[],"userIsDealer":false,"prizePrice":'.$prizePrice.',"scorePrice":'.$scorePrice.'}}';
				exit($tmp);
			}else if($act=="getshippingtype"){
				$weight=0;
				$virtual = true;
				foreach($cartInfo as $item){
					if($item['goodsInfo']['freeDelivery']==0){
						$virtual = false;
						$weight += $item['goodsInfo']['weight'];
					}
				}
				$price = $weight;
				$tmp = '{"errno":0,"data":{';
					load_class("delivery");
					$dm = new DeliveryModel();
					$sql = "select id from qk_delivery_type where iStatus=1 order by sortId asc,id asc";
					$delivery = $db->getAll($sql);
					$i=0;
					foreach($delivery as $item){
						$info = $dm->getTypeInfo($item['id']);
						$price = $dm->getPrice($weight,$item['id'],$cartInfo);
						$price = $price*100;
						if($virtual){$price=0;}
							$tmp.= '"'.$info['id'].'":{"SysNo":'.$info['id'].',"ShipTypeID":"'.$info['id'].'","ShipTypeName":"'.$info['name'].'","ShipTypeDesc":"'.$info['detail'].'","PremiumRate":"0.010000","PremiumBase":0,"FreeShipBase":0,"Status":1,"StatusQueryType":2,"StatusQueryUrl":"http:\/\/www.ems.com.cn\/qcgzOutQueryAction.do?reqCode=gotoSearch","IsOnlineShow":1,"ShippingId":'.$info['id'].',"shippingPrice":'.$price.',"subOrder":{"1":{"shippingPrice":'.$price.'}},"shippingPriceCut":0}';
							$i++;
							if($i<count($delivery)){
								$tmp .= ",";
							}
					}
				$tmp .= '},"isArrivedLimitTime":false}';
				echo $tmp;
				exit();
				//{"errno":0,"data":{"7":{"SysNo":7,"ShipTypeID":"7","ShipTypeName":"普通快递","ShipTypeDesc":"圆通快递，江浙沪地区效率高、质量好、费用低","PremiumRate":"0.050000","PremiumBase":1500,"FreeShipBase":0,"Status":1,"StatusQueryType":3,"StatusQueryUrl":"http:\/\/www.yto.net.cn?","IsOnlineShow":1,"ShippingId":7,"shippingPrice":1000,"subOrder":{"1":{"shippingPrice":1000}},"shippingPriceCut":0}},"isArrivedLimitTime":false}
			}else if($act=="getpaytypeofshipping"){
				$paybank = $db->getAll("select id,name,logo,detail from `qk_payment` where iStatus=1");
				$tmp = '{"errno":0,"data":{';
					$i = 0;
					foreach($paybank as $item){
						$tmp .= '"'.$item['id'].'":{"pay_type":'.$item['id'].',"PayTypeName":"'.$item['name'].'","IsNetBank":0,"IsNet":1,"PayTypeDesc":"'.$item['detail'].'","OrderNumber":"01","needPrcdFee":0,"logo":"'.$item['logo'].'"}';
						$i++;
						if($i<count($paybank)){
							$tmp .= ",";
						}
					}
				$tmp .= '}}';
				exit($tmp);
			}else if($act=="getcoupon"){
				$um = new UserModel();
				$coupon = $um->getCoupon($userId);
				if(is_array($coupon) && count($coupon)>0){
					$tmp = '{"errno":0,"data":[';
					$i =0;
					foreach($coupon as $item){
						if($item['endtime']==0){
							$endtime = "无限期";
						}else{
							$endtime = date("Y-m-d H:i:s",$item['endtime']+3600*24-1);
						}
						$tmp .= '{"code":"'.$item['number'].'","content":"'.$item['name'].'","endtime":"'.$endtime.'"}';
						$i++;
						if($i<count($coupon)){
							$tmp .= ',';
						}
					}
					$tmp .= ']}';
					exit($tmp);
				}else{
					exit('{"errno":0,"data":[]}');
				}
				
			}else if($act=="checkcoupon"){
				$um = new UserModel();
				$_POST['userId'] = $userId;
				$_POST['number']=$_POST['code'];
				$info = $um->checkCoupon($_POST);
				if(is_array($info) && count($info)>0){
					exit('{"errno":0,"data":{"number":"'.$info['number'].'","money":'.$info['money'].'}}');					
				}else{
					exit('{"errno":3,"data":"该优惠券在当前站点不存在，请检查您的优惠券输入是否有误及您输入的优惠券支持使用的站点。"}');
				}
			}
			exit('{"success":false,"message":"Param Error"}');
		}
		$id = getgpc("id");
	
		$act = getgpc("act");
		if(!$id){
			$id = $db->getOne("select id from qk_order where iStatus=0");
			$orderInfo = $om->getInfo($id);
			
			if($orderInfo['amount']==0 && $orderInfo['deliveryTypeId'] && $act=="confirm"){
				//echo $orderInfo['amount'];
				$orderInfo['amount'] = $om->getCartAmount($orderInfo['deliveryTypeId']);
				//echo $orderInfo['amount'];
			}
			
		}
		
		assign("id",$id);
		if(!$orderInfo['addrId']){
			$addrId = $db->getOne("select id from qk_user_addr where userId='$userId'");
			$orderInfo['addrId'] = $addrId;
		}
		//echo $id;exit;
		$goodsPrice = $om->getCartGoodsPrice();
		$orderInfo['goodsPrice'] = $goodsPrice;
		$orderInfo['tax'] = $om->getTax($id,$goodsPrice);
		$orderInfo['amount'] += $orderInfo['tax'];
		//echo $orderInfo['amount']."&".$orderInfo['tax'];exit;
		//echo $orderInfo['tax'];exit;
		assign("orderInfo",$orderInfo);

		$sql = "select * from qk_paytype where parentId=0";
		$paytype = $db->getAll($sql);
		assign("paytype",$paytype);

		$sql = "select * from qk_invoicetype";
		$invoicetype = $db->getAll($sql);
		assign("invoicetype",$invoicetype);

		$sql = "select * from qk_invoice_content where iStatus=1 order by sortId asc,id asc";
		$invoiceContent = $db->getAll($sql);
		assign("invoiceContent",$invoiceContent);

		$pageInfo['title'] = "确认订单 - ".$GLOBALS['siteConf']['siteName'];
		assign("pageInfo",$pageInfo);

		display("purchase/order");
	}

	function prize(){
		BaseAction::checkLogin();
		global $db;
		$userId = $_SESSION['userId'];
		$id = getgpc("id");
		if($id && settype($id,"integer")){
			$sql = "select eventGoodsId from qk_user_prize where id='$id'";
			$eventGoodsId = $db->getOne($sql);
			$sql = "select goodsId from qk_event_goods where id='$eventGoodsId'";
			$goodsId = $db->getOne($sql);
			
		}
		display("purchase/prize");
	}
}
?>
