var isPay = true; // 是否在请求支付,false表示正在请求,true可以请求
var tabindex = 1;
/**
 * 获取指定的URL参数值
 * URL:http://www.baidu.com/index?name=tyler
 * 参数:paramName URL参数
 * 调用方法:getParam("name")
 * 返回值:tyler
 */
var search_str = "",
	pageNumber = 0,
	pagesize = 10;
//初始化mui
mui.init({
	pullRefresh: {
		container: '#pullrefresh_order_list',
		down: {
			//						callback: pulldownRefresh
		},
		up: {
			contentrefresh: '正在加载...',
			callback: pullupRefresh
		}
	}
});
mui.ready(function() {
	tabindex = getParam("salesStatus");
	tabindex == null ? tabindex = '1' : tabindex;
	$(".tab-with-orderlist .icon-topay").removeClass('mui-active');
	switch(tabindex) {
		case "2":
			$(".tab-with-orderlist .icon-todelivery").addClass('mui-active');
			break;
		case "5":
			$(".tab-with-orderlist .icon-delivery").addClass('mui-active');
			break;
		case "-1":
			$(".tab-with-orderlist .icon-allorder").addClass('mui-active');
			break;
		default:
			$(".tab-with-orderlist .icon-topay").addClass('mui-active');
			break;
	}
	mui('#pullrefresh_order_list').pullRefresh().pullupLoading();
	getCartNum();
	document.querySelector('.loading-bg').style.display = 'none';
});

function SetRemainTime(setName, index, sys_second) {

	var setName = setInterval(function() {
		if(sys_second > 1) {
			sys_second -= 1;
			var minute = Math.floor((sys_second / 60));
			var second = Math.floor(sys_second % 60);

			//$("#testid"+index).html(second);
			$("#testid" + index).html(minute + "分" + second + "秒");
		} else {
			$("#timeli" + index).hide();
			$("#testid" + index).parent().parent().parent().hide();
			clearInterval(setName);
		}
	}, 1000);

}

/**
 * 上拉加载具体业务实现
 */
