<?php
 /**
 *      [XCECP] (C) Colorful Network Inc.
 *      This is NOT a freeware, use is subject to license terms
 */

class OrderModel extends BaseModel{
	public $errString="";
	public $msg='';
	function getInfo($params){
		load_class("goods");
		$gm = new GoodsModel();
		if(!is_array($params)){
			if(!$params || !settype($params,"integer")){return false;}
			$wheres = " and id='$params'";
		}else{
			if(!$params['id'] && !$params['outTradeNo']){return false;}
			if($params['id'] && settype($params['id'],"integer")){$wheres .= " and id='".$params['id']."'";}
			if($params['outTradeNo']){$wheres .= " and outTradeNo='".$params['outTradeNo']."'";}
			if($params['userId'] && settype($params['userId'],"integer")){$wheres .= " and userId='".$params['userId']."'";}

		}
		$sql = "select * from qk_order where 1=1 $wheres";
		$info = $this->db->getRow($sql);
		$info['userInfo'] = $this->db->getRow("select * from qk_user where id='".$info['userId']."'");
		$info['goods'] = $GLOBALS['db']->getAll("select order.id,order.goodsId,order.pnum,order.prizeId,order.spec,goods.name,order.price,order.remark,order.point,order.appraise,order.appraisetime,order.posttime from qk_order_goods as `order` left join qk_goods as goods on order.goodsId=goods.id where order.orderId='".$info['id']."'");
		$g=0;
		$info['goodsAmount']=0;
		//print_R($info['goods']);
		foreach($info['goods'] as $item){
			$info['goods'][$g]['goodsInfo'] = $gm->getInfo($item['goodsId']);
			$info['goods'][$g]['price'] = sprintf("%01.2f",$item['price']);
			$info['goodsAmount']+=sprintf("%01.2f",$item['price']*$item['pnum']);
			$g++;
		}
		
		unset($g);
		$info['status'] = $GLOBALS['db']->getOne("select name from qk_order_status where id='".$info['iStatus']."'");
		$info['payStatus'] = $GLOBALS['db']->getOne("select name from qk_order_status where id='".$info['payStatusId']."'");
		$info['paytypeId'] = $GLOBALS['db']->getOne("select typeId from qk_payment where id='".$info['paymentId']."'");
		$info['delivery'] = $GLOBALS['db']->getOne("select name from qk_delivery where id='".$info['deliveryTypeId']."'");
		$info['deliveryTypeName'] = $GLOBALS['db']->getOne("select name from qk_delivery_type where id='".$info['deliveryTypeId']."'");
		$info['invoicetype'] = $GLOBALS['db']->getOne("select name from qk_invoicetype where id='".$info['invoicetypeId']."'");
		$info['invoiceContent'] = $GLOBALS['db']->getOne("select name from qk_invoice_content where id='".$info['invoiceContentId']."'");
		$info['paymentName'] = $GLOBALS['db']->getOne("select name from qk_payment where id='".$info['paymentId']."'");
		$info['couponMoney'] = $GLOBALS['db']->getOne("select money from qk_user_coupon where orderId='".$info['id']."'");
		//echo $info['couponMoney'];exit;
		if(!$info['couponMoney']){$info['couponMoney']=0;}
		$info['amount'] = sprintf("%01.2f",$info['amount']);
		$info['finance'] = $this->db->getAll("select * from `qk_finance` where orderId='".$info['id']."' and iStatus=1 and typeId=2");
		$info['financeAmount']=0;$info['financeAmount'] = $this->db->getOne("select sum(amount) from `qk_finance` where orderId='".$info['id']."' and iStatus=1 and typeId=2");
		$info['amountNow'] = 0;
		$info['divide']=array();

		if($info['divideNum']>1){
			if($info['goodsAmount']<=4000){
				$shou=0.3;$dai=0.7;
			}else{
				$shou=0.5;$dai=0.5;
			}
			$info['divideAmount'] = $info['goodsAmount']*$dai;	//总贷款额度
			$info['divideMoney'] = decimalTwo($info['divideAmount']/$info['divideNum'])+decimalTwo($info['divideAmount']*0.008);	//总贷款额度/分期数(本金) + 每期需还利息
			
			$info['amountNow'] = decimalTwo($info['goodsAmount']*$shou)+$info['deliveryPrice']-$info['couponMoney'];	//首付 + 物流费用 - 优惠券
			//echo $info['amountNow'];exit;
			//$info['amount'] = $info['divideMoney']*$info['divideNum'] + $info['amountNow'];
			$info['divide'][0]['amount'] = $info['amountNow'];// decimalTwo($info['goodsAmount']*$shou);
			$info['downAmount'] = decimalTwo($info['goodsAmount']*$shou);
			$info['interestAmount'] = decimalTwo($info['divideAmount']*0.008)*$info['divideNum'];
			$info['interestAmount'] = $info['divideMoney']*$info['divideNum'] - $info['divideAmount'];

			if($info['financeAmount'] + $info['divide'][0]['amount']>0){//如果已付款金额小于首付金额 即第一次付款未结束
				$info['amountNow'] = $info['amountNow']+$info['financeAmount'];	//每期还金额=总额度/分期数 + 每期利息
			}else{
				//首付结束 其余为每期需还金额
				$info['amountNow'] = $info['divideMoney'];
			}
			$info['divide'][0]['time'] = $this->db->getOne("select posttime from qk_finance where orderId='".$info['id']."' and iStatus=1 and typeId=2 order by id asc");
			if(!$info['divide'][0]['time']){$info['payStatusId']=4; }
			$day=date("j",$info['divide'][0]['time']);
			
			if($day<=10){
				$info['divide'][1]['time'] = strtotime(date("Y-m-20 23:59:59",$info['divide'][0]['time']));
			}else{
				$info['divide'][1]['time'] = strtotime("+1 month",strtotime(date("Y-m-20 23:59:59",$info['divide'][0]['time'])));
			}
			$finance = $this->db->getOne("select sum(amount) from qk_finance where orderId='".$info['id']."' and iStatus=1 and typeId=2 and posttime<=".$info['divide'][1]['time']);
			//echo $finance;
			$info['divide'][1]['iStatus'] = ($finance+$info['divideMoney']*2+$info['deliveryPrice'])<=0?1:0;
			//print_r(date("Y-m-d",$info['divide'][0]['time']));exit;
			//print_r($info['divide'][1]['iStatus']);exit;
			$info['divide'][1]['amount']=$info['divideMoney'];
			if($info['payStatusId']=='5' || $info['payStatusId']=='21' || $info['payStatusId']=='22'){ $info['divide'][0]['iStatus']=1; }

			for($num=2;$num<=$info['divideNum'];$num++){
				$info['divide'][$num]['time']=strtotime("+".($num-1)." month",$info['divide'][1]['time']);
				$info['divide'][$num]['amount']=$info['divideMoney'];
				$finance = $this->db->getOne("select sum(amount) from qk_finance where orderId='".$info['id']."' and iStatus=1 and typeId=2 and posttime<=".$info['divide'][$num]['time']);
				$info['divide'][$num]['iStatus'] = ($finance+$info['divideMoney']*($num+1)+$info['deliveryPrice'])<=0?1:2;
			}
		}else{
			$info['divideAmount']=0;
			if($info['payStatusId']==4){
				$info['amountNow'] = $info['amount'];
			}
		}

		return $info;
	}

