
var PageSize = 20;//每页计数
var CurrentPage = 1; //当前页
//搜索条件
var searchUrl = '';

function setList()
{
	var pageWidth=document.documentElement.clientWidth-9;
	$(".sub_container_content").css("width",pageWidth);
	$(".sub_container_listhead").css("width",pageWidth);
	$(".llist").css("width",pageWidth);
	var c1_width = pageWidth*0.02+"px";
	var c18_width = pageWidth*0.05+"px";
	var c2_width = pageWidth*0.06+"px";
	var c3_width = pageWidth*0.09+"px";
	var c4_width = pageWidth*0.05+"px";
	var c5_width = pageWidth*0.04+"px";
	var c6_width = pageWidth*0.04+"px";
	var c7_width = pageWidth*0.04+"px";
	var c8_width = pageWidth*0.04+"px";
	var c9_width = pageWidth*0.05+"px";
	var c10_width = pageWidth*0.05+"px";
	var c11_width = pageWidth*0.06+"px";
	var c12_width = pageWidth*0.05+"px";
	var c13_width = pageWidth*0.05+"px";
	var c14_width = pageWidth*0.07+"px";
	var c15_width = pageWidth*0.06+"px";
	var c16_width = pageWidth*0.06+"px";
	var c17_width = pageWidth*0.06+"px";

	$('.c1').css("width",c1_width);
	$('.c2').css("width",c2_width);
	$('.c18').css("width",c18_width);
	$('.c3').css("width",c3_width);
	$('.c4').css("width",c4_width);
	$('.c5').css("width",c5_width);
	$('.c6').css("width",c6_width);
	$('.c7').css("width",c7_width);
	$('.c8').css("width",c8_width);
	$('.c9').css("width",c9_width);
	$('.c10').css("width",c10_width);
	$('.c11').css("width",c11_width);
	$('.c12').css("width",c12_width);
	$('.c13').css("width",c13_width);
	$('.c14').css("width",c14_width);
	$('.c15').css("width",c15_width);
	$('.c16').css("width",c16_width);
	$('.c17').css("width",c17_width);
}