function pullupRefresh() {
	++pageNumber;
	var Status = ""
	var btnArray = ['否', '是'];
	tabindex == "-1" ? Status = "" : Status = tabindex;
	$.ajax(base_path + '/cart/selectShopOrder?dates=' + new Date().getTime(), {
		data: {
			"pageSize": pagesize,
			"text": search_str,
			"pageNO": pageNumber,
			"beginDate": $("#mydate").val(),
			"salesStatus": Status
		},
		dataType: 'json',
		type: 'post',
		timeout: 15000,
		xhrFields: {
			withCredentials: true
		},
		crossDomain: true,
		success: function(dt) {
			console.log(dt.isRedirect);
			if(dt.isRedirect) {
				location.href = dt.redirectURL;
			} else {
				if(dt.status) {
					var order_data = [];
					order_data = dt.data.orderList;
					//参数为true代表没有更多数据了。
					mui('#pullrefresh_order_list').pullRefresh().endPullupToRefresh(order_data.length < pagesize);
					var table = document.body.querySelector('.my-scroll-order'),
						str = "",
						str1 = "";
					mui(order_data).each(function(index) {
						var li = document.createElement('li');
						switch(this.salesStatus) {
							case "0":
								str = '<span>取消订单</span>';
								break;
							case "1":
								str = '<span class="cl-red">待付款</span><button type="button" id="orderPay" onclick="goOrderPay(\'' + this.salesOrderid + '\',' + this.efficacious + ');" class="mui-btn my-btn-danger mui-pull-right">去支付</button>';
								str1 = '<button type="button" id="orderPay" onclick="goOrderPay(\'' + this.salesOrderid + '\',' + this.efficacious + ');" class="mui-btn my-btn-danger mui-pull-right">去支付</button>';
								break;
							case "2":
								str = '<span>待发货</span>';
								break;
							case "3":
								str = '<span>退款申请中</span>';
								break;
							case "4":
								str = '<span>已退款</span>';
								break;
							case "5":
								str = '<span>已发货</span>';
								break;
							case "6":
								str = '<span>申请退货中</span>';
								break;
							case "7":
								str = '<span>退货中</span>';
								break;
							case "8":
								str = '<span>订单关闭</span>';
								break;
							case "9":
								str = '<span>换货中</span>';
								break;
							case "10":
								str = '<span>换货完成</span>';
								break;
							case "11":
								str = '<span>申请换货中</span>';
								break;
							default:
								str = '<span>订单完成</span>';
								break;
						}
						//var orderSalesStatus = this.salesStatus;	//订单状态
						if(Status == "") {
							str1 = '状态:' + str;
						}

						var a = '<ul class="mui-table-view">',allcount=0;
						mui(this.orderItemList).each(function(index) {
							var pro_color = switchcolor(this.itemColorId);
							var colorImg = switchColorImg(this.itemColorId);
							allcount+=this.itemNum;
							/* CheckImgExists(this.itemProductPic) == false ? this.itemProductPic = '/iamberry/common/shop/images/chanpin-list-1.jpg' : this.itemProductPic; */
							// if(this.productStatus != 1) {
							//     var itemNum = this.itemNum;
							//     if(itemNum < 3){
							//         itemNum = 1;
							//     }
							//     a += '<li class="mui-table-view-cell"><table class="my-tb-order"><tr><td rowspan="3"><div class="wh-80"><img class="wh-80" src="' + this.itemProductPic + '"></div></td><td rowspan="3">'  + '赠送' + (this.itemNum / 3) + '套三年滤芯' + '<span class="cl-red"></span></td><td><span></td><td></td></tr><tr><td></td></tr><tr></tr></table></li>'
							// } else {
							//     a += '<li class="mui-table-view-cell"><a proid="' + this.itemProductId + '" colorid="' + this.itemColorId + '" class="go_chanpin_details"><table class="my-table-order"><tbody><tr><td rowspan="3" style="width:26%"><div class="wh-80"><img src="' + colorImg + '"></div></td><td>' + this.itemProductName + '</td><td><span><h5 class="mui-text-center">x' + this.itemNum + '</h5></span></td></tr><tr><td><span><h5>颜色:' + pro_color + '</h5></span></td></tr><tr><td><span>单价:<span class="mui-h5">¥' + accDiv(this.itemProductDiscount, 100) + '</span></span></td><td></td></tr></tbody></table></a></li>'
							// }
							a += '<li class="mui-table-view-cell"><a proid="' + this.itemProductId + '" colorid="' + this.itemColorId + '" class="go_chanpin_details"><table class="my-table-order"><tbody><tr><td rowspan="3" style="width:26%"><div class="wh-80" style="margin: 5px 10px 0 0;"><img src="' + this.itemProductPic + '"></div></td><td>' + this.itemProductName + '</td></tr><tr><td><span><h5>' + this.productColor + ' x ' + this.itemNum + '</h5></span></td></tr><tr><td><span><span class="mui-h5">¥' + accDiv(this.itemProductDiscount, 100) + '</span></span></td><td></td></tr></tbody></table></a></li>'
						});
						//状态为1 的 ,表示代发货,,这里显示支付关闭倒计时;
						if(this.salesStatus == 1) {
							if(this.salesAdminRemark > 0) {
								a += '<li id="timeli' + index + '" class="mui-table-view-cell show_post_info">' +
									'<span class="mui-pull-left">支付倒计时:</span>' +
									'<span style="border:0;font-size:large;" class="my-btn-orange" id="testid' + index + '">' +
									'</span></li>';
								SetRemainTime("setName" + index, index, this.salesAdminRemark); //间隔函数,1秒执行
							}

						}

						a += '<li class="mui-table-view-cell"><div class="btn-zu">' + str1 + '<a class="mui-btn my-btn-orange mui-pull-right mr-5 go_order_details" value=' + this.salesOrderid + '>订单详情</a></div><div>共'+allcount+'件     合计:<span class="mui-h5 cl-red">¥' + accDiv(this.salesAmount, 100) + '</span></div></li>';
						
						this.salesPostFirm == null ? this.salesPostFirm = "" : this.salesPostFirm;
						if(this.salesPostFirm == 'sto') {
							this.salesPostFirm = '申通快递';
						}
						if(this.salesPostFirm == 'yto') {
							this.salesPostFirm = '圆通快递';
						}
						if(this.salesPostFirm == 'sf') {
							this.salesPostFirm = '顺丰快递';
						}
						if(this.salesPostFirm == 'zto') {
							this.salesPostFirm = '中通速递';
						}
						if(this.salesPostFirm == 'ems') {
							this.salesPostFirm = '邮政EMS';
						}
						if(this.salesPostFirm == 'zjs') {
							this.salesPostFirm = '宅急送';
						}
						if(this.salesPostFirm == 'yunda') {
							this.salesPostFirm = '韵达快递';
						}
						if(this.salesPostFirm == 'cces') {
							this.salesPostFirm = 'cces快递';
						}
						if(this.salesPostFirm == 'pick') {
							this.salesPostFirm = '上门提货';
						}
						if(this.salesPostFirm == 'htky') {
							this.salesPostFirm = '汇通快递';
						}
						if(this.salesPostFirm == 'ttkdex') {
							this.salesPostFirm = '天天快递';
						}
						if(this.salesPostFirm == 'stars') {
							this.salesPostFirm = '星晨急便';
						}
						if(this.salesPostFirm == 'jd') {
							this.salesPostFirm = '京东快递';
						}
						if(this.salesPostFirm == '01') {
							this.salesPostFirm = '其他';
						}
						if(this.salesPostFirm == '02') {
							this.salesPostFirm = '上门送货';
						}
						if(this.salesPostFirm == 'longbanwuliu') {
							this.salesPostFirm = '龙邦快递';
						}
						if(this.salesPostFirm == 'dbkd') {
							this.salesPostFirm = '德邦快递';
						}
						if(this.salesPostNum == null || this.salesPostNum == "") {
							this.salesPostNum = ""
						} else {
							a += '<li class="mui-table-view-cell show_post_info"  postfirm="' + this.salesPostFirm + '" postnum="' + this.salesPostNum + '" gourl="order_list.html?salesStatus=' + Status + '"><span class="mui-pull-left">物流信息:</span>' + this.salesPostFirm + '&nbsp;&nbsp;&nbsp;<span>' + this.salesPostNum + '</span></li>';
						}
						li.innerHTML = a + '</ul>';
						table.appendChild(li);
					});
				} else {
					mui.confirm(dt.message + '是否重新加载页面?', '爱贝源-提示', btnArray, function(e) {
						if(e.index == 1) {
							location.reload(true);
						}
					});
				}
			}
		},
		error: function(xhr, type, errorThrown) {
			//异常处理;
			errorfn(xhr);
		}
	});
}