	function confirm($params){
		$id = $params["id"];
		$addrId = $params["addrId"];
		$paymentId = $params["payType"];
		$remark = $params["remark"];
		if($id && settype($id,"integer") && $addrId && $paymentId){
			$sql = "update qk_order set addrId = '$addrId',paymentId='$paymentId',remark='$remark' where id='$id'";
			if($this->db->query($sql)){
				return true;
			}
		}
		return false;
	}

	function finish($params){
		global $_G;
		$userId = $_SESSION["userId"];
		$id = $params["id"];
		$addrId = $params["addrId"];
		$remark = $params["remark"];
		$uid = $params['uid'];
		$aid = $params['aid'];
		$receiver = $params['receiver'];
		$receiveAddrId = $params['receiveAddrId'];
		$receiveAddrDetail = $params['receiveAddrDetail'];
		$receiverTel = $params['receiverTel'];
		$receiverMobile = $params['receiverMobile'];
		$zipCode = $params['zipCode'];
		$shipType = $params['shipType'];
		$sign_by_other = $params['sign_by_other'];
		$Price = $params['Price'];
		$payType = $params['payType'];
		$point = $params['point'];
		$shippingPrice = $params['shippingPrice'];
		$couponCode = str_replace('-','',$params['couponCode']);
		$comment = $params['comment'];
		$suborders = $params['suborders'];
		$divideTypeId = $params['divideTypeId'];if(!$divideTypeId || !is_numeric($divideTypeId)){$divideTypeId=1;}
		$divideNum = $params['divideNum'];if(!$divideNum || !is_numeric($divideNum)){$divideNum=0;}
		$scorePrice = 0;
		load_class("user");
		$um = new UserModel();
		$userInfo = $um->getInfo($userId);
		$userScore = $userInfo['score'];
		$pm = new PurchaseModel();
		$cartInfo = $pm->cartInfo();
		$scorePrice = $pm->cartInfoScorePrice($cartInfo);
		$score = $pm->cartInfoScore($cartInfo);
		//echo $scorePrice;exit;
		if($userScore < $scorePrice){
			exit('{"success":false,"message":"'.$_G['lang']['scoreInsufficient'].'","type":2}');		
		}
		//优惠券
		$couponId = 0;
		$couponMoney = 0;
		if($couponCode){
			$couponInfo = $um->checkCoupon(array("userId"=>$userId,"number"=>$couponCode));
			if(!$couponInfo){ $this->msg='优惠券'+$couponCode+'不可用';return false; }
			$couponId = $couponInfo['couponId'];
			if(!$couponInfo['money']){
					exit('{"success":false,"message":"'.$_G['lang']['couponExpired'].'","type":2}');			
			}else{
				$couponMoney = $couponInfo['money'];
			}
		}
		//优惠券 End

		load_class("delivery");
		$dm = new DeliveryModel();
		
		if(!$cartInfo || count($cartInfo)==0){
				exit('{"success":false,"message":"Cart Empty","type":2,"errno":6002,"data":{"errCode":-100,"errMsg":"'.$_G['lang']['order']['cartEmpty'].'"}}');
				return false;
		}

		$id = $this->db->getOne("select id from qk_order where userId='$userId' and iStatus=0");
		if(!$id || !settype($id,"integer")){
			$sql = "insert into qk_order set iStatus=0,userId='$userId',posttime=UNIX_TIMESTAMP()";
			if($this->db->query($sql)){
				$id = $this->db->insert_id();
			}else{
				return false;
			}
		}
		$deliveryTypeId  = $shipType;
		$paymentId = $payType;
		$remark = $comment;
		$deliveryPrice = 0;
		$score = 0;
		$virtual = true;
		if($id && settype($id,"integer") && $paymentId){
			$sql = "update qk_order set addrId = '$addrId',paymentId='$paymentId',remark='$remark',deliveryTypeId='$deliveryTypeId'";
			$sql .= ",receiver='$receiver',receiveAddrId='$receiveAddrId',address='$receiveAddrDetail',phone='$receiverTel',mobile='$receiverMobile'";
			$sql .= ",zipCode='$zipCode'";
			$sql .= " where id='$id'";
			if($this->db->query($sql)){
				$price = 0;
				$goodsPrice = 0;
				$weight = 0;
				$orderGoodsAddSql = array();
				$deleteCartSql = array();
				$addSalesSql = array();
				$inventoryCheckSuccess = true;
				foreach($cartInfo as $item){
					if($item['goodsInfo']['freeDelivery']!=1){
						$weight += $item['goodsInfo']['weight'];
						$virtual = false;
					}
					settype($item['priceNow'],"float");
					settype($item['pnum'],"integer");
					if($item['goodsInfo']['buyWay']!=2){
						$price += $item['priceNow']*$item['pnum'];
					}
					$score += $item['goodsInfo']['score']*$item['pnum'];
					if($item['prizePrice']){$price -= $item['prizePrice'];}
					$inventory = $this->db->getOne("select inventory from `qk_goods` where id='".$item['goodsId']."'");
					if(!$inventory || !is_numeric($inventory) || $inventory<1 || $inventory<$pnum){
						$this->msg = '商品'.$item['goodsInfo']['name'].'库存已不足';
						$inventoryCheckSuccess=false;
						break;
					}else{
						$orderGoodsAddSql[] = "insert into qk_order_goods set userId='$userId',orderId='$id',goodsId='".$item['goodsId']."',pnum='".$item['pnum']."',price='".$item['priceNow']."',prizeId='".$item['prizeId']."',spec='".$item['spec']."',remark='".$item['remark']."',posttime=UNIX_TIMESTAMP();";
						$addSalesSql[] = "update qk_goods set sales=sales+'".$item['pnum']."' where id='".$item['goodsId']."';";
						$deleteCartSql[] ="delete from qk_shoppingcart where userId='$userId' and id='".$item['id']."'";
						$inventorySql[] = "update qk_goods set inventory=inventory-'".$item['pnum']."' where id='".$item['goodsId']."';";
					}
				}
				if(!$inventoryCheckSuccess){return false;}
				foreach($orderGoodsAddSql as $key=>$sql){
					$this->db->query($sql);$this->db->query($deleteCartSql[$key]);$this->db->query($addSalesSql[$key]);$this->db->query($inventorySql[$key]);
				}
				$goodsPrice = $price;

				//Process user address
				$sql = "select * from qk_user_addr where id='$addrId'";
				$addr = $this->db->getRow($sql);
				if($addr){
					$sql = "update qk_order set firstName='".$addr['firstName']."',lastName='".$addr['lastName']."',comName='".$addr['comName']."',address='".$addr['address']."'";
					$sql .=",suburb='".$addr['suburb']."',city='".$addr['city']."',province='".$addr['province']."',country='".$addr['country'].",district='".$addr['district']."''";
					if($addr['zipCode']){
						$sql .= ",zipCode='".$addr['zipCode']."'";
					}
					$sql .= " where id='$id'";
					$this->db->query($sql);
				}
				//tax fee start
				$tax = 0;
				$sql = "select zipCode from qk_order where id='$id'";
				$zipCode = $this->db->getOne($sql);
				if($zipCode !== false && $zipCode){
					$sql = "select taxRate from qk_region where zipCode='$zipCode'";
					$taxRate = $this->db->getOne($sql);
					if($taxRate!==false && settype($taxRate,"float") && $taxRate>0){
						$tax = $price*$taxRate;
					}
				}
				//fax fee end

				$deliveryPrice = $dm->getPrice($weight,$deliveryTypeId);
				if($virtual){$deliveryPrice=0;}
				
				//echo($amount);exit;
				//用户积分查询及扣除
				if($scorePrice){
					$sql = "select id from qk_user_score where iStatus=1 and typeId=2 and userId='$userId' and orderId='$id'";
					$scoreId = $this->db->getOne($sql);
					if($scoreId){
						$sql = "update qk_user_score set score='-$scorePrcie' where id='$scoreId'";
					}else{
						$sql = "insert into qk_user_score set userId='$userId',orderId='$id',score='-$scorePrice',iStatus=1,typeId=2,remark='订单 ".$id." 支出',posttime=UNIX_TIMESTAMP()";
					}
					$this->db->query($sql);
				}
				//用户积分查询及扣除 End

				//用户购买所得积分计算
				if($score){$this->score($id);}
				//用户购买所得积分计算 End
				$payStatusId = 4;
				//echo $deliveryPrice;
				if($divideNum>1 && $divideNum<13){
					if($goodsPrice<=3000){$shou=0.3;$dai=0.7;}else{$shou=0.5;$dai=0.5;}
					$divideMoney = decimalTwo($goodsPrice*$dai*0.008) + decimalTwo($goodsPrice*$dai/$divideNum);
					$amount = decimalTwo($goodsPrice*$shou)+$divideMoney*$divideNum+$deliveryPrice;
				}else{
					$amount = $goodsPrice + $tax + $deliveryPrice;
				}
				//echo decimalTwo($amount);exit;

				if($couponMoney && intval($couponMoney)){
					$amount = $amount-$couponMoney;
					if($price<0)$price=0;
					$sql = "update qk_user_coupon set iStatus=0,orderId='$id',useoftime=UNIX_TIMESTAMP(),ip='".getIp()."' where number='$couponCode'";
					$this->db->query($sql);
				}

				$sql = "update qk_order set amount='$amount',tax='$tax',iStatus=3,payStatusId='$payStatusId',couponCode='$couponCode',divideTypeId='$divideTypeId',divideNum='$divideNum',deliveryPrice='$deliveryPrice' where userId='$userId' and id='$id'";
				$this->db->query($sql);
				$creditLine = $this->db->getOne("select creditLine from `qk_user` where id='$userId'");
				settype($creditLine,'integer');
				if($creditLine==0){
					if($goodsPrice<=3000){
						$this->db->query("update qk_user set creditLine=3000 where id='$userId'");
					}else if($goodsPrice<=7000){
						$this->db->query("update qk_user set creditLine=7000 where id='$userId'");				
					}
				}
				return $id;
			}
		}
		return false;
	}
	function score($orderId){
		$orderInfo = $this->getInfo($orderId);
		$orderGoods = $orderInfo['goods'];
		foreach($orderGoods as $goods){
			$goodsInfo = $goods['goodsInfo'];//print_r($goods);exit;
			$name = $goodsInfo['name'];
			$score = $goodsInfo['score']*$goods['pnum'];
			$buyerId = $orderInfo['userId'];
			if($buyerId && $score){
				//取得订单中可以记积分的单件产品
				//echo $buyerId . $score;
				//计算消费积分
				$sql = "select id from qk_user_score where orderId='".$orderId."' and goodsId='".$goodsInfo['id']."'";
				$scoreNum = $this->db->getOne($sql);
				if(!$scoreNum){
				//	echo $scoreNum;
					$sellerId = $goodsInfo['userId'];
					$this->buyerScore($buyerId,1,$score,$goods,$orderInfo);
					$this->sellerScore($sellerId,1,$score,$goods,$orderInfo);
					$this->distributionScore($buyerId,1,$score,$goods,$orderInfo);
				}else{
					//echo '处理过该订单该商品的积分';
				}
			}
		}
		//print_r($orderInfo);
	}

