// 全选按钮状态
var allCheckBtn = true;
var payTotal = 0;
mui.ready(function() {
	marquee_Show();
	selectCart();
	mui('body').on('click', '.click-all-btn', function() {
		if(allCheckBtn) {
			allCheckBtn = false;
			$(".all_check").prop('checked', allCheckBtn);
			$(".mt-mr-che").prop('checked', allCheckBtn);
			$("#pay-total").html("0.0");
			$("#go-clearing").html("去结算(0)")
		} else {
			allCheckBtn = true;
			var length = $(".mt-mr-che").length;
			$("#go-clearing").html("去结算(" + length + ")");
			$(".all_check").prop('checked', allCheckBtn);
			$(".mt-mr-che").prop('checked', allCheckBtn);
			reSetTotal()
		}
	});
	mui('body').on('tap', '#go-clearing', function() {
		var str = $("#go-clearing").html();
		if("去结算(0)" != str) {
			var input = $(".mui-input-numbox");
			var carts = "";
			for(var i = 0; i < input.length; i += 1) {
				var id = $(input[i]).attr("id");
				id = id + "btn";
				if($("#" + id)[0].checked == true) {
					carts += $(input[i]).attr("id").replace("cartIdInput", "-")
				}
			}
			carts = carts.substring(1, carts.length);
			window.location.href = '/tooth/pay/settlement?cartId=' + carts + '&tiemstamp=' + new Date().getTime() + "&userQrcodeType=" + JSON.parse(sessionStorage.getItem('userQrcodeType'))
		} else {
			alert("请选择您要结算的产品~")
		}
	});
	mui('body').on('click', '.mt-mr-che', function() {
		var input = $(".mui-input-numbox");
		var total = 0;
		var sum = 0;
		var count = 0;
		for(var i = 0; i < input.length; i += 1) {
			var id = $(input[i]).attr("id");
			id = id + "btn";
			if($("#" + id)[0].checked == true) {
				count += 1;
				var price = parseInt($(input[i]).attr("price"));
				var num = parseInt($(input[i]).val());
				total += price * num;
				sum += 1
			}
		}
		if($('.mt-mr-che').length <= count) {
			allCheckBtn = true;
			$(".all_check").prop('checked', allCheckBtn)
		} else {
			allCheckBtn = false;
			$(".all_check").prop('checked', allCheckBtn)
		}
		$("#go-clearing").html("去结算(" + sum + ")");
		$("#pay-total").html(accDiv(total, 100))
	});
	document.querySelector('.loading-bg').style.display = 'none'
});