$(document).ready(function(){
    //loading
    $('#loadingContainer').ajaxStart(function(){$(this).show();$('#loadingbackground').show().css({"opacity": "0.5"});}).ajaxStop(function(){$(this).hide();});
	$("#txtDateFrom").datepicker();
	$("#txtDateTo").datepicker();
	
	setInterval(function(){
        $('div.sub_container_page').css('top',$(window.parent.frames.right).height()-$('div.sub_container_page').height()-2); //设置底部分页区域的位置
        $('div.sub_container_content').css('height',$(window.parent.frames.right).height()-$('div.sub_container_title').height()-$('div.sub_container_operation').height()-$('div.sub_container_listhead').height()-$('div.sub_container_page').height()-10); //设置内容区域的高度
        if($.browser.mozilla){setList();}
        $('#frmHeight').val($(window.parent.frames.right).height());//将窗口高度用hidden记录,在iframe中取值
    },1000);
    
    if(CanExportOrder=="False"){
         $('#bt_ExportPart').hide();
          $('#bt_Export').hide();
    }
	
	if(getQueryStringRegExp('test') == ''){
	    BindList();
	}
	
	//搜索
	$('#btnSearch').click(function(){
	    $('#ustatus').val('');
	    CurrentPage = 1;
	    BindList();
	    if ($(".searchDetails").is(":visible")){
            $('#btnSearchAdv').click();
        };
    });
    
	//全选
    $('input[@name=chkAll]').click(function(){
        $('input[@name=chkItem]').attr('checked',$(this).attr('checked'));
    });
    //更新跟单员
    $('#btnUpdateManagers').click(function(){
        var urldata = '';
        $('input[@name=chkItem][@checked]').each(function(){
            urldata += $(this).val() + ',' + $('#manager_' + $(this).val()).val() + '|';
        });
        if(urldata != ''){
            urldata = urldata.substring(0,urldata.length-1)
        }else{
            alert('请选择要修改跟单员的订单');
            return false;
        };
        $.ajax({
            url:'OrderList.aspx?type=ajax&Action=UpdateManagerAjax&ManagerInfo='+urldata + '&NoCopyRight=1',
            cache:false,
            success:function(data){
                if(!checkLoginStatus(data)){return false;}//是否要重新登陆
                if(data>0){
                    alert('更新成功');
                };
            },
            error:function(){alert('error');}
        });
        return false;
    });
    //批量删除
    $('#btnDelete').click(function(){
        var ids = '';
        $('input[@name=chkItem][@checked]').each(function(){
            ids += $(this).val() + ',';
        });
        if(ids != ''){
            ids = ids.substring(0,ids.length-1)
        }else{
            alert('请选择要删除的订单');
            return false;
        };
        if(confirm('确定要删除选中的订单吗?')){DeleteOrder(ids);}
        return false;
    });
   //导出订单
   $('#bt_ExportPart').click(function(){
        var urldata = '';
        $('input[@name=chkItem][@checked]').each(function(){
            urldata += $(this).val() + ',';
        })
        if(urldata != '')
        {
            return true;
        }
        else
        {
            alert("请选择要导出的订单");
            return false;
        }
	});
    
    $('#bt_print').show().click(function(){
        window.open('OrderListPrint.aspx','print','top=0,left=0, toolbar=no, menubar=no,resizable=yes,location=no,status=no');
        return false;
    });    
    
    $("#txtStartTime").datepicker().click(function(){$(this).blur()});
    $("#txtEndTime").datepicker().click(function(){$(this).blur()});
    
    $('#ddlTopAreas').change(function(){
        $('#ddlSubAreas').remove();$('#ddlThirdAreas').remove();
        if($(this).val() == '0'){return false;};
        $.ajax({
            url:'OrderList.aspx?Nocopyright=1&type=ajax&Action=GetSubArea&ParentID=' + $('#ddlTopAreas').val(),
            cache:false,
            success:function(data){
                if(!checkLoginStatus(data)){return false;}//是否要重新登陆
                var objSubArea = $('<select id="ddlSubAreas" name="ddlSubAreas" class="searchvalue"></select>');
                objSubArea.html(data);
                objSubArea.insertAfter($('#ddlTopAreas'));
                objSubArea.change(function(){
                    $('#ddlThirdAreas').remove();
                    if($(this).val() == '0'){return false;};
                    $.ajax({
                        url:'OrderList.aspx?Nocopyright=1&type=ajax&Action=GetSubArea&ParentID=' + $('#ddlSubAreas').val(),
                        cache:false,
                        success:function(data){
                            if(!checkLoginStatus(data)){return false;}//是否要重新登陆
                            var objthirdarea = $('<select id="ddlThirdAreas" name="ddlThirdAreas" class="searchvalue"></select>');
                            objthirdarea.html(data).insertAfter($('#ddlSubAreas'))
                        },error:function(){}
                    });
                });
            },error:function(){alert('get address error');}
        });
    });
    
    //高级搜索
    $('#btnSearchAdv').toggle(function(){
        $('.searchDetails').show();
        $(this).val('关闭');
    },function(){
        $('.searchDetails').hide();
        $(this).val('高级搜索');
    });
    
    
    
})//end ready
    