	function distributionScore($userId,$level,$score,$goods,$orderInfo){
		$buyerId = $orderInfo['userId'];
		$orderId = $orderInfo['id'];
		$goodsInfo = $goods['goodsInfo'];
		$certNo = $orderInfo['userInfo']['certNo'];
		$remark = "本区域用户 ".$orderInfo['userInfo']['loginName']." 购买 ".$goodsInfo['name']." ".$goods['pnum']." 件";
		$district = $this->db->getRow("select * from qk_district where certNo='".substr($certNo,0,6)."'"); //print_r($district);
		if($district['parentCertNo'] && $district['parentId']!=0 && $district['level']==1){
			//县级区域分销
			$sql = "select * from qk_user where distributionGradeId=2 and distributionCountyId='".$district['id']."'";
			$countyUser = $this->db->getAll($sql);
			foreach($countyUser as $user){
				$addscore = $score*0.08;
				$sql = "insert into qk_user_score set userId='".$user['id']."',orderId='$orderId',goodsId='".$goodsInfo['id']."',score='$addscore',iStatus=0,typeId=1,remark='$remark',posttime=UNIX_TIMESTAMP()";
				//echo "县级分销".$sql.'<br/>';
				$this->db->query($sql);
			}
			//实体店
			$sql = "select * from qk_user where distributionGradeId=1 and distributionCountyId='".$district['id']."'";
			$countyUser = $this->db->getAll($sql);
			foreach($countyUser as $user){
				$addscore = $score*0.15;
				$sql = "insert into qk_user_score set userId='".$user['id']."',orderId='$orderId',goodsId='".$goodsInfo['id']."',score='$addscore',iStatus=0,typeId=1,remark='$remark',posttime=UNIX_TIMESTAMP()";
				//echo "实体店：".$sql.'<br/>';
				$this->db->query($sql);
			}
			$sql = "select * from qk_district where id='".$district['parentId']."'";
			$city = $this->db->getRow($sql);
		}
		//市级区域分销
		if($city['parentCertNo'] && $city['parentId']!=0 && $city['level']==2){
			$sql = "select * from qk_user where distributionGradeId=3 and distributionCityId='".$city['id']."'";
			$cityUser = $this->db->getAll($sql);
			foreach($cityUser as $user){
				$addscore = $score*0.05;
				$sql = "insert into qk_user_score set userId='".$user['id']."',orderId='$orderId',goodsId='".$goodsInfo['id']."',score='$addscore',iStatus=0,typeId=1,remark='$remark',posttime=UNIX_TIMESTAMP()";
				//echo "市级分销：".$sql.'<br/>';
				$this->db->query($sql);
			}
			$sql = "select * from qk_district where id='".$city['parentId']."'";
			$province = $this->db->getRow($sql);
		}
		//省级区域分销
		if($province['parentCertNo']==0 && $province['parentId']==0 && $province['level']==2){
			$sql = "select * from qk_user where distributionGradeId=4 and distributionProvinceId='".$province['id']."'";
			$provinceUser = $this->db->getAll($sql);
			foreach($provinceUser as $user){
				$addscore = $score*0.03;
				$sql = "insert into qk_user_score set userId='".$user['id']."',orderId='$orderId',goodsId='".$goodsInfo['id']."',score='$addscore',iStatus=0,typeId=1,remark='$remark',posttime=UNIX_TIMESTAMP()";
				//echo "省级分销：".$sql.'<br/>';
				$this->db->query($sql);
			}
		}
	}