//function search_pullrefresh(str) {
//	if(str != null && str != '') {
//		if(!checkParameter(str)) {
//			mui.alert('您输入的格式有误,请重新输入!');
//		} else {
//			pageNumber = 0;
//			$('.my-scroll-order').empty();
//			search_str = str;
//			mui('#pullrefresh_order_list').pullRefresh().refresh(true);
//			mui('#pullrefresh_order_list').pullRefresh().pullupLoading();
//		}
//	} else {
//		pageNumber = 0;
//		$('.my-scroll-order').empty();
//		search_str = str;
//		mui('#pullrefresh_order_list').pullRefresh().refresh(true);
//		mui('#pullrefresh_order_list').pullRefresh().pullupLoading();
//	}
//}
//mui.os.ios ? listener_ipt() : keyup_fn();
//
//function keyup_fn() {
//	$('body').on('keyup', '#order-list-search', function(e) {
//		var currKey = 0,
//			e = e || event;
//		currKey = e.keyCode || e.which || e.charCode;
//		var keyName = String.fromCharCode(currKey);
//		if(currKey == "13") {
//			//传参数并加载数据
//			var str = $.trim($('#order-list-search').val());
//			search_pullrefresh(str);
//		}
//	});
//}
//
//function listener_ipt() {
//	document.getElementById('order-list-search').onblur = function() {
//		//传参数并加载数据
//		var str = $.trim($('#order-list-search').val());
//		search_pullrefresh(str);
//	}
//}