function BindList(){
    searchUrl = '&PageSize=' + PageSize + '&Page=' + CurrentPage;
    searchUrl += '&ustatus=' + $('#ustatus').val() + '&adminID=' + $('#adminID').val() + '&Status=' + $('#selStatus').val() + '&ShipType=' + $('#selShipType').val() + '&OrderMethod=' + $('#selAddMethod').val();
    searchUrl += '&PayType=' + $('#ddlPayType').val() + '&DateFrom=' + $('#txtStartTime').val() + '&DateTo=' + $('#txtEndTime').val() + '&KeyType=' + $('#ddlKeyType').val() + '&Keywords=' + escape($('#txtKeyword').val());
    var addressID = '';
    if($('#ddlTopAreas')[0] && $('#ddlTopAreas').val() != '0'){addressID += $('#ddlTopAreas').val();}
    if($('#ddlSubAreas')[0] && $('#ddlSubAreas').val() != '0'){addressID += ',' + $('#ddlSubAreas').val();}
    if($('#ddlThirdAreas')[0] && $('#ddlThirdAreas').val() != '0'){addressID += ',' + $('#ddlSubAreas').val();}
    searchUrl += '&AddressID=' + addressID;
    $.ajax({
        type:'post',
        url:'OrderList.aspx?NoCopyRight=1&type=ajax&Action=BindOrderList&Page=' + CurrentPage,
        data:$('.searchvalue').serialize(),
        dataType:'json',
        cache:false,
        success:function(msg){
			var data = msg.Orders;
            var managerSelect = msg.managers;   //<select name='managers'><option value='1'>admin1</option></select>
            //权限
			var orderAssign = msg.power.OrderAssign == 'true' ? true : false;
            var orderDelete = msg.power.OrderDelete == 'true' ? true : false;
            if(!orderAssign){
                $('#template').find('#Manager').hide();$('#btnUpdateManagers').hide();
                $('#listhead').find('th.manager').hide();
            }else{
                $('#template').find('#Manager').show();$('#btnUpdateManagers').show();
                $('#listhead').find('th.manager').show();
            };
            if(!orderDelete){
                $('#template').find('#Delete').hide();$('#btnDelete').hide();
                $('#listhead').find('th.delete').hide();
                $('.c16').css('text-align','left');
            }else{
                $('#template').find('#Delete').show();$('#btnDelete').show();
                $('#listhead').find('th.delete').show();
            };
            
            $('input[@name=chkAll]').attr('checked','');
            $('tr:gt(0)','#datas').remove();

            $.each(data,function(i,n){
                var row = $('#template').clone().show();
                row.mouseover(function(){$(this).addClass('on')}).mouseout(function(){$(this).removeClass('on')}); //将复制的行显示出来并添加样式
                row.find('#CheckBox').html('<input type="checkbox" name="chkItem" value="' + n.OrderID + '" />');//checkbox
                if(orderAssign){
                    row.find('#Manager').html(managerSelect).find('select').attr('id','manager_'+n.OrderID).change(function(){CheckOn($(this));}).find('option[@value=' + n.LastModify + ']').attr('selected','selected');//跟单员
                }
                row.find('#SupplierID').text(n.SupplierID);
                row.find('#OrderNo').html(n.OrderNo).addClass("hand").click(function(){
					$('#ShowOrderProduct').popup({width:'60%',height:'80%',popupHead:'ShowOrderProductHead',btnClose:'ShowOrderProductClose'});
					$.ajax({                          
                           url:'OrderList.aspx?NoCopyRight=1&type=ajax&Action=GetOrderProducts&OrderID='+n.OrderID,
                           async:false,
                           cache:false,
                           success:function(data){if(!checkLoginStatus(data)){return false;};
                           var arrData = data.split("@");
                           $('#span_Product').html(arrData[0]);
                           },
                           error:function(){alert('error');}
                      });
                });
                row.find('#OrderTime').html(n.OrderTime);
                row.find('#ProductPrice').html(Number(n.ProductPrice).toFixed(2));
                row.find('#ShipPrice').html(Number(n.ShipPrice).toFixed(2));
                row.find('#TotalPrice').html(Number(n.TotalPrice).toFixed(2));
                row.find('#AdvancePayment').html(Number(n.AdvancePayment).toFixed(2));
                row.find('#NeedPay').html(Number(n.NeedPay).toFixed(2));
                row.find('#ShippingType').html(n.ShippingType);
                row.find('#PayType').html(GetPayType(n.PayType));
                row.find('#MemberName').html(n.MemberName);
                row.find('#ReceiverName').html(n.ReceiverName);
                row.find('#ReceiverPhone').html((n.ReceiverPhone.split(',')[0] != undefined ? n.ReceiverPhone.split(',')[0] : '') +(n.ReceiverPhone.split(',')[1] != undefined ?  '<br />' + n.ReceiverPhone.split(',')[1] : '')+(n.ReceiverMobile!=undefined ? '<br/>'+n.ReceiverMobile:''));
                row.find('#Status').html(GetStatusString(n.PayType,n.Status));//状态
                row.find('#Modify').html('<a href="OrderModify.aspx?from=list&OrderID=' + n.OrderID + '">管理</a>').find('a').click(function(){ShowModify($(this).attr('href'));return false;});//修改
                if(orderDelete){
                    row.find('#Delete').html('<span style="cursor:pointer">删除</span>').find('span').click(function(){if(confirm('确定要删除吗?')){DeleteOrder(n.OrderID);};});//删除
                }

                row.attr('id','ready_' + n.OrderID);//id=ready_OrderID
                $('#datas').append(row);
                
            })//end each
            //如果是firefox,将过长的订单号换行
            if($.browser.mozilla){
                $('tr:gt(0)','#datas').each(function(){
                    var strOrderNo = $(this).find('#OrderNo').html();
                    $(this).find('#OrderNo').html(strOrderNo.BreakWord(15));
                })
            }
            
            //分页
            $('.sub_container_page').show();
            var pagerStyle = "flickr";//jPagerBar样式
            ShowPageBar("pageDataList1_Pager",//[containerId]
               "OrderList.aspx",//[url]
               {style:pagerStyle,mark:"pageDataList1Mark",
               totalCount:msg.totalCount,showPageNumber:3,pageCount:PageSize,currentPageIndex:CurrentPage,noRecordTip:" 没有记录",preWord:"上一页",nextWord:"下一页",
               onclick:"CurrentPage={pageindex};BindList();return false;"}//[attr]
            );//分页结束
            
        },//end success
        error:function(XMLHttpRequest,textStatus){
            if(textStatus=='parsererror'){
                alert('身份已过期,请重新登陆!')
            }else if(textStatus == 'error'){
                alert('查询条件有误');
            };
        }//end error
    });//end ajax
}