	function buyerScore($userId,$level,$score,$goods,$orderInfo){
		$buyerId = $orderInfo['userId'];
		$orderId = $orderInfo['id'];
		$goodsInfo = $goods['goodsInfo'];
		$remark = '';
		$remarkGoods = "购买商品 ".$goodsInfo['name']." ".$goods['pnum']." 件";
		if($level==1){
			$remark .= $remarkGoods;
		}else{		
			$remark .= "下级用户 ".$orderInfo['userInfo']['loginName'].' '.$remarkGoods;
		}
		$proportion = 0;
		switch($level){
			case 1:
				$proportion = 0.15;break;
			case 2:
				$proportion = 0.10;break;
			case 3:
				$proportion = 0.06;break;
			case 4:
				$proportion = 0.03;break;
			case 5:
				$proportion = 0.01;break;
			case 6:
				$proportion = 0.01;break;
			case 7:
				$proportion = 0.01;break;
			case 8:
				$proportion = 0.01;break;
		}
		$addscore = $score*$proportion;
		$sql = "insert into qk_user_score set userId='$userId',orderId='$orderId',goodsId='".$goodsInfo['id']."',score='$addscore',iStatus=0,typeId=1,remark='$remark',posttime=UNIX_TIMESTAMP()";
		//echo $sql."<br/>";
		$this->db->query($sql);	//添加积分 默认不生效 将订单设置为完成后生效
		$inviterId = $this->db->getOne("select inviterId from qk_user where id='$userId'");
		if($inviterId){
			if($level<8){
				$this->buyerScore($inviterId,$level+1,$score,$goods,$orderInfo);
			}
		}
	}