function selectCart() {
	mui.ajax(base_path + '/cart/selectCartByOpenId?userQrcodeType=' + JSON.parse(sessionStorage.getItem('userQrcodeType')), {
		dataType: 'json',
		type: 'post',
		timeout: 15000,
		success: function(dt) {
			if(dt.status) {
				if(dt.data.cartList.length <= 0) {
					$(".gwc_null").show();
					$(".marquee_cart").hide();
					$(".shopping-box").hide();
					$('.shoping-tt').hide()
				} else {
					if(marquee != '') {
						$('<div class="marquee_cart">立即购买，每台赠送三年滤芯</div>').insertBefore(".shoping-tt")
					}
					var noteLi = "";
					var sumCount = 0;
					var pro_color = "",img='';
					for(var i = 0; i < dt.data.cartList.length; i += 1) {
						if(dt.data.cartList[i].productType==1){
						switch (dt.data.cartList[i].cartColorId){
						case 1:
							img='http://static.iamberry.com/tooth/images/shop/cp-blue.png';pro_color='品蓝';
							break;
						case 2:
							img='http://static.iamberry.com/tooth/images/shop/cp-black.png';pro_color='品黑';
							break;
						case 3:
							img='http://static.iamberry.com/tooth/images/shop/cp-green.png';pro_color='苹果绿';
							break;
						case 4:
							img='http://static.iamberry.com/tooth/images/shop/cp-red.png';pro_color='西瓜红';
							break;
						default:
							break;
						}
						}else{
							img=dt.data.cartList[i].productIntroduceImg;pro_color=dt.data.cartList[i].productColor;
						}
						if(dt.data.cartList[i].productStatus != 1) {
							noteLi += "<li class='mui-table-view-cell mui-media bg-f'><div class='mui-slider-right mui-disabled'><a class='mui-btn mui-btn-red btn-del' id='cartItem_" + dt.data.cartList[i].cartId + "' onclick='deleteCartItem(this, 1)' lang='" + dt.data.cartList[i].cartProductId + "' colorid='"+dt.data.cartList[i].cartColorId+"'>删除</a></div><div class='mui-slider-handle'><img style='width: auto !important;' class='mui-media-object mui-pull-left wh-100' src='" + img + "'><div class='mui-media-body'><div class='wt-space gwc_tit'>" + dt.data.cartList[i].productName + "</div><p class='mui-ellipsis delete-cart-style'>产品下架</p><p></p></div>" + "</div></li>"
						} else {
							sumCount += 1;
							total = accDiv(dt.data.cartList[i].productDiscount * dt.data.cartList[i].cartNum, 100);
							noteLi += "<li class='mui-table-view-cell mui-media bg-f'><div class='mui-slider-right mui-disabled'><a class='mui-btn mui-btn-red btn-del' id='cartItem_" + dt.data.cartList[i].cartId + "' onclick='deleteCartItem(this, 1)' lang='" + dt.data.cartList[i].cartProductId + "' colorid='"+dt.data.cartList[i].cartColorId+"'>删除</a></div><div class='mui-slider-handle'><input name='checkbox' type='checkbox' checked='checked' id='cartIdInput" + dt.data.cartList[i].cartId + "btn' class='mui-pull-left mt-mr-che' /><span class='mui-media-object mui-pull-left wh-100 go_chanpin_details' proid='" + dt.data.cartList[i].cartProductId + "' colorid='"+dt.data.cartList[i].cartColorId+"'><img src='" + img + "'></span><div class='mui-media-body'><div class='wt-space gwc_tit'>" + dt.data.cartList[i].productName + "</div><small class='gwc_pp'>颜色：" + pro_color + "</small><div class='price'><span class='price_sp'>¥" + accDiv(dt.data.cartList[i].productDiscount, 100) + "</span><small id='sub-total" + dt.data.cartList[i].cartId + "'>小计：¥" + total + "</small></div><p class='mui-ellipsis'></p><div class='mui-numbox' data-numbox-min='1' data-numbox-max='999'><button class='mui-btn mui-btn-numbox-minus' type='button' onclick='subCartNum(" + dt.data.cartList[i].cartId +","+dt.data.cartList[i].cartColorId+")'>-</button><input class='mui-input-numbox' readonly='readonly' price='" + dt.data.cartList[i].productDiscount + "' dir='" + dt.data.cartList[i].cartProductId + "' type='tel' lang='" + dt.data.cartList[i].cartNum + "' id='cartIdInput" + dt.data.cartList[i].cartId + "' value='" + dt.data.cartList[i].cartNum + "'><button class='mui-btn mui-btn-numbox-plus' onclick='addCartNum(" + dt.data.cartList[i].cartId + ","+dt.data.cartList[i].cartColorId+")' type='button'>+</button></div><p></p></div>" + "</div></li>"
						}
					}
					payTotal = dt.data.total;
					$("#pay-total").html(accDiv(dt.data.total, 100));
					$("#go-clearing").html("去结算(" + sumCount + ")");
					$("#cart-list-ul").append(noteLi)
				}
			}
		},
		error: function(xhr, type, errorThrown) {
			errorfn(xhr)
		}
	})
};