//点击修改,显示修改商品的页面
function ShowModify(href){
    $('#frmModify').attr('src',href + searchUrl+'&ran='+Math.random()).css('height',$(window.parent.frames.right).height()).show().siblings().hide();
}

//删除订单(一次可删除多个订单)
function DeleteOrder(orderID){
    $.ajax({
        url:'OrderList.aspx?type=ajax&Action=DeleteOrdersAjax&IDs='+orderID + '&NoCopyRight=1',
        cache:false,
        success:function(data){
            if(!checkLoginStatus(data)){return false;}//是否要重新登陆
            if(data==-1){
                alert("你没有删除订单的权限");
            }else if(data==0){
                alert('订单已删除');
                BindList();
            }else if(data==1){
                alert('订单删除失败');
            };
        },error:function(){alert('error');}
    });
};

function CheckOn(obj){
    obj.parent().siblings('td[@id=CheckBox]').find('input[@name=chkItem]').attr('checked','true');
}

//去掉字符串前后空格
String.prototype.Trim = function() { 
    return this.replace(/(^\s*)|(\s*$)/g, ""); 
}

//将过长的字符换行(firefox不能自动换行) 参数maxLength:每行显示的最大字符数量
String.prototype.BreakWord = function(intLen){
    var strContent=this; 
    var strTemp="";
    while(strContent.length>intLen){
    strTemp+=strContent.substr(0,intLen)+"<br />"; 
    strContent=strContent.substr(intLen,strContent.length); 
    }
    strTemp+=strContent;
    return strTemp;
}

//获取URL中参数
function getQueryStringRegExp(name){    
	var reg = new RegExp("(^|\\?|&)"+ name +"=([^&]*)(\\s|&|$)", "i");
	if (reg.test(location.href))
		return unescape(RegExp.$2.replace(/\+/g, " "));
		return "";
}

function checkLoginStatus(data){
    var result = true;
    if(data.indexOf('<!DOCTYPE') != -1){
        result = false;
        alert('身份已过期,请重新登陆!');
    }
    return result;
}