	function sellerScore($userId,$level,$score,$goods,$orderInfo){
		$buyerId = $orderInfo['userId'];
		$orderId = $orderInfo['id'];
		$goodsInfo = $goods['goodsInfo'];
		$remark = '';
		$remarkGoods = "推荐商品 ".$goodsInfo['name']." 被购买 ".$goods['pnum']." 件";
		if($level==1){
			$remark .= $remarkGoods;
		}else{		
			$remark .= "下级用户 ".$goods['goodsInfo']['userInfo']['loginName'].' '.$remarkGoods;
		}
		$proportion = 0;
		switch($level){
			case 1:
				$proportion = 0.03;break;
			case 2:
				$proportion = 0.02;break;
			case 3:
				$proportion = 0.01;break;
			case 4:
				$proportion = 0.01;break;
			case 5:
				$proportion = 0.01;break;
			case 6:
				$proportion = 0.01;break;
			case 7:
				$proportion = 0.01;break;
		}
		$addscore = $score*$proportion;
		$sql = "insert into qk_user_score set userId='$userId',orderId='$orderId',goodsId='".$goodsInfo['id']."',score='$addscore',iStatus=0,typeId=1,remark='$remark',posttime=UNIX_TIMESTAMP()";
		//echo $sql."<br/>";
		$this->db->query($sql);	//添加积分 默认不生效 将订单设置为完成后生效
		$inviterId = $this->db->getOne("select inviterId from qk_user where id='$userId'");
		if($inviterId){
			if($level<7){
				$this->sellerScore($inviterId,$level+1,$score,$goods,$orderInfo);
			}
		}
	}


