<%@LANGUAGE="VBSCRIPT" CODEPAGE="936"%>
<%option explicit%>
<!--#include file="../Conn.asp"-->
<!--#include file="../KS_Cls/Kesion.MemberCls.asp"-->
<!--#include file="../KS_Cls/Kesion.Label.CommonCls.asp"-->
<%

Dim KSCls
Set KSCls = New ShoppingCart
KSCls.Kesion()
Set KSCls = Nothing

Class ShoppingCart
        Private KS, KSRFObj,KSUser,DomainStr
		Private ProductList,TotalPrice
		Private Sub Class_Initialize()
		  Set KS=New PublicCls
		  DomainStr=KS.GetDomain
		  Set KSUser = New UserCls
		  Set KSRFObj = New Refresh
		End Sub
        Private Sub Class_Terminate()
		 Call CloseConn()
		 Set KS=Nothing
		 Set KSUser=Nothing
		End Sub
		%>
		<!--#include file="PackCart.asp"-->
		<%
		Public Sub Kesion()
		  Dim FileContent,Products,i,RS,strsql,CartStr,OrderAutoID
		      ProductList = KS.FilterIDs(Session("ProductList"))
              If ProductList="" and GetPackage(false)="" Then Response.Write "<script>alert('您的购物车中没有商品！');top.location.href='/';</script>":response.end
			  If KS.S("Action")<>"Confirm" Then  Response.Write "<script>alert('非法提供!');window.close();</script>":response.end
			 
			    '入订单
				 '生成订单号
				 Dim OrderID:OrderID=KS.Setting(71) & Year(Now)&right("0"&Month(Now),2)&right("0"&Day(Now),2)&KS.MakeRandom(8)
			     Dim ContactMan:ContactMan=Session("Payment_ContactMan")
				 Dim Address:Address=Session("Payment_Address")
				 Dim ZipCode:ZipCode=Session("Payment_ZipCode")
				 Dim Phone:Phone=Session("Payment_Phone")
				 Dim Email:Email=Session("Payment_Email")
				 Dim Mobile:Mobile=Session("Payment_Mobile")
				 Dim QQ:QQ=Session("Payment_QQ")
				 Dim PaymentType:PaymentType=Session("Payment_PaymentType")
				 Dim DeliverType:DeliverType=Session("Payment_DeliverType")
				 Dim InvoiceContent:InvoiceContent=Session("Payment_InvoiceContent")
				 Dim NeedInvoice:NeedInvoice=KS.ChkClng(Session("Payment_NeedInvoice"))
				 Dim Remark:Remark=Session("Payment_Remark")
                 Dim RSA,RealPrice,MoneyGoods,RealMoneyTotal,CouponID,CouponUserID,CouponNum,FaceValue,MaxDiscount,availablemoney
				
				  AvailableMoney=0 : MaxDiscount=0
				  
				If ContactMan="" Then Response.Write "<script>alert('您的购物车中没有商品,本次交易失败!');window.close();</script>":response.end
				
				 CouponNum=KS.S("CouponNum")
				 Set RS=Server.CreateObject("ADODB.RecordSet") 
				 If CouponNum<>"" and Cbool(KSUser.UserLoginChecked)=true Then
				  RS.Open "Select top 1 * From KS_ShopCouponUser Where CouponNum='" & CouponNum & "'",conn,1,3
				  If RS.Eof And RS.Bof Then
				    RS.Close:Set RS=Nothing
					Response.Write "<script>alert('对不起,您输入的优惠券不可用!');history.back();</script>"
					Exit Sub
				  Else
				     If RS("UseFlag")=1 and RS("AvailableMoney")<=0 Then
					   RS.Close:Set RS=Nothing
					   Response.Write "<script>alert('对不起,该优惠券的可抵扣金额已用完!');history.back();</script>"
					   Exit Sub
					 ElseIf Cbool(KSUser.UserLoginChecked)=false Then
					   RS.Close:Set RS=Nothing
					   Response.Write "<script>alert('对不起,必须登录后才可以使用优惠券!');history.back();</script>"
					   Exit Sub
					 Else  
					   'RS("UserName")=KSUser.UserName
					   'RS.Update
					   CouponID=KS.ChkClng(RS("CouponID"))
					 End If
				  End If
				   RS.Close 
				 End If
				
				 
				 If CouponID="" Or CouponID=0 Then
				   CouponID=KS.ChkClng(KS.S("Couponid"))
				 End If
				 
				
				 
				 If CouponID<>0 and Cbool(KSUser.UserLoginChecked)=true Then
				  If KS.ChkClng(KS.S("Couponid"))=0 And CouponNum<>"" Then
				  RS.Open "Select A.*,b.id as CouponUserID,b.AvailableMoney From KS_ShopCoupon A Inner Join KS_ShopCouponUser B ON A.ID=B.CouponID Where B.CouponNum='" & CouponNum & "'",conn,1,1
				  Else
				  RS.Open "Select A.*,b.id as CouponUserID,b.AvailableMoney From KS_ShopCoupon A Inner Join KS_ShopCouponUser B ON A.ID=B.CouponID Where B.ID=" &KS.ChkClng(KS.S("Couponid")) ,conn,1,1
				  End If
				  If Not RS.Eof Then
				     If DateDiff("s",RS("BeginDate"),Now)<0 Then
					  RS.Close:Set RS=Nothing
		              Response.Write "对不起,您输入的优惠券需要" & RS("BeginDate") & "后才能使用!"
					  Exit Sub
				     ElseIf DateDiff("s",RS("EndDate"),Now)>0 Then
					  RS.Close:Set RS=Nothing
					  Response.Write "<script>alert('对不起,您输入的优惠券已过期!');history.back();</script>"
					  Exit Sub
					 ElseIf RS("Status")=0 Then
					  RS.Close:Set RS=Nothing
					  Response.Write "<script>alert('对不起,您输入的优惠券已锁定!');history.back();</script>"
					  Exit Sub
					 ElseIf KS.S("TRealTotalPrice")<RS("MinAmount") Then
					  RS.Close:Set RS=Nothing
					  Response.Write "<script>alert('对不起,该优惠券要求订单金额必须大于等于 ￥" & RS("MinAmout") & " 元才可以抵用!');history.back();</script>"
					  Exit Sub
					 ElseIf RS("AvailableMoney")<=0 Then
					  RS.Close:Set RS=Nothing
					  Response.Write "<script>alert('对不起,该优惠券已全部抵用完了,不能再使用!');history.back();</script>"
					  Exit Sub
					 Else
					   MaxDiscount=RS("maxdiscount")
					   AvailableMoney=RS("AvailableMoney")
					   FaceValue=RS("FaceValue") 
					   CouponUserID=RS("CouponUserID")
					   CouponID=RS("ID")
					 End If
				  End If
				  RS.Close
				 End If
				 
				 
				 
			 If Not KS.IsNul(ProductList) Then 
				   RS.Open "select I.* ,L.LimitBuyBeginTime,L.LimitBuyEndTime,L.ID as TaskID from Product I Left Join KS_ShopLimitBuy L On I.LimitBuyTaskID=L.Id where I.ID in ("&ProductList&") order by I.ID",Conn,1,1
					 Do While Not RS.eof
					   Set RSA=Server.CreateObject("ADODB.RecordSet")
					   RSA.Open "select top 1 * from KS_OrderItem where ID is null",Conn,1,3
					   RSA.AddNew
						 RSA("OrderID")=OrderID
						 RSA("ProID")=RS("ID")
						 RSA("SaleType")=RS("ProductType")
						 RSA("Price_Original")=RS("Price_Original")
						 RSA("Price")=RS("Price")
						 If Trim(RS("ID"))=trim(Session("ChangeBuyID")) Then
						 RSA("IsChangedBuy")=1
						 Else
						 RSA("IsChangedBuy")=0
						 End If
					     If RS("IsLimitBuy")="1" And Now>RS("LimitBuyBeginTime") And RS("LimitBuyEndTime")>Now And RS("LimitBuyAmount")>0 Then
						 RSA("LimitBuyTaskID")=rs("taskid")
						 RSA("IsLimitBuy")=1
						 ElseIf RS("IsLimitBuy")="2" And RS("LimitBuyAmount")>0 Then
						 RSA("LimitBuyTaskID")=rs("taskid")
						 RSA("IsLimitBuy")=2
						 Else
						 RSA("LimitBuyTaskID")=0
						 RSA("IsLimitBuy")=0
						 End If
						 
						 
						If Trim(RS("ID"))=trim(Session("ChangeBuyID")) Then
						   RealPrice=Session("ChangeBuyPrice")														
					   ElseIf RS("IsLimitBuy")="1" And Now>RS("LimitBuyBeginTime") And RS("LimitBuyEndTime")>Now And RS("LimitBuyAmount")>0 Then
						   RealPrice=RS("LimitBuyPrice")
					   ElseIf RS("IsLimitBuy")="2" And RS("LimitBuyAmount")>0 Then
						   RealPrice=RS("LimitBuyPrice")
   
						ElseIF Cbool(KSUser.UserLoginChecked)=true Then
						   If RS("GroupPrice")=0 Then
						   RealPrice=RS("Price_Member")
						  Else
						   Dim RSP:Set RSP=Conn.Execute("Select top 1 Price From KS_ProPrice Where GroupID=" & KSUser.GroupID & " And ProID=" & RS("ID"))
						   If RSP.Eof Then
							 RealPrice=RS("Price_Member")
						   Else
							 RealPrice=RSP(0)
						   End If
						   RSP.Close:Set RSP=Nothing
						  End If
						Else
						  RealPrice=RS("Price")
						End If
						 RSA("RealPrice")=RealPrice
						 RSA("Amount")=KS.ChkClng(Session("Amount"&RS("ID")))
						 RSA("AttributeCart")=Session("AttributeCart"&RS("ID"))
						 RSA("TotalPrice")=Round(RealPrice*Session("Amount"&RS("ID")),2)
						 RSA("BeginDate")=Now
						 RSA("ServiceTerm")=RS("ServiceTerm")
						 RSA("PackID")=0
						 RSA("BundleSaleProID")=0
					   RSA.Update
					   RSA.Close:Set RSA=Nothing
					   MoneyGoods=MoneyGoods+Round(RealPrice*Session("Amount"&RS("ID")),2)

						 '扣除供抢购数
						 Conn.Execute("Update Product Set LimitBuyAmount=LimitBuyAmount-" & Session("Amount"&RS("ID"))& " Where id=" & RS("ID"))
						 Conn.Execute("Update Product Set LimitBuyAmount=0 Where id=" & RS("ID") & " and LimitBuyAmount<0")
						 
						 '将捆绑促销的抢购商品加入KS_OrderItem表
						 Dim RSK:Set RSK=Conn.Execute("Select I.ID,I.Title,I.ServiceTerm,I.Price_Original,I.Price,b.Price as realprice,b.amount,b.AttributeCart From Product I inner Join KS_ShopBundleSelect b on i.id=b.pid Where B.ProID=" & RS("ID") & " and b.username='" & GetUserID & "' order by I.id")
						 Do While Not RSK.Eof
						   	   Set RSA=Server.CreateObject("ADODB.RecordSet")
							   RSA.Open "select top 1 * from KS_OrderItem where ID is null",Conn,1,3
							   RSA.AddNew
								 RSA("OrderID")=OrderID
								 RSA("ProID")=RSK("ID")
								 RSA("SaleType")=6       '捆绑销售的商品
								 RSA("Price_Original")=RSK("Price_Original")
								 RSA("Price")=RSK("Price")
								 RSA("IsChangedBuy")=0
								 RSA("LimitBuyTaskID")=0
								 RSA("IsLimitBuy")=0
								 RSA("RealPrice")=RSK("RealPrice")
								 RSA("Amount")=RSK("Amount")
								 RSA("AttributeCart")=RSK("AttributeCart")
								 RSA("TotalPrice")=Round(RSK("RealPrice")*RSK("Amount"),2)
								 RSA("BeginDate")=Now
								 RSA("ServiceTerm")=RSK("ServiceTerm")
								 RSA("PackID")=0
								 RSA("BundleSaleProID")=RS("ID")
							   RSA.Update

								 moneyGoods=MoneyGoods + Round(RSK("RealPrice")*RSK("Amount"),2)

						       RSA.Close:Set RSA=Nothing
						 RSK.MoveNext
						 Loop
						 RSK.Close:Set RSK=Nothing
						 
						
						
						Session("Amount"&RS("ID"))=""

					  RS.MoveNext
					 Loop
				  RS.Close:Set RS=Nothing
			 End If 
			  
			 '====================================将礼包内的商品加入到orderitem表===========================================
			 Set RS=Server.CreateObject("ADODB.RECORDSET")
			 RS.Open "Select a.title,a.GroupPrice,a.Price_Original,a.Price_Member,a.Price,b.* From Product A inner join KS_ShopPackageSelect b on a.id=b.proid Where b.UserName='" & GetUserID & "'",Conn,1,1
				 Do While Not RS.Eof
				 	  Set RSA=Server.CreateObject("ADODB.RecordSet")
					   RSA.Open "select top 1 * from KS_OrderItem where ID is null",Conn,1,3
					   RSA.AddNew
						 RSA("OrderID")=OrderID
						 RSA("ProID")=RS("ProID")
						 RSA("SaleType")=5
						 RSA("PackID")=rs("packid")
						 RSA("Price_Original")=RS("Price_Original")
						 RSA("Price")=RS("Price")
						 RSA("IsChangedBuy")=0
						 
						IF Cbool(KSUser.UserLoginChecked)=true Then
						   If RS("GroupPrice")=0 Then
						   RealPrice=RS("Price_Member")
						  Else
						   Set RSP=Conn.Execute("Select top 1 Price From KS_ProPrice Where GroupID=" & KSUser.GroupID & " And ProID=" & RS("ID"))
						   If RSP.Eof Then
							 RealPrice=RS("Price_Member")
						   Else
							 RealPrice=RSP(0)
						   End If
						   RSP.Close:Set RSP=Nothing
						  End If
						Else
						  RealPrice=RS("Price")
						End If
						 RealPrice=RealPrice * Conn.Execute("Select top 1 discount From KS_ShopPackage Where ID=" & RS("PackID"))(0)/10
						 RSA("RealPrice")=RealPrice
						 RSA("Amount")=RS("Amount")
						 RSA("AttributeCart")=RS("AttributeCart")
						 RSA("TotalPrice")=Round(RealPrice*RS("Amount"),2)
						 RSA("BeginDate")=Now
						 RSA("ServiceTerm")=0
						 RSA("BundleSaleProID")=0
					   RSA.Update
					   RSA.Close:Set RSA=Nothing
					   MoneyGoods=MoneyGoods+Round(RealPrice*RS("Amount"),2)
				  RS.MoveNext
				 Loop
				 RS.Close
				 '删除礼包订购表数据
				 Conn.Execute("Delete From KS_ShopPackageSelect Where UserName='" & GetUserID &"'")
				 '删除捆绑促销订购表数
				 Conn.Execute("Delete From KS_ShopBundleSelect Where UserName='" & GetUserID &"'")

			  
				
	             '实际支付金额。
				 Dim PaymentDiscount:PayMentDiscount=KS.ReturnPayment(PaymentType,1)
				 Dim DeliveryMoney:DeliveryMoney=Session("DeliveryMoney")
				 If Not IsNumeric(DeliveryMoney) Then DeliveryMoney=0
				 Dim ToCity:ToCity=Session("ToCity")
				 Dim TaxRate:TaxRate=KS.Setting(65)
				 Dim IncludeTax:IncludeTax=KS.Setting(64)
				 Dim TaxMoney,UserName,NoUseCouponMoney
				 If IncludeTax=1 Or NeedInvoice=0 Then TaxMoney=1 Else TaxMoney=1+Taxrate/100
				 '总金额 = (总价*付费方式折扣+运费)*(1+税率)
				 RealMoneyTotal=Round((MoneyGoods*PayMentDiscount/100+DeliveryMoney)*TaxMoney,2)
				 
				 NoUseCouponMoney=RealMoneyTotal
				 If FaceValue>0 And AvailableMoney<>0 Then
				    If MaxDiscount>0 Then
					 dim allowmoney:allowmoney=round(RealMoneyTotal)* (maxdiscount/100) '按百分比得可抵扣金额
					  if (allowmoney>availablemoney) then
						 allowmoney=availablemoney
					  end if
					  FaceValue=allowmoney
					End If
				    RealMoneyTotal=Round(RealMoneyTotal-FaceValue,2)
				 End If

			   RS.Open "Select top 1 * From KS_Order",Conn,1,3
			   RS.AddNew
			     RS("OrderID")=OrderID
				 If Cbool(KSUser.UserLoginChecked)=true Then
				  UserName= KSUser.UserName
				 Else
				  UserName = "游客"
				 End If
				RS("UserName") = UserName
				RS("MoneyTotal")=RealMoneyTotal
				RS("MoneyGoods")=MoneyGoods
				RS("NoUseCouponMoney")=NoUseCouponMoney
				RS("NeedInvoice")=NeedInvoice
				RS("InvoiceContent")=InvoiceContent
				RS("Remark")=Remark
				RS("InputTime")=Now
				RS("ContactMan")=ContactMan
				RS("Address")=Address
				RS("ZipCode")=ZipCode
                RS("Mobile")=Mobile
				RS("Phone")=Phone
				RS("QQ")=QQ
				RS("Email")=Email
				RS("PaymentType")=KS.ChkClng(PaymentType)
				RS("DeliverType")=KS.ChkClng(DeliverType)
                RS("Discount_Payment")=PaymentDiscount   '付款方式折扣率
				RS("Charge_Deliver")=DeliveryMoney     '运费
				RS("ToCity")=ToCity '送达城市
				If IsNumeric(Session("Weight")) Then
				 RS("Weight")=Session("Weight")
				Else
				 RS("Weight")=0
				End If
				RS("CouponUserID")=KS.ChkClng(CouponUserID)               '优惠券使用人ID
				RS("UseCouponMoney")=FaceValue            '使用的抵扣金额
				RS("PayTime")="2000-1-1"   '表示未付款

				'相关初始值
				RS("Invoiced")=0       '发票未开
				RS("MoneyReceipt")=0   '已收款
				RS("BeginDate")=Now    '开始服务日期
				RS("Status")=0         '订单状态
				RS("DeliverStatus")=0  '送货状态
				RS("PresentMoney")=0       '返回客户现金
				RS("PresentPoint")=0       '返回客户点券
				RS("PresentScore")=0       '返回客户积分
			  RS.Update
			  RS.MoveLast
			  OrderAutoID=RS("id")
			  RS.Close
			  
			  If KS.ChkClng(CouponUserID)<>0 and facevalue>0 Then
			   RS.Open "Select top 1 * From KS_ShopCouponUser WHERE ID=" & KS.ChkClng(CouponUserID),conn,1,3
			   If Not RS.Eof Then
			       RS("UseFlag")=1
				   RS("UserName")=UserName
				   RS("UseTime")=Now
				   RS("OrderID")=OrderID
				   If KS.IsNul(RS("Note")) Then
				     RS("Note")="于[" & Now & "]在订单[" & OrderID & "]中抵扣了" & formatnumber(Round(FaceValue,2),2,-1) & "元;"
				   Else
				     RS("Note")=rs("Note") & "<br/>于[" & Now & "]在订单[" & OrderID & "]中抵扣了" & formatnumber(Round(FaceValue,2),2,-1) & "元;"
				   End If
				   RS("AvailableMoney")=RS("AvailableMoney")-facevalue
				   If RS("AvailableMoney")<0 Then RS("AvailableMoney")=0
				   RS.Update 
			   End If
			   RS.Close
			   'Conn.Execute("Update KS_ShopCouponUser Set AvailableMoney=AvailableMoney-" & facevalue &",UseFlag=1,UserName='" & UserName & "',UseTime=" & SQLNowString & ",OrderID='" & OrderID & "' Where id=" & KS.ChkClng(CouponUserID)) 
			  End If
			  Set RS=Nothing
			  
			  Session("ProductList")=""  '交易成功！置购物车参数为空
			  
		           If KS.Setting(124)="" Then Response.Write "请先到""基本信息设置->模板绑定""进行模板绑定操作!":response.end
				   FileContent = KSRFObj.LoadTemplate(KS.Setting(124))
				   FCls.RefreshType = "ShoppingSuccess" '设置刷新类型，以便取得当前位置导航等
				   FCls.RefreshFolderID = "0"        '设置当前刷新目录ID 为"0" 以取得通用标签
				 If Trim(FileContent) = "" Then FileContent = "商城订单提交成功页模板不存在!"
				 
				 '得到支付平台
				 If Instr(FileContent,"{$PayMentList}")<>0 Then
					   Dim SQL,K,Param,PayStr
					   Set RS=Server.CreateOBject("ADODB.RECORDSET")
					   RS.Open "Select ID,PlatName,Note,IsDefault From KS_PaymentPlat Where IsDisabled=1 Order By OrderID",conn,1,1
					   If Not RS.Eof Then SQL=RS.GetRows(-1)
					   RS.Close:Set RS=Nothing
					   If Not IsArray(SQL) Then
						PayStr=""
					   Else
					     PayStr="<form name=""myform"" id=""myform"" method=""get"" action=""payonline.asp"" target=""_blank"">"
						 PayStr=PayStr & "<input type=""hidden"" name=""id"" value=""" & OrderAutoID & """/>"
						 For K=0 To Ubound(SQL,2)
						   PayStr=PayStr & "<input type='radio' value='" & SQL(0,K) & "' name='PaymentPlat'"
						   If trim(SQL(3,K))="1" Then PayStr=PayStr &  " checked"
						   PayStr=PayStr &  ">"& SQL(1,K) & "(" & SQL(2,K) &")<br>"
						 Next
					   End If
					   PayStr=PayStr & "<input type=""submit"" style=""padding:2px"" value="" 进入支付平台全额付款 "" />"
					   
					   If KS.Setting(82)<>"0" And IsNumeric(KS.Setting(82)) Then  '如果是允许支付定金，则跳至会员中心
					   PayStr=PayStr & "<input type=""button"" onclick=""location.href='../user/user_PayOnline.asp?Action=Payonline&ID=" & OrderAutoID & "&PaymentPlat='+$('input[name=PaymentPlat][checked]').val();"" style=""padding:2px"" value="" 进入会员中心支付定金 "" />"
					   End If
					   PayStr=PayStr & "</form>"
					  FileContent=Replace(FileContent,"{$PayMentList}",PayStr) 
				 End If
				 
				 
                 FileContent=Replace(FileContent,"{$ShowOrderID}",OrderID)
			     FileContent=Replace(FileContent,"{$ShowOrderAutoID}",OrderAutoID)
			     FileContent=Replace(FileContent,"{$ShowTotalMoney}",FormatNumber(RealMoneyTotal,2,-1))
			     FileContent=KSRFObj.KSLabelReplaceAll(FileContent)
                 KS.Echo FileContent
       End Sub
	   
End Class
%>