function GetStatusString(payType,status)
{
	var str = "";
	
	switch(payType)
	{
		case '1':
			switch(status)
			{
				case '0':
					str = "未付款";
					break;
				case '1':
					str = "部分付款";
					break;
				case '2':
					str = "已付款";
					break;
				case '3':
					str = "已确认";
					break;
				case '4':
					str = "正在配货";
					break;
				case '5':
					str = "部分发货";
					break;
				case '6':
					str = "已发货";
					break;
				case '7':
					str = "已签收";
					break;
                case '8':
                    str = "等待退款";
                    break;
                case '9':
                    str = "已退款";
                    break;
                case '10':
                    str = "交易取消";
                    break;
                case '11':
                    str = "交易失败";
                    break;
                case '12':
                    str = "交易完成";
			}
			break;
		case '2':
			switch(status)
			{
				case '0':
					str = "未付款";
					break;
				case '1':
					str = "部分付款";
					break;
				case '2':
					str = "已付款";
					break;
				case '3':
					str = "已确认";
					break;
				case '4':
					str = "正在配货";
					break;
				case '5':
					str = "部分发货";
					break;
				case '6':
					str = "已发货";
					break;
				case '7':
					str = "已签收";
					break;
                case '8':
                    str = "等待退款";
                    break;
                case '9':
                    str = "已退款";
                    break;
                case '10':
                    str = "交易取消";
                    break;
                case '11':
                    str = "交易失败";
                    break;
                case '12':
                    str = "交易完成";
			}
			break;
		case '3':
			switch(status)
			{
				case '0':
					str = "未付款";
					break;
				case '1':
					str = "部分付款";
					break;
				case '2':
					str = "已付款";
					break;
				case '3':
					str = "已确认";
					break;
				case '4':
					str = "正在配货";
					break;
				case '5':
					str = "部分发货";
					break;
				case '6':
					str = "已发货";
					break;
				case '7':
					str = "已签收";
					break;
                case '8':
                    str = "等待退款";
                    break;
                case '9':
                    str = "已退款";
                    break;
                case '10':
                    str = "交易取消";
                    break;
                case '11':
                    str = "交易失败";
                    break;
                case '12':
                    str = "交易完成";
			}
			break;
		case '4':
			switch(status)
			{
				case '0':
					str = "未付款";
					break;
				case '1':
					str = "部分付款";
					break;
				case '2':
					str = "已付款";
					break;
				case '3':
					str = "已确认";
					break;
				case '4':
					str = "正在配货";
					break;
				case '5':
					str = "部分发货";
					break;
				case '6':
					str = "已发货";
					break;
				case '7':
					str = "已签收";
					break;
                case '8':
                    str = "等待退款";
                    break;
                case '9':
                    str = "已退款";
                    break;
                case '10':
                    str = "交易取消";
                    break;
                case '11':
                    str = "交易失败";
                    break;
                case '12':
                    str = "交易完成";
			}
			break;
		case '5': //--货到付款
			
			switch(status)
			{
				case '0':
					str = "未付款";
					break;
				case '1':
					str = "部分付款";
					break;
				case '2':
					str = "未确认";					
					break;
				case '3':
					str = "已确认";
					break;
				case '4':
					str = "正在配货";
					break;
				case '5':
					str = "部分发货";
					break;
				case '6':
					str = "已发货";
					break;
				case '7':
					str = "已签收";
					break;
                case '8':
                    str = "等待退款";
                    break;
                case '9':
                    str = "已退款";
                    break;
                case '10':
                    str = "交易取消";
                    break;
                case '11':
                    str = "交易失败";
                    break;
                case '12':
                    str = "交易完成";
                    break;
				default:
					break;
			}
			break;
		case '6': //--门店自提
			switch(status)
			{
				case '0':
					str = "未付款";
					break;
				case '1':
					str = "部分付款";
					break;
				case '2':
					str = "未确认";
					break;
				case '3':
					str = "已确认";
					break;
				case '4':
					str = "正在配货";
					break;
				case '5':
					str = "部分发货";
					break;
				case '6':
					str = "已发货";
					break;
				case '7':
					str = "已签收";
					break;
                case '8':
                    str = "等待退款";
                    break;
                case '9':
                    str = "已退款";
                    break;
                case '10':
                    str = "交易取消";
                    break;
                case '11':
                    str = "交易失败";
                    break;
                case '12':
                    str = "交易完成";
                    break;
				default:
					break;
			}
			break;
		default: //--团购拍卖用的着
			switch(status)
			{
				case '0':
					str = "未付款";
					break;
				case '1':
					str = "部分付款";
					break;
				case '2':
					str = "未确认";
					break;
				case '3':
					str = "已确认";
					break;
				case '4':
					str = "正在配货";
					break;
				case '5':
					str = "部分发货";
					break;
				case '6':
					str = "已发货";
					break;
				case '7':
					str = "已签收";
					break;
//				case '8':
//					str = "已退单";
//					break;
//				case '9':
//					str = "已退款";
//					break;
//				case '10':
//					str = "已作废";
//					break;
//				case '12':
//					str = "已归档";
                case '8':
                    str = "等待退款";
                    break;
                case '9':
                    str = "已退款";
                    break;
                case '10':
                    str = "交易取消";
                    break;
                case '11':
                    str = "交易失败";
                    break;
                case '12':
                    str = "交易完成";
					break;
				default:
					break;
			}
			break;
	}
	return str;
}
//支付类型
function GetPayType(paytype){
    result = '';
    switch(paytype){
        case '1':
            result = '在线支付';
            break;
        case '2':
            result = '银行卡转账';
            break;
        case '3':
            result = '邮局汇款';
            break;
        case '4':
            result = '公司转账';
            break;
        case '5':
            result = '货到付款';
            break;
        case '6':
            result = '门店自提';
            break;
    };
    return result;
};