	function addScore($userId,$level,$score,$orderId){
		$remark = "订单".$orderId."收入";
		if($level>1){$remark = "下级用户".$remark;}
		$proportion = 1;
		switch($level){
			case 1:
				$proportion = 0.15;break;
			case 2:
				$proportion = 0.10;break;
			case 3:
				$proportion = 0.06;break;
			case 4:
				$proportion = 0.03;break;
			case 5:
				$proportion = 0.01;break;
			case 6:
				$proportion = 0.01;break;
			case 7:
				$proportion = 0.01;break;
			case 8:
				$proportion = 0.01;break;
		}
		$score = $score*$proportion;
		$score = sprintf("%.2f",$score);
		$sql = "insert into qk_user_score set userId='$userId',orderId='$orderId',score='$score',iStatus=0,typeId=1,remark='$remark',posttime=UNIX_TIMESTAMP()";
		$this->db->query($sql);
		$inviterId = $this->db->getOne("select inviterId from qk_user where id='$userId'");
		if($inviterId){
			//$sqlScoreParent = "insert into qk_user_score set userId='$parentId',orderId='$id',score='$score',iStatus=0,typeId=1,remark='下级用户订单".$id."收入',posttime=UNIX_TIMESTAMP()";
			//$this->db->query($sqlScoreParent);
			if($level<8){
				$this->addScore($inviterId,$level+1,$score,$orderId);
			}
		}
	}

	function getCartAmount($deliveryTypeId){
		if($deliveryTypeId){
			$userId = $_SESSION['userId'];
				$sql = "select cart.*,goods.price,goods.weight,goods.freeDelivery from qk_shoppingcart as cart  left join qk_goods as goods on cart.goodsId=goods.id where cart.userId='$userId' or sessionId='".session_id()."' order by id desc";
				$cartInfo = $this->db->getAll($sql);
				if(!$cartInfo || count($cartInfo)==0){return 0;}
				$price = 0;
				$weight = 0;
				$prizePrice = 0;
				foreach($cartInfo as $item){
					settype($item['price'],"float");
					settype($item['pnum'],"integer");
					if($item['freeDelivery']!=1){ $weight += $item['weight']; }
					if($item['prizeId']){$prizePrice += $item['price'];}
					$price += $item['price']*$item['pnum'];
				}
				load_class("delivery");
				$dm = new DeliveryModel();
				$deliveryPrice = $dm->getPrice($weight,$deliveryTypeId);
				$amount = $price + $deliveryPrice - $prizePrice;
				return $amount;
		}
		return false;
	}

	function getCartGoodsPrice(){
			$userId = $_SESSION['userId'];
				$sql = "select cart.*,goods.price,goods.weight,goods.freeDelivery from qk_shoppingcart as cart  left join qk_goods as goods on cart.goodsId=goods.id where cart.userId='$userId' or sessionId='".session_id()."' order by id desc";
				$cartInfo = $this->db->getAll($sql);
				if(!$cartInfo || count($cartInfo)==0){return 0;}
				$price = 0;
				foreach($cartInfo as $item){
					settype($item['price'],"float");
					settype($item['pnum'],"integer");
					$price += $item['price']*$item['pnum'];
				}
				return $price;
		return 0;
	}

