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;
		case "15":
		    $(".tab-with-orderlist .icon-ping").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) {
			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":
								
								var salesSpellOrderId='';
								if(typeof(this.salesSpellOrderId)!="undefined"){
									salesSpellOrderId=this.salesSpellOrderId;
								}
								str1 = '<button type="button" id="orderPay" onclick="goOrderPay(\'' + this.salesOrderid + '\',\'' + this.efficacious + '\',\''+this.salesIsSpellOrder+'\',\''+this.orderItemList[0].itemProductId+'\',\''+this.orderItemList[0].itemColorId+'\',\''+this.salesIsSpellOrder+'\',\''+salesSpellOrderId+'\');" class="mui-btn my-btn-danger mui-pull-right">去支付</button>';
								str = '<span class="cl-red">待付款</span>'+str1;
								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;
							case "15":
								str = '<span>正在拼单</span>';
								str1='<button type="button" class="mui-btn my-btn-redP mui-pull-right" productId="'+this.orderItemList[0].itemProductId+'" colorId="'+this.orderItemList[0].itemColorId+'" orderid="'+this.salesOrderid+'">邀请好友拼单</button>'
								break;	
							default:
								str = '<span>订单完成</span>';
								break;
						}
						//var orderSalesStatus = this.salesStatus;	//订单状态
						if(Status == "") {
							str1 = '状态:' + str;
						}
						let isSpell=this.salesIsSpellOrder,isSpellStr='';
						if(isSpell==1){
							isSpellStr='isSpell="'+this.salesIsSpellOrder+'"';
						}
						var a = '<ul class="mui-table-view">',allcount=0;
						mui(this.orderItemList).each(function(index) {
							allcount+=this.itemNum;
							let price=accDiv(this.itemProductDiscount, 100);
							if(isSpell==1){
								price=accDiv((this.itemTotal/this.itemNum), 100);
							}
							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 + '" style="background: #eff5f7;"></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">¥'+price+'</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 + ' '+isSpellStr+'>订单详情</a></div><div>共'+allcount+'件     合计:<span class="mui-h5 cl-red">¥' + accDiv(this.salesYetAmount, 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) {
			//异常处理;
			console.log(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 = 15;
				break;
			case 2:
				tabindex = 2;
				break;
			case 3:
				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,isSpell,productId,colorId,isSpell,salesSpellOrderId) {
	var dataArgs = {
		"orderId": salesOrderid
	};

	if(!efficacious) {
		mui.alert("您的订单有商品下架,请重新生成订单购买!");
		return false;
	}
	let isSpellstr='';
		if(isSpell==1){
			isSpellstr='&isSpell=1';													
	}
	$.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) { // 支付成功
											//salesSpellOrderId=''发起拼团      !='' 参与好友拼团
											if(isSpell==1 && salesSpellOrderId==''){
												location.href='pay_add_group.html?productId='+productId+'&colorId='+colorId+'&orderid='+orderIds.orderId+'&isSpell=1'
											}else{
												location.href = "pay_win.html?orderId=" + orderIds.orderId + isSpellstr;
											}
										} 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 + "支付失败!");
							location.href = "order_details.html?orderId=" + dt.data.orderId + isSpellstr; // 前往订单详情
						}
					});
				} 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() //设置结束日期
//	});
//	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();
//	});
//});

//邀请好友拼团
$(document).on('tap', '.my-btn-redP', function() {
	var th=$(this);
	location.href='pay_add_group.html?productId='+th.attr("productId")+'&colorId='+th.attr("colorId")+'&orderid='+th.attr("orderid")+'&isSpell=1';
});