mui.each(document.querySelectorAll('.tab-with-orderlist .mui-control-item'), function(index, el) {
	el.addEventListener('tap', function() {
		pageNumber = 0;
		switch(index) {
			case 0:
				tabindex = 1;
				break;
			case 1:
				tabindex = 2;
				break;
			case 2:
				tabindex = 5;
				break;
			default:
				tabindex = -1;
				break;
		}
		$('.my-scroll-order').empty();
		mui('#pullrefresh_order_list').pullRefresh().refresh(true);
		mui('#pullrefresh_order_list').pullRefresh().pullupLoading();
	}, false);
});

function goOrderPay(salesOrderid, efficacious) {
	var dataArgs = {
		"orderId": salesOrderid
	};

	if(!efficacious) {
		mui.alert("您的订单有商品下架,请重新生成订单购买!");
		return false;
	}

	$.ajax(base_path + '/cart/orderPay', { // 提交订单,准备支付
		data: dataArgs,
		dataType: 'json',
		type: 'POST',
		timeout: 15000,
		xhrFields: {
			withCredentials: true
		},
		crossDomain: true,
		success: function(dt) {
			if(dt.isRedirect) {
				location.href = dt.redirectURL;
			} else {
				layer.closeAll();
				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: "正在请求加载订单信息..."
							}); // 调用加载弹出层
							$.ajax(base_path + '/order/checkOrderPaySuccess', { // 校验订单状态
								data: orderIds,
								dataType: 'json',
								type: 'post',
								timeout: 15000,
								xhrFields: {
									withCredentials: true
								},
								crossDomain: true,
								success: function(dt) {
									if(dt.isRedirect) {
										location.href = dt.redirectURL;
									} else {
										if(dt.status) { // 支付成功
											window.location.href = base_path + "/order/paySuccess?orderId=" + orderIds.orderId + "&dates=" + new Date().getTime();
										} else {
											setTimeout(checkOrderStatus(orderIds), 1000);
										}
									}
								},
								error: function(xhr, type, errorThrown) {
									isPay = true;
									layer.closeAll();
									mui.alert("您的网络异常,请刷新重试!");
									return;
								}
							});
						} else {
							isPay = true;

							mui.alert("对不起,支付失败!请稍后重试!" + dt.data.orderId + "支付失败!");
							window.location.href = "order_details.html?orderId=" + dt.data.orderId; // 前往订单详情
						}
					});
				} else {
					isPay = true;
					mui.alert(dt.message);
				}
			}
		},
		error: function(xhr, type, errorThrown) {
			isPay = true;
			layer.closeAll();
			mui.alert("您的网络异常,请刷新重试!");
			return;
		}
	});
}

function checkParameter(remark) {
	if(!/^[\u4e00-\u9fa5_a-zA-Z0-9-]+$/.test(remark)) {
		return false;
	}
	return true;
}
mui('body').on('tap', '#mydate', function() {
	var th = this;
	var picker = new mui.DtPicker({
		type: "date", //设置日历初始视图模式
		beginDate: new Date(2016, 7, 1), //设置开始日期
		endDate: new Date() //设置结束日期
	});
	console.log(picker)
	picker.show(function(rs) {
		pageNumber = 0;
		th.value = rs.text;
		picker.dispose();
		$('.my-scroll-order').empty();
		mui('#pullrefresh_order_list').pullRefresh().refresh(true);
		mui('#pullrefresh_order_list').pullRefresh().pullupLoading();
	});
});
mui("body").on('tap', '.mui-btn[data-id=btn-cancel]', function() {
	pageNumber = 0;
	document.getElementById('mydate').value = "";
})
mui("body").on('tap', '.my-right', function() {
	if($(".search-box").is(":hidden")) {
		$('.search-box').show();
		$(".tab-with-orderlist").css("margin-top", 107 + "px");
		$(".mui-bar-nav~.mui-content").css("padding-top", 156 + "px");
	} else {
		$('.search-box').hide();
		document.getElementById('mydate').value = "";
		$(".tab-with-orderlist").css("margin-top", 56 + "px");
		$(".mui-bar-nav~.mui-content").css("padding-top", 107 + "px");
	}
})