	function ajaxEditService($params){
		$id = $params['id'];
		$act = $params['act'];
		$col = $params['col'];
		$val = $params['val'];
		$oldval = $params['oldval'];
		if($id && is_numeric($id) && $col){
			$sql = "update `qk_order_service` set  $col='$val' where id='$id'";
			if($this->db->query($sql)){
				//saveLog("管理员 ".$_SESSION['adminId']." 修改退换货申请 $id 总金额 $oldval => $val");
				return true;
			}
		}
		return false;
	}
	function ajaxEdit($params){
		$id = $params['id'];
		$act = $params['act'];
		$col = $params['col'];
		$val = $params['val'];
		$oldval = $params['oldval'];
		if($id && is_numeric($id) && $col){
			$sql = "update `qk_order` set  $col='$val' where id='$id'";
			if($this->db->query($sql)){
				if($col=="amount"){
					saveLog("管理员 ".$_SESSION['adminId']." 修改订单 $id 总金额 $oldval => $val");
				}
				return true;
			}
		}
		return false;
	}
	function del($id){
		if($id && settype($id,"integer")){
			$sql = "delete from qk_order where id='$id'";
			if($this->db->query($sql)){
				$this->db->query("delete from qk_order_goods where orderId='$id'");
				return true;	
			}
		}
		return false;
	}
	function delService($id){
		if($id && settype($id,"integer")){
			$sql = "delete from qk_order_service where id='$id'";
			if($this->db->query($sql)){
				return true;	
			}
		}
		return false;
	}

	function getAllStatus(){
		$sql = "select * from qk_codemap where parentId=2 and iStatus=1";
		return $this->db->getAll($sql);
	}

	function edit($params){
		$id = $params['id'];
		if($id && settype($id,"integer")){
			$iStatus = $params['iStatus'];
			$amount = $params['amount'];
			$receiver = $params['receiver'];
			$firstName = $params['firstName'];
			$lastName = $params['lastName'];
			$address = $params['address'];
			$zipCode = $params['zipCode'];
			$receiverMobile = $params['receiverMobile'];
			$receiverTel = $params['receiverTel'];
			$remark = $params['remark'];
			$paymentId = $params['paymentId'];
			$payStatusId = $params['payStatusId'];
			$phone = $params['phone'];
			$mobile = $params['mobile'];
			$deliveryNumber = $params['deliveryNumber'];
			$sql = "update qk_order set amount='$amount',address='$address',zipCode='$zipCode',receiver='$receiver',receiverMobile='$receiverMobile',receiverTel='$receiverTel',remark='$remark',iStatus='$iStatus'";
			if($paymentId && is_numeric($paymentId)){
				$sql.=",paymentId='$paymentId'";
			}
			$sql .=",phone='$phone',mobile='$mobile',deliveryNumber='$deliveryNumber',payStatusId='$payStatusId' where id='$id'";
			if($this->db->query($sql)){
				if($iStatus==20){
					$sqlScore = "update qk_user_score set iStatus=1 where typeId=1 and orderId='$id'";
				}else{
					$sqlScore = "update qk_user_score set iStatus=0 where typeId=1 and orderId='$id'";
				}
				$this->db->query($sqlScore);
				return true;
			}
		}
		return false;
	}

	function ship($params){
		$id = $params['id'];
		$deliveryRemark = $params['deliveryRemark'];
		if($id && settype($id,"integer")){
			$deliveryNumber = $params['deliveryNumber'];
			load_class("order");
			$order = new OrderModel();
			$orderInfo = $order->getInfo($id);
			if($orderInfo['iStatus']==6){ $this->msg='该订单已经发货'; return false; }
			$sql = "update qk_order set deliveryNumber='$deliveryNumber',deliveryRemark='$deliveryRemark',iStatus=6 where id='$id'";
			if($this->db->query($sql)){
				$this->msg='订单发货成功';
				return true;
			}
		}
		$this->msg='订单发货失败';
		return false;
	}

	function addGoods($params){
		$orderId = $params['orderId'];
		$goodsId = $params['goodsId'];
		$pnum = $params['pnum'];
		if($orderId && $goodsId && $pnum && settype($orderId,"integer") && settype($goodsId,"integer") && settype($pnum,"integer")){
			$sql = "select userId from qk_order where id='$orderId'";
			$userId = $this->db->getOne($sql);
			if($userId===false){
				return '{"success":false,"message":"Order Error"}';
			}
			if($pnum==0){
				$msg = '{"success":false,"message":"Buy Num Error"}';		
			}else{
				$sql = "select price,name from qk_goods where id='".$goodsId."'";
				$goodsInfo = $this->db->getRow($sql);
				if($goodsInfo===false){
					$msg = '{"success":false,"message":"该商品不存在"}';
				}else{
					$price = $goodsInfo['price'];
					$name = $goodsInfo['name'];
					$sql = "select id from qk_order_goods where goodsId='$goodsId' and orderId='$orderId'";
					$id = $this->db->getOne($sql);
					if($id){
						return '{"success":false,"message":"Goods Exists"}';
					}
					$sql = "insert into qk_order_goods set orderId='$orderId',goodsId='$goodsId',pnum='$pnum',price='$price',posttime=UNIX_TIMESTAMP()";
					if($this->db->query($sql)){
						$id = $this->db->insert_id();
						$amount = $this->getAmount($orderId);
						$msg = '{"success":true,"message":"Success","data":{"name":"'.$name.'","price":"'.$price.'","id":"'.$id.'","amount":"'.$amount.'"}}';
					}else{
						$msg = '{"success":false,"message":"Add Error"}';
					}
				}
			}
			
		}else{
			$msg = '{"success":false,"message":"Params Error"}';
		}
		return $msg;
	}

