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;

mui.ready(function() {
	mui.ajax('/iamberry/wechat/order/payBefore', {
		dataType: 'json',
		type: 'POST',
		timeout: 15000,
		success: function(dt) {
			if(dt.status == true) {
				// 购物项遍历
				//console.log(dt)
				var liNote = "";
				if(dt.data.balance == 0) {
					$(".pay_ipt_box").hide();
				} else {
					used_balance = accDiv(dt.data.balance, 100);
					$('#used_balance').html("¥ " + accDiv(dt.data.balance, 100));
				}
				var yhq_str = "";
				if(dt.data.couponItems.length == 0) {
					$(".forward").hide();
				} else {
					$("#yhq_count").html(dt.data.couponItems.length);
					mui(dt.data.couponItems).each(function(index) {
						yhq_str += '<div class="mui-input-row mui-radio"><label>' + this.couponName + '</label><input name="radio1" value="' + accDiv(this.couponReduce, 100) + '" type="radio" id="' + this.couponItemId + '" yhq_type="' + this.couponType + '"></div>';
					});
					$(".my-popover").html(yhq_str + '<div class="mui-input-row mui-radio"><label>不使用优惠券</label><input name="radio1" value="1" type="radio"></div>');
				}
				for(var i = 0; i < dt.data.cartItems.length; i++) {
					var total = dt.data.cartItems[i].cartNum * dt.data.cartItems[i].productPrice / 100; // 购物车小计,分-->元
					var pro_color = switchcolor(dt.data.cartItems[i].productColor)
					total = total.toFixed(2); // 保留两位小数
					var productId = dt.data.cartItems[i].cartProductId;
					var price = dt.data.cartItems[i].productPrice;
					var num = dt.data.cartItems[i].cartNum;
					liNote = liNote +
						"<li class='mui-table-view-cell mui-media'>" +
						"<a>" +
						"<span class='mui-media-object mui-pull-left wh-100'> <img src='" + dt.data.cartItems[i].productIntroduceImg + "'></span>" +
						"<div class='mui-media-body'>" +
						"<div class='wt-space gwc_tit'>" + dt.data.cartItems[i].productName + "<span class='price_sp cl-gwc mui-pull-right' id='product-" + productId + "' price='" + price + "'>¥" + total + "</span></div>" +
						"<small class='gwc_pp'>颜色：" + pro_color + "</small>" +
						"<div class='mui-numbox'><button class='mui-btn mui-btn-numbox-minus' onclick='shoppSubEvent(" + productId + ")' type='button'>-</button>" +
						"<input class='mui-input-numbox' readonly='readonly' type='tel' id='shoppNum-" + productId + "' value='" + num + "'/>" +
						// "<span class='price cl-6'>x" + num + "</span>" +
						"<button class='mui-btn mui-btn-numbox-plus' onclick='shoppAddEvent(" + productId + ")' type='button'>+</button></div>" +
						"</div>" +
						"</a>" +
						"</li>";
				}
				var $productListUl = $("#products-list-ul");
				$productListUl.empty();
				$productListUl.append(liNote);
				dt.data.userIntegral = dt.data.userIntegral - 1;
				// 保存数据
				meonyProportion = dt.data.meonyProportion; // 兑换比例
				payTotal = dt.data.payTotal; // 支付金额,单位分
				userIntegral = dt.data.userIntegral; // 用户可用积分
				cartIdStr = dt.data.cartId; // 购物车ID

				// 替换数据
				usePayMoney = accDiv(dt.data.payTotal, 100);
				$("#user-integral-span").html(dt.data.userIntegral);
				$("#user-pay-money-span").html(usePayMoney + " 元");

				//默认自己拉出地址
				if(dt.data.addressInfo != undefined && dt.data.addressInfo != null) {
					$("#user-address-div").empty().append(
						"收货人：" + dt.data.addressInfo.salesAddressName + "<span class='ml-5'>" + dt.data.addressInfo.salesAddressTel + "</span>" +
						"<a>" +
						"<p class='shipping_address wt-space'>" + dt.data.addressInfo.salesAddressInfo + "<span class='mui-icon mui-icon-arrowright icon-r-c'></span></p>" +
						"</a>");
					$("#user-address-div").show();
					$("#open-wechat-addres-a").hide();
					//给微信参数赋值
					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 {
				mui.alert(dt.message);
			}
		},
		error: function(xhr, type, errorThrown) {
			errorfn(xhr);
		}
	});
	// 获取微信共享地址
	mui('body').on('tap', '#open-wechat-addres-a,#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;

				$("#user-address-div").empty().append(
					"收货人：" + wechatAddr.userName + "<span class='ml-5'>" + wechatAddr.userTel + "</span>" +
					"<a>" +
					"<p class='shipping_address wt-space'>" + wechatAddr.detailInfo + "<span class='mui-icon mui-icon-arrowright icon-r-c'></span></p>" +
					"</a>");
				$("#user-address-div").show();
				$("#open-wechat-addres-a").hide();
			},
			function() {
				if($('#user-address-div').html() != null && $('#user-address-div').html() != '') {
					wechatAddr.status = true;
				} else {
					wechatAddr.status = false;
					// 用户取消拉出地址
					mui.alert("您没有选择收货地址!");
				}
			}
		);

	});

	// 积分数量改变时
	mui('body').on('change', '#input-user-integral', function() {
		var inputUserIntegral = $("#input-user-integral").val();
		$.trim(inputUserIntegral);
		var r = /^[1-9]+\d*$/;
		if(!r.test(inputUserIntegral)) {
			$("#input-user-integral").val(userInputIntegral);
			return false;
		}
		inputUserIntegral = parseInt(inputUserIntegral);
		if(inputUserIntegral > userIntegral) {
			$("#input-user-integral").val(userInputIntegral);
			return false;
		}
		if((inputUserIntegral * meonyProportion) > payTotal) {
			$("#input-user-integral").val(userInputIntegral);
			return false;
		}
		// 置换数据
		userInputIntegral = inputUserIntegral;
		var temp = (userInputIntegral * meonyProportion / 100).toFixed(2);
		$("#integral-money-span").html(temp);
		temp = ((payTotal - (userInputIntegral * meonyProportion)) / 100).toFixed(2);
		$("#user-pay-money-span").html(temp);
	});
	// 去支付
	mui('body').on('tap', '.btn-weixin-pay', function() {
		var yhq_id = $("input[name=radio1]:checked").attr('id');
		if(yhq_id == undefined) {
			yhq_id = "";
		}
		var remark = $("#textarea").val();
		var pattern = new RegExp("[ `~!@#$^&*()=|{}':;'\\[\\]<>/?~！@#￥……&*（）——|{}【】‘；：”“'、？]")
		if(remark != "") {
			$.trim(remark);
			if(pattern.test(remark)) {
				mui.alert("请不要输入中文、字母、数字以外的特殊字符!");
				return;
			}
			if(!(remark.length >= 0 && remark.length <= 100)) {
				mui.alert("备注字数长度在0-100之间!");
				return;
			}
		}

		if(wechatAddr.status) {
			if(isPay) {

				isPay = false; // 锁定请求按钮
				layer.open({
					type: 2,
					shadeClose: false,
					content: "正在请求加载订单信息..."
				}); // 调用加载弹出层

				/* 组装数据 */
				var dataArgs = {
					"orderAddressInfo": wechatAddr.detailInfo,
					"orderAddressPostNum": wechatAddr.postalCode,
					"orderAddressMoblie": wechatAddr.userTel,
					"orderAddressName": wechatAddr.userName,
					"cartIdStr": cartIdStr,
					"orderIntegralNum": userInputIntegral,
					"orderUserRemark": remark,
					"couponId": yhq_id,
					"balancePayAmount": accMul(ipt_balance, 100)
				};

				mui.ajax('/iamberry/wechat/order/pay', { // 提交订单,准备支付
					data: dataArgs,
					dataType: 'json',
					type: 'POST',
					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") {
							mui.openWindow({

								url: domanUrl + "/iamberry/wechat/order/paySuccess?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') {
									var orderIds = {
										"orderId": dt.data.orderId
									};
									layer.open({
										type: 2,
										shadeClose: false,
										content: "正在请求加载订单信息..."
									}); // 调用加载弹出层
									var url = "/iamberry/wechat/order/checkOrderPaySuccess";
									$.getJSON(url, {
										"s": new Date().getTime(),
										"orderId": dt.data.orderId
									}, function(data) {
										if(data.status == true) { // 支付成功
											window.location.href = "/iamberry/wechat/order/paySuccess?orderId=" + orderIds.orderId + "&dates=" + new Date().getTime();
										} else {
											setTimeout("checkOrderStatus('" + dt.data.orderId + "')", 1000);
										}
									});
								} else {
									isPay = true;
									// mui.alert("对不起，支付失败!请稍后重试!" + dt.data.orderId + "支付失败!");
									window.location.href = "/iamberry/pay/goOrderInfo?orderId=" + dt.data.orderId + "&dates=" + new Date().getTime(); // 前往订单详情
								}
							});
						} else {
							isPay = true;
							mui.alert(dt.message);
							window.location.href = "/iamberry/pay/goOrderInfo?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;
		}
	});
	mui('body').on('tap', '.mui-popover-action li>a', function() {
		var a = this,
			parent;
		//根据点击按钮，反推当前是哪个actionsheet
		for(parent = a.parentNode; parent != document.body; parent = parent.parentNode) {
			if(parent.classList.contains('mui-popover-action')) {
				break;
			}
		}
		//关闭actionsheet
		mui('#' + parent.id).popover('toggle');
		yhq_val = $("input[name=radio1]:checked").val();
		yhq_type = $("input[name=radio1]:checked").attr("yhq_type");
		if(yhq_val == undefined) {
			yhq_val = 0
		} else {
			if(yhq_type == 1) {
				if(yhq_val > (usePayMoney - ipt_balance)) {
					$("input[name=radio1]:checked").removeAttr("checked");
					yhq_val = 0;
					mui.alert(' ', '当前优惠券不可用', function() {});
				}
				$("#yhq_price").html(yhq_val);
				$("#accSub,#accSub>div:first-child").show();
				$("#user-pay-money-span").html((usePayMoney - yhq_val - ipt_balance).toFixed(2));
			} else {
				yhq_val = accSub(usePayMoney, Math.floor(accMul($("input[name=radio1]:checked").val(), usePayMoney) * 100) / 100);
				$("#yhq_price").html(yhq_val);
				$("#accSub,#accSub>div:first-child").show();
				$("#user-pay-money-span").html((usePayMoney - yhq_val - ipt_balance).toFixed(2));
			}
		}
	});
	mui.os.ios ? listener_ipt() : keyup_fn();
	var reg = /^(([1-9]\d*))$/;

	function keyup_fn() {
		$('body').on('blur', '#pay_ipt', function(e) {
			ipt_balance = $(this).val();
			if(reg.test(ipt_balance)) {
				if(ipt_balance > (usePayMoney - yhq_val)) {
					ipt_balance = (usePayMoney - yhq_val).toFixed(2);
					if(ipt_balance < 0) {
						ipt_balance = 0;
						$(this).val("");
					} else {
						$(this).val((usePayMoney - yhq_val).toFixed(2));
					}
				}
				if(ipt_balance > used_balance) {
					ipt_balance = used_balance;
					$(this).val(used_balance);
				}
				$('#used_buy').html(ipt_balance);
				var money = (usePayMoney - yhq_val).toFixed(2);
				money <= 0 ? money = 0 : money;
				$("#accSub,#accSub>div:last-child").show();
				$("#user-pay-money-span").html((money - ipt_balance).toFixed(2) + " 元");
			} else {
				mui.alert(' ', '您输入的数字有误，请重新输入', function() {
					$(this).val("");
					ipt_balance = 0;
					$('#used_buy').html(ipt_balance);
					$("#user-pay-money-span").html((usePayMoney - yhq_val - ipt_balance).toFixed(2) + " 元");
				});
			}
		});
	}

	function listener_ipt() {
		document.getElementById('pay_ipt').onblur = function() {
			var th = this;
			ipt_balance = th.value;
			if(reg.test(ipt_balance)) {
				if(ipt_balance > (usePayMoney - yhq_val)) {
					ipt_balance = (usePayMoney - yhq_val).toFixed(2);
					if(ipt_balance < 0) {
						ipt_balance = 0;
						th.value = "";
					} else {
						th.value = (usePayMoney - yhq_val).toFixed(2);
					}
				}
				if(ipt_balance > used_balance) {
					th.value = used_balance;
					ipt_balance = used_balance;
				}
				$('#used_buy').html(ipt_balance);
				var money = (usePayMoney - yhq_val).toFixed(2);
				money <= 0 ? money = 0 : money;
				$("#accSub,#accSub>div:last-child").show();
				$("#user-pay-money-span").html((money - ipt_balance).toFixed(2) + " 元");
			} else {
				mui.alert(' ', '您输入的数字有误<br>请重新输入', function() {
					th.value = "";
					ipt_balance = 0;
					$('#used_buy').html(ipt_balance);
					$("#user-pay-money-span").html((usePayMoney - yhq_val - ipt_balance).toFixed(2) + " 元");
				});
			}
		}
	}
	document.querySelector('.loading-bg').style.display = 'none';
});
// 校验订单状态
function checkOrderStatus(orderId) {
	var url = "/iamberry/wechat/order/checkOrderPaySuccess";
	var order = {
		"s": new Date().getTime(),
		"orderId": orderId
	};
	$.getJSON(url, order, function(data) {
		if(data.status == true) { // 支付成功
			window.location.href = "/iamberry/wechat/order/paySuccess?orderId=" + orderId + "&dates=" + new Date().getTime();
		} else {
			window.location.href = '/iamberry/pay/goOrderInfo?orderId=' + orderId + "&dates=" + new Date().getTime();;
		}
	});
}

// 点击加号的事件
function shoppAddEvent(productId) {
	mui.ajax('/iamberry/wechat/cart/addCart', {
		data: {
			"productId": productId,
			"carNum": 1
		},
		dataType: 'json',
		type: 'GET',
		timeout: 15000,
		success: function(dt) {
			if(dt.status == true) {
				// 销售价
				var productObj = $("#product-" + productId);
				var price = parseInt(productObj.attr("price"));
				// total
				var total = payTotal + price;
				payTotal = total;
				// 修改数量
				var shoppNumObj = $("#shoppNum-" + productId);
				var num = parseInt(shoppNumObj.val());
				shoppNumObj.val(num + 1);
				/* $("#user-pay-money-span").html((payTotal / 100).toFixed(2)); */
				yhq_val = $("input[name=radio1]:checked").val();
				yhq_type = $("input[name=radio1]:checked").attr("yhq_type");
				usePayMoney = accDiv(payTotal, 100);
				if(yhq_val == undefined) {
					yhq_val = 0
				}
				if(yhq_type == 2) {
					yhq_val = accSub(usePayMoney, (Math.floor(accMul(yhq_val, usePayMoney) * 100) / 100));
					$("#yhq_price").html(accSub(usePayMoney, Math.floor(accMul($("input[name=radio1]:checked").val(), usePayMoney) * 100) / 100));
				}
				$("#user-pay-money-span").html((usePayMoney - yhq_val - ipt_balance).toFixed(2) + " 元");
				// 修改小计
				productObj.html("¥" + ((num + 1) * price / 100).toFixed(2));
			} else {
				// 失败之后的事件
				mui.alert(dt.message);
			}
		},
		error: function(xhr, type, errorThrown) {}
	});
}

// 购物车减
function shoppSubEvent(productId) {
	var shoppNumObj = $("#shoppNum-" + productId);
	var num = parseInt(shoppNumObj.val());

	if(num <= 1) {
		mui.alert("不能继续减少了哦!");
		return;
	}
	mui.ajax('/iamberry/wechat/cart/deleteCart', {
		data: {
			"productId": productId,
			"cartNum": 1
		},
		dataType: 'json',
		type: 'GET',
		timeout: 15000,
		success: function(dt) {
			if(dt.status == true) {
				// 销售价
				var productObj = $("#product-" + productId);
				var price = parseInt(productObj.attr("price"));
				// total
				var total = payTotal - price;
				payTotal = total;
				// 修改数量
				var shoppNumObj = $("#shoppNum-" + productId);
				var num = parseInt(shoppNumObj.val());
				shoppNumObj.val(num - 1);
				/*$("#user-pay-money-span").html((payTotal / 100).toFixed(2));*/
				yhq_val = $("input[name=radio1]:checked").val();
				yhq_type = $("input[name=radio1]:checked").attr("yhq_type");
				usePayMoney = accDiv(payTotal, 100);
				if(yhq_val == undefined) {
					yhq_val = 0
				}
				if(yhq_type == 2) {
					yhq_val = accSub(usePayMoney, Math.floor(accMul(yhq_val, usePayMoney) * 100) / 100);
					$("#yhq_price").html(accSub(usePayMoney, Math.floor(accMul($("input[name=radio1]:checked").val(), usePayMoney) * 100) / 100));
					if(ipt_balance > (usePayMoney - yhq_val)) {
						if((usePayMoney - yhq_val) <= 0) {
							ipt_balance = 0;
							$('#used_buy').html(ipt_balance);
							$('#pay_ipt').val("");
						} else {
							ipt_balance = (usePayMoney - yhq_val).toFixed(2);
							$('#used_buy').html(ipt_balance);
							$('#pay_ipt').val(ipt_balance);
						}
					}
					$("#user-pay-money-span").html((usePayMoney - yhq_val - ipt_balance).toFixed(2) + " 元");
				} else {
					if((usePayMoney - yhq_val) < ipt_balance) {
						if((usePayMoney - yhq_val) <= 0) {
							ipt_balance = 0;
							$('#used_buy').html(ipt_balance);
							$('#pay_ipt').val("");
						} else {
							ipt_balance = (usePayMoney - yhq_val).toFixed(2);
							$('#used_buy').html(ipt_balance);
							$('#pay_ipt').val(ipt_balance);
						}
					}
					if(yhq_val > (usePayMoney - ipt_balance)) {
						mui.alert(' ', '当前优惠券不可用', function() {
							$("input[name=radio1]:checked").removeAttr("checked");
							yhq_val = 0;
							$("#yhq_price").html(yhq_val);
							$("#user-pay-money-span").html((usePayMoney - yhq_val - ipt_balance).toFixed(2) + " 元");
						});
					}
					$("#user-pay-money-span").html((usePayMoney - yhq_val - ipt_balance).toFixed(2) + " 元");
				}
				productObj.html("¥" + ((num - 1) * price / 100).toFixed(2));
			} else {
				mui.alert(dt.message);
			}
		},
		error: function(xhr, type, errorThrown) {
			errorfn(xhr);
		}
	});
}