<!DOCTYPE html>
<html>

	<head>
		<meta charset="utf-8">
		<meta name="viewport" content="width=device-width, initial-scale=1,maximum-scale=1, user-scalable=no">
		<meta name="apple-mobile-web-app-capable" content="yes">
		<meta name="apple-mobile-web-app-status-bar-style" content="black">
		<title>结算</title>
		<link rel="stylesheet" type="text/css" href="css/mui.min.css" />
		<link rel="stylesheet" type="text/css" href="css/iconfont.css" />
		<link rel="stylesheet" type="text/css" href="css/main.css" />
		<script type="text/javascript">
			// 屏蔽分享
			window.hiddenAllWechatMenu = true;
		</script>
	</head>

	<body>
		<div class="mui-content" style="padding-bottom: 56px;">
			<div class="address-cantainner">
				<ul class="mui-table-view mui-table-view-striped my-grid-view-no mui-table-view-condensed">
					<li class="mui-table-view-cell">
						<div class="mui-table">
							<!--没有选地址时显示的div-->
							<div class="mui-table-cell mui-col-xs-12 table-middle btn-add-address">
								<div class="add-address"><span class="iconfont icon-jia"></span>添加收货地址</div>
							</div>

							<!--选择微信地址后显示的div-->
							<div id="user-address-div" style="display: none;">
								<!--<div class="mui-table-cell mui-col-xs-1 mui-text-left table-middle">
								<p><span class="iconfont icon-dingwei"></span></p>
							</div>
							<div class="mui-table-cell mui-col-xs-10 mui-text-left table-middle">
								<div>收货人:林笑笑 <span class="mui-pull-right">16899996678</span></div>
								<p>收货地址:广东省深圳市福田区莲花街道深圳特区 报业大厦12b</p>
							</div>
							<div class="mui-table-cell mui-col-xs-1 mui-text-right table-middle">
								<p><span class="mui-icon mui-icon-arrowright"></span></p>
							</div>-->
							</div>
						</div>
					</li>
				</ul>
			</div>
			<div class="clearing-box">
				<ul class="mui-table-view mui-table-view-striped my-grid-view-no mui-table-view-condensed shopping-cart-list">

				</ul>
				<ul class="mui-table-view">
					<li class="mui-table-view-cell" id="ul-youhuiquan" style="padding-left:7px;display: none;">
						<a class="mui-navigate-right btn-youhuiquan">
							现金券<span class="mui-pull-right cl-red">未选择现金券</span>
						</a>
					</li>
					<li>
						<div class="mui-input-row">
							<label class="lbl-remarks">订单备注</label>
							<input class="ipt-remarks" id="textarea" type="text" placeholder="选填:您对订单有特殊要求,可以在此备注">
						</div>
					</li>
				</ul>
				<div class="mui-content-padded mui-text-right">合计:<span class="pro-price">¥<span class="count_price">0.0</span></span>
				</div>
			</div>

			<div class="buy-footer1">
				<table class="tb-clearing">
					<tr>
						<td class="quanxuan">
							共<span id="pro-count" class="cl-red">0</span>件商品
						</td>
						<td class="mui-text-center">需支付:<span class="count_price_box">¥<span class="pay_price">0.0</span></span>
						</td>
						<td>
							<a id="go-pay" class="mui-btn mui-pull-right add_gwc go-clearing">立即支付</a>
						</td>
					</tr>
				</table>
			</div>
		</div>
		<!-- 加载ing begin-->
		<div class="loading covers">
			<div class="loading-bj"></div>
			<p>正在加载...</p>
		</div>
		<!-- 加载ing end -->
		<script src="js/mui.min.js"></script>
		<script src="js/jquery-2.1.1.min.js"></script>
		<script src="js/main.js"></script>
		<script src="js/wechat-utils-1.0.js"></script>
		<script>
			window.addEventListener('pageshow', function(e) {
				// 通过persisted属性判断是否存在 BF Cache
				if(e.persisted) {
					location.reload();
				}
			});

			var userIntegral = 0; // 用户可用积分
			var meonyProportion = 0; // 兑换比例:1个积分=?分钱
			var payTotal = 0.0; // 支付总金额
			var userInputIntegral = 0; // 抵扣积分
			var isPay = true; // 是否在请求支付,false表示正在请求,true可以请求
			var cartIdStr = ""; // 购物车ID
			var usePayMoney = 0;
			var ipt_balance = 0;
			var yhq_val = 0;
			var used_balance = 0;
			var yhq_type = 1;
			var yhq_id = '';
			mui.ready(function() {
				var parameter = {}; //ajax参数json集合
				var cartidList = '';
				if(!window.sessionStorage) {
					mui.alert("您的浏览器不支持sessionStorage");
				} else {
					//读取上一个页面带过来的sessionStorage
					pay_data = JSON.parse(sessionStorage.getItem('pay_data'));
					if(pay_data != null) {
						cartidList = pay_data.text[0]; //购物项id集合
						parameter["cartIds"] = cartidList;
						$.ajax(base_path + '/wechat/order/payBefore', {
							data: parameter,
							dataType: 'json',
							type: 'get',
							xhrFields: {
								withCredentials: true
							},
							crossDomain: true,
							timeout: 15000,
							success: function(dt) {
								if(dt.isRedirect) {
									location.href = dt.redirectURL;
								} else {
									if(dt.status == true) {
										// 购物项遍历
										console.log(dt)
										var liNote = "";
										var yhq_str = "";
										if(dt.data.couponItems.length > 0) {
											$("#ul-youhuiquan").show();
											var str = '';
											mui.each(dt.data.couponItems, function() {
												str += '<li class="my-table-view-cell" style="opacity:.5;margin:20px 0;"><div class="mui-table"><div class="mui-table-cell table-middle mui-col-xs-11">现金券:¥' + ((this.couponReduce) / 100).toFixed(2) + '<h6>有效期至:' + this.couponUseEndDate + '</h6></div><div class="mui-table-cell table-middle mui-col-xs-1"><input name="radio" type="radio" class="mui-pull-left" val="' + (this.couponReduce / 100).toFixed(2) + '" couponid="' + this.couponItemId + '"/></div></div></li>';
											});
											str += '<li class="my-table-view-cell" style="opacity:.5;margin:20px 0;"><div class="mui-table"><div class="mui-table-cell table-middle mui-col-xs-11">不使用现金券<h6></h6></div><div class="mui-table-cell table-middle mui-col-xs-1"><input name="radio" type="radio" class="mui-pull-left"/></div></div></li>';
											$("body").append('<div class="my-picker"><ul class="mui-table-view mui-table-view-striped mui-table-view-condensed my-grid-view-no" style="padding: 25px 15px; overflow: scroll;max-height: 420px;">' + str + '</ul><button class="mui-btn my-btn-block my-btn-user-know" disabled="disabled">确认</button><span class="iconfont icon-guanbi"></span></div>');
										}
										var proCount = 0;
										mui.each(dt.data.cartItems, function(index) {
											var num = this.cartNum;
											proCount += num;
											var total = (num * this.productPrice / 100).toFixed(2); //购物车小计,单位分,保留两位小数
											var productId = this.cartProductId;
											liNote += '<div class="mui-table"><div class="mui-table-cell mui-col-xs-5"><img class="mui-media-object wh-100" src="' + this.productIntroduceImg + '"></div><div class="mui-table-cell table-middle mui-col-xs-7" style="line-height:2.5">' + this.productName + '<h6>颜色:' + this.productColor + '<span class="center">数量:' + num + '</span></h6><div>单价¥' + (this.productPrice / 100).toFixed(2) + '</div></div></div>';
										});
										var $productListUl = $(".shopping-cart-list");
										$productListUl.empty();
										$productListUl.append(liNote);
										// 保存数据
										payTotal = dt.data.payTotal; // 支付金额,单位分

										cartIdStr = dt.data.cartId; // 购物车ID

										//默认自己拉出地址
										if(dt.data.addressInfo != undefined && dt.data.addressInfo != null) {
											$(".btn-add-address").hide();
											$("#user-address-div").html('<div class="mui-table"><div class="mui-table-cell mui-col-xs-1 mui-text-left table-middle"><p><span class="iconfont icon-dingwei"></span></p></div><div class="mui-table-cell mui-col-xs-10 mui-text-left table-middle"><div>收货人:' + dt.data.addressInfo.salesAddressName + ' <span class="mui-pull-right">' + dt.data.addressInfo.salesAddressTel + '</span></div><p>收货地址:' + dt.data.addressInfo.salesAddressInfo + '</p></div><div class="mui-table-cell mui-col-xs-1 mui-text-right table-middle"><p><span class="mui-icon mui-icon-arrowright"></span></p></div></div>').show();
											//给微信参数赋值
											wechatAddr.status = true;
											wechatAddr.detailInfo = dt.data.addressInfo.salesAddressInfo;
											wechatAddr.userName = dt.data.addressInfo.salesAddressName;
											wechatAddr.userTel = dt.data.addressInfo.salesAddressTel;
											wechatAddr.postalCode = dt.data.addressInfo.salesAddressPostnum;
										}else{
											wechatAddr.status = false;
										}
										$(".count_price,.pay_price").text((dt.data.payTotal / 100).toFixed(2));
										$("#pro-count").text(proCount);
										$(".loading").hide().css("opacity", "0"); //隐藏(正在加载...)
									} else {
										mui.alert("获取数据失败!", function() {
											location.href = "shopping-cart.html";
										});
									}
								}
							},
							error: function(xhr, type, errorThrown) {
								console.log(xhr);
								mui.alert("获取数据失败,网络错误!")
							}
						});
					} else {
						mui.alert("sessionStorage异常!", function() {
							location.href = "index.html";
						})
					}
				}
				//				var str = "";
				//				for(i = 0; i < 3; i++) {
				//					str += '<div class="mui-table"><div class="mui-table-cell mui-col-xs-5"><img class="mui-media-object wh-100" src="images/pro-bai.png"></div><div class="mui-table-cell table-middle mui-col-xs-7" style="line-height:2.5">柔性声波牙刷<h6>颜色:极光白<span class="center">数量:2</span></h6><div>¥2999.00</div></div></div>';
				//				}
				//				document.querySelector('.shopping-cart-list').innerHTML = str;

			});

			//callback为用户点击蒙版时自动执行的回调;
			var mask = mui.createMask(function() {
				$(".my-picker").removeClass("active"); //隐藏弹窗
			});
			//现金券弹窗
			$(document).on('tap', '.btn-youhuiquan', function() {
				mask.show();
				//				if($(".my-picker").length==0){
				//				var li = '<li class="my-table-view-cell" style="opacity:.5;margin:20px 0;"><div class="mui-table"><div class="mui-table-cell table-middle mui-col-xs-11">现金券:¥99.9<h6>有效期至:2017-12-12</h6></div><div class="mui-table-cell table-middle mui-col-xs-1"><input name="radio" type="radio" class="mui-pull-left" /></div></div></li>';
				//				var str = '';
				//				for(i = 0; i < 17; i++) {
				//					str += li;
				//				}
				//				$("body").append('<div class="my-picker"><ul class="mui-table-view mui-table-view-striped mui-table-view-condensed my-grid-view-no" style="padding: 25px 15px; overflow: scroll;max-height: 420px;">' + str + '</ul><button class="mui-btn my-btn-block my-btn-user-know" disabled="disabled">确认使用</button><span class="iconfont icon-guanbi"></span></div>');
				//				}
				//				setTimeout(function() {
				if($(".my-picker").length > 0) {
					$(".my-picker").addClass("active");
				}
				//				}, 500);
			});
			//确认使用
			$(document).on('tap', '.my-btn-user-know', function() {
				console.log("确认使用");
				if(typeof($(".my-picker input[name=radio]:checked").attr("couponid")) != "undefined") {
					$(".btn-youhuiquan").attr("couponid", $(".my-picker input[name=radio]:checked").attr("couponid"));
					yhq_id = $(".my-picker input[name=radio]:checked").attr("couponid");
					$(".btn-youhuiquan span").text("-¥" + $(".my-picker input[name=radio]:checked").attr("val"));
					var price = accSub($(".count_price").text(), $(".my-picker input[name=radio]:checked").attr("val"));
					if(price <= 0) {
						price = 0.0; //判断商品价格减去现金券价格若<0 则显示0
					}
					$(".pay_price").text(parseInt(price).toFixed(2));
				} else {
					yhq_id = '';
					$(".btn-youhuiquan").removeAttr("couponid");
					$(".btn-youhuiquan span").text("不使用现金券");
					$(".pay_price").text($(".count_price").text());
				}
				$(".my-picker").removeClass("active"); //隐藏弹窗
				$(".mui-backdrop").remove(); //移除遮罩层
			});
			//单选事件
			$(document).on('tap', '.my-picker .my-table-view-cell', function() {
				$(this).find("input[name=radio]").prop("checked", true);
				$(this).css("opacity", "1");
				$(this).siblings().css("opacity", ".5");
				$(".my-btn-user-know").removeAttr("disabled").addClass("active");
			});
			//关闭弹窗
			$(document).on('tap', '.icon-guanbi', function() {
				$(".mui-backdrop").remove(); //移除遮罩层
				$(".my-picker").removeClass("active"); //隐藏弹窗
			});
			// 获取微信共享地址
			$(document).on('tap', '.btn-add-address,#user-address-div', function() {
				editAddrV1(
					function(res) {
						// 用户成功拉出地址 
						var address = res.provinceName + "-" + res.cityName + "-" + res.countryName + "-" + res.detailInfo;
						wechatAddr.status = true;
						wechatAddr.detailInfo = address;
						wechatAddr.postalCode = res.postalCode;
						wechatAddr.userName = res.userName;
						wechatAddr.userTel = res.telNumber;
						wechatAddr.nationalCode = res.nationalCode;
						$(".btn-add-address").hide();
						$("#user-address-div").html('<div class="mui-table"><div class="mui-table-cell mui-col-xs-1 mui-text-left table-middle"><p><span class="iconfont icon-dingwei"></span></p></div><div class="mui-table-cell mui-col-xs-10 mui-text-left table-middle"><div>收货人:' + wechatAddr.userName + ' <span class="mui-pull-right">' + wechatAddr.userTel + '</span></div><p>收货地址:' + wechatAddr.detailInfo + '</p></div><div class="mui-table-cell mui-col-xs-1 mui-text-right table-middle"><p><span class="mui-icon mui-icon-arrowright"></span></p></div></div>').show();
					},
					function() {
						if($('#user-address-div').html() != null && $('#user-address-div').html() != '') {
							wechatAddr.status = true;
						} else {
							wechatAddr.status = false;
							// 用户取消拉出地址
							mui.alert("您没有选择收货地址!");
						}
					}
				);
			});
			// 去支付
			$(document).on('tap', '#go-pay', function() {

				var remark = $("#textarea").val();
				
				var ch_en_num = /^[A-Za-z0-9 _\[\]\【\】\{\}\{\}\(\)\(\)\《\》\<\>\,\,\.\。\、\!\!\~\·\@\#\¥\$\%\^\…\&\—\:\:\;\;\‘\’\'\'\"\"\“\”\?\?\-\=\|\*\+\-\u4e00-\u9fa5]{0,100}$/;
				if(ch_en_num.test(remark)) {
					console.log("备注验证通过")
				} else {
					mui.alert("备注格式错误!仅支持中/英文,数字,普通符号");
					return false;
				}
				if(wechatAddr.status) {
					if($('#user-address-div').html() == null || $('#user-address-div').html() == '') {
						wechatAddr.status = false;
						mui.toast("请选择收货信息!");
						return ;
					} 
					
					if(isPay) {
						isPay = false; // 锁定请求按钮
						/* 组装数据 */
						var dataArgs = {
							"orderAddressInfo": wechatAddr.detailInfo,
							"orderAddressPostNum": wechatAddr.postalCode,
							"orderAddressMoblie": wechatAddr.userTel,
							"orderAddressName": wechatAddr.userName,
							"cartIdStr": cartIdStr
						};
						if(yhq_id != '') {
							dataArgs["couponId"] = yhq_id;
						}
						if(remark != '') {
							dataArgs["orderUserRemark"] = remark;
						}
						
						$.ajax(base_path + '/wechat/order/pay', { // 提交订单,准备支付
							data: dataArgs,
							dataType: 'json',
							type: 'post',
							xhrFields: {
								withCredentials: true
							},
							crossDomain: true,
							timeout: 15000,
							success: function(dt) {
								//						layer.closeAll();
								//mui.alert(dt.resultCode=="500");
								if(dt.resultCode == "500") {
									mui.alert(dt.message);
									isPay = true;
									return;
								};
								if(dt.data.info == "isOK") {
									location.href = 'pay-win.html?orderId=' + dt.data.orderId + "&dates=" + new Date().getTime()
									return;
								};
								if(dt.status) {
									var str = dt.data.info;
									var obj = JSON.parse("{" + str + "}");
									WeixinJSBridge.invoke('getBrandWCPayRequest', obj, function(res) {
										if(res.err_msg == 'get_brand_wcpay_request:ok') {
											$.ajax(base_path + '/wechat/order/checkOrderPaySuccess?dates=' + new Date().getTime(), {
												data: {
													"orderId": dt.data.orderId
												},
												dataType: 'json',
												xhrFields: {
													withCredentials: true
												},
												crossDomain: true,
												type: 'get',
												timeout: 15000,
												success: function(dataobj) {
													if(dataobj.isRedirect) {
														location.href = dataobj.redirectURL;
													} else {
														if(dataobj.status == true) { // 支付成功
															location.href = "pay-win.html?orderId=" + dataobj.data + "&dates=" + new Date().getTime();
														} else {
															location.href = "order-details.html?orderId=" + dataobj.data + "&dates=" + new Date().getTime(); // 前往订单详情
														}
													}
												},
												error: function(xhr, type, errorThrown) {
													console.log(xhr);
												}
											});
										} else {
											isPay = true;
											mui.alert("对不起,支付失败!请稍后重试!" + dt.data.orderId + "支付失败!", function() {
												location.href = "order-details.html?orderId=" + dt.data.orderId + "&dates=" + new Date().getTime(); // 前往订单详情
											});
										}
									});
								} else {
									isPay = true;
									mui.alert(dt.message);
									location.href = "order-details.html?orderId=" + dt.data.orderId + "&dates=" + new Date().getTime(); // 前往订单详情
								}
							},
							error: function(xhr, type, errorThrown) {
								isPay = true;
								//						layer.closeAll();
								mui.alert("您的网络异常,请刷新重试!");
								return;
							}
						});
					} else {
						mui.alert("正在请求支付中~~请稍后!");
						return;
					}
				} else {
					mui.alert("请选择收货地址!");
					return;
				}
			});
		</script>
	</body>

</html>