	function editGoods($params){
		$c = true;
		$orderGoodsId = $params['orderGoodsId'];
		$pnum = $params['pnum'];
		if(!$orderGoodsId || !settype($orderGoodsId,"integer") || !$pnum || !settype($pnum,"integer")){ $msg='{"success":false,"message":"Params Error"}'; $c=false;}
		if($c){
			$orderId = $this->db->getOne("select orderId from qk_order_goods where id='$orderGoodsId'");
			$sql = "update qk_order_goods set pnum='$pnum' where id='$orderGoodsId'";
			if($this->db->query($sql)){
				$amount = $this->getAmount($orderId);
				$msg = '{"success":true,"message":"Success","data":{"pnum":"'.$pnum.'","amount":"'.sprintf("%.2f",$amount).'"}}';
			}
		}
		return $msg;
	}
	function getGoodsPrice($orderId){
		if(!$orderId){return 0;}
		$sql = "select * from qk_order_goods where orderId='$orderId'";
		$goods = $this->db->getAll($sql);
		//echo $orderId;print_r($goods);exit;
		$orderInfo = $this->getInfo($orderId);
		$goodsPrice = 0;
		foreach($orderInfo['goods'] as $goods){
			$pnum = $goods['pnum'];
			$price = $goods['price']*$pnum;
			$goodsPrice += $price;
		}
		return $goodsPrice;		
	}

	function getAmount($orderId){
		$sql = "select * from qk_order_goods where orderId='$orderId'";
		$goods = $this->db->getAll($sql);
		$orderInfo = $this->getInfo($orderId);
		$deliveryTypeId = $orderInfo['deliveryTypeId'];
		$weight = 0;
		$goodsPrice = 0;
		$prizePrice = 0;
		foreach($orderInfo['goods'] as $goods){
			if($goods['goodsInfo']['freeDelivery']!=1){
				$weight += $goods['goodsInfo']['weight'];
			}
			$pnum = $goods['pnum'];
			//if($goods['prizeId']){$pnum--;}
			$price = $goods['price']*$pnum;
			$goodsPrice += $price;
			$prizePrice += $goods['price'];
		}
		load_class("delivery");
		$dm = new DeliveryModel();
		$deliveryPrice = $dm->getPrice($weight,$deliveryTypeId);
		//echo $deliveryPrice;
		//echo $goodsPrice;
		//echo $prizePrice;
		$amount = $deliveryPrice + $goodsPrice - $prizePrice;
		$sql = "update qk_order set amount='$amount' where id='$orderId'";
		$this->db->query($sql);
		return $amount;
	}

	function addOrder($params){
		$loginName = $params['loginName'];
		$email = $params['email'];
		$deliveryTypeId = $params['deliveryTypeId'];
		if($deliveryTypeId && ($loginName || $email)){
			if($loginName){$userId = $this->db->getOne("select id from qk_user where loginName='$loginName'");}
			if($email){$userId = $this->db->getOne("select id from qk_user where email='$email'");}
			if($userId){
				$sql = "insert into qk_order set userId='$userId',deliveryTypeId='$deliveryTypeId',iStatus=4,posttime=UNIX_TIMESTAMP()";
				$this->db->query($sql);
				$orderId = $this->db->insert_id();
				$res = array("success"=>true,"message"=>"","data"=>array("orderId"=>$orderId));
			}else{
				$res = array("success"=>false,"message"=>"用户不存在");		
			}
		}else{
			$res = array("success"=>false,"message"=>"Params Error");
		}
		echo json_encode($res);
	}

	function getTax($orderId,$goodsPrice){
		//echo $goodsPrice;exit;
		if(!$goodsPrice){
			$goodsPrice = $this->getGoodsPrice($orderId);
		}
		//echo $goodsPrice;
				//tax fee start
				$tax = 0;
				$sql = "select zipCode from qk_order where id='$orderId'";
				$zipCode = $this->db->getOne($sql);
				if(!$zipCode){
					$userId = $_SESSION['userId'];
					$sql = "select zipCode from qk_user_addr where userId='$userId' order by `primary` desc,id desc";
					$zipCode = $this->db->getOne($sql);
				}
				//echo $zipCode;exit;
				if($zipCode !== false && $zipCode){
					$sql = "select taxRate from qk_region where zipCode='$zipCode'";
					$taxRate = $this->db->getOne($sql);
					if($taxRate!==false && settype($taxRate,"float") && $taxRate>0){
						$tax = $goodsPrice*$taxRate;
					}
				}
				//echo $tax;exit;
			return $tax;
				//fax fee end
	}
}
?>