function subCartNum(cartId,colorId) {
	var nowNum = $("#cartIdInput" + cartId).val();
	$.trim(nowNum);
	var r = /^[1-9]+[0-9]*$/;
	if(!r.test(nowNum)) {
		return false
	}
	var pId = $("#cartIdInput" + cartId).attr("dir");
	var num = parseInt(nowNum);
	if(num > 1) {
		num = num - 1;
		mui.ajax(base_path + '/cart/deleteCart', {
			data: {
				"productId": pId,
				"cartNum": 1,
				"colorId":colorId
			},
			dataType: 'json',
			type: 'GET',
			timeout: 15000,
			success: function(dt) {
				if(dt.status == true) {
					$("#cartIdInput" + cartId).val(num);
					$("#cartIdInput" + cartId).prop("lang", num);
					var price = parseInt($("#cartIdInput" + cartId).attr("price"));
					$("#sub-total" + cartId).html("小计：¥" + accDiv(price * num, 100));
					reSetTotal()
				} else {
					alert(dt.message)
				}
			},
			error: function(xhr, type, errorThrown) {}
		})
	} else {
		var cartItemObj = document.getElementById("cartItem_" + cartId);
		deleteCartItem(cartItemObj, 1)
	}
};

function addCartNum(cartId,colorId) {
	var nowNum = $("#cartIdInput" + cartId).val();
	$.trim(nowNum);
	var r = /^[1-9]+[0-9]*$/;
	if(!r.test(nowNum)) {
		return false
	}
	var num = parseInt(nowNum);
	if(num < 999) {
		num = num + 1;
		var pId = $("#cartIdInput" + cartId).attr("dir");
		mui.ajax(base_path + '/cart/addCart', {
			data: {
				"productId": pId,
				"carNum": 1,
				"colorId":colorId
			},
			dataType: 'json',
			type: 'GET',
			timeout: 15000,
			success: function(dt) {
				if(dt.status == true) {
					$("#cartIdInput" + cartId).val(num);
					$("#cartIdInput" + cartId).prop("lang", num);
					var price = parseInt($("#cartIdInput" + cartId).attr("price"));
					$("#sub-total" + cartId).html("小计：¥" + accDiv(price * num, 100));
					reSetTotal()
				} else {
					alert(dt.message)
				}
			},
			error: function(xhr, type, errorThrown) {
				errorfn(xhr)
			}
		})
	}
};

function deleteCartItem(obj, isParent) {
	var btnArray = ['否', '是'];
	mui.confirm('您确定要删除吗?', '提示', btnArray, function(e) {
		if(e.index == 1) {
			mui.ajax(base_path + '/cart/deleteCartByProductId', {
				data: {
					"productId": $(obj).attr("lang"),
					"colorId":$(obj).attr("colorid"),
					"datestamp": new Date().getTime()
				},
				dataType: 'json',
				type: 'GET',
				timeout: 15000,
				success: function(dt) {
					if(dt.status == true) {
						if(isParent == 1) {
							$(obj).parent().parent().remove()
						} else {
							$(obj).parent().parent().remove()
						}
						$(obj).parent().remove();
						if($("#cart-list-ul>li").length <= 0) {
							$(".gwc_null").show();
							$(".marquee_cart").hide();
							$(".shopping-box").hide();
							$('.shoping-tt').hide()
						}
						var length = $(".mt-mr-che").length;
						$("#go-clearing").html("去结算(" + length + ")");
						$(".all_check").prop('checked', true);
						$(".mt-mr-che").prop('checked', true);
						reSetTotal()
					} else {
						alert(dt.message)
					}
				},
				error: function(xhr, type, errorThrown) {
					errorfn(xhr)
				}
			})
		}
	})
};

function reSetTotal() {
	var input = $(".mui-input-numbox");
	var total = 0;
	for(var i = 0; i < input.length; i += 1) {
		var id = $(input[i]).attr("id");
		id = id + "btn";
		if($("#" + id)[0].checked == true) {
			var price = parseInt($(input[i]).attr("price"));
			var num = parseInt($(input[i]).val());
			total += price * num
		}
	}
	payTotal = total;
	$("#pay-total").html(accDiv(total, 100))
};
mui('body').on('tap', '#cartActivity', function() {
	document.querySelector('.loading-bg').style.display = 'block';
	location.href = this.getAttribute('url')
});