var baseUrl = 'http://localhost:59628/';//'http://data.bailuntec.com'; //

var globalOrderSort='';
var globalOrderType = '';
var global_userid;
var global_username;
var jobs;
function OnlyTable(tableId, aoColumn, actionUrl, serverParams,tbParams,dataParam,pagesize) {
    var $btTable = $('#' + tableId);
    $btTable.bootstrapTable({
        url: actionUrl,
        //toolbar: "#toolbar",

        ajaxOptions:{
            beforeSend: function (xhr) {
                xhr.setRequestHeader('Authorization', $.cookie("BailunToken"))
            }
        },
        sidePagination: "server",//设置在哪进行分页，默认”client”，可选”server”，如果设置 “server”，则必须设置url或者重写ajax方法
        pagination: true,//底部工具栏是否显示分页条
        striped: true,//是否显示列表背景色
        mobileResponsive: true,
        showRefresh: false,//是否显示刷新按钮
        showColumns: false,//是否显示 字段支持隐藏的下拉选择
        showToggle: false,//是否显示试图2
        sortable: true,//是否允许排序
        search: false,//是否显示查询框
        showFooter: (tbParams == undefined ? false : tbParams.showfooter || false),
        fixedColumns: (dataParam == undefined || dataParam.fixedcol == undefined ? false : dataParam.fixedcol),
        fixedNumber: (dataParam == undefined || dataParam.fixedcolnum == undefined ? 0 : dataParam.fixedcolnum),
        formatLoadingMessage: function () {
            return "<img src='/img/loading.gif' />";
        },
        queryParams: function queryParams(params) {
            if (null != serverParams && "" != serverParams) {
                var dataObj = eval(serverParams);
                $.each(dataObj, function (idx, item) {
                    params[item.name] = item.value;
                    // params.push({ "name": item.name, "value": item.value });
                });
            }

            globalOrderSort = params.sort;
            globalOrderType = params.order;

            return params;
        },

        columns: aoColumn,//列表字段
        pageList: "[25, 50, 100,200]",
        pageSize: pagesize||25,
        paginationFirstText: "第一页",
        paginationPreText: "上一页",
        paginationNextText: "下一页",
        paginationLastText: "最后页",
        onLoadSuccess: function (data) {
            if (data != undefined && data.statusCode == '401') {
                parent.window.location = parent.window.location;
            }
            
            if (tbParams != undefined && tbParams.showCount) {
                //替换汇总行的相关列值
                var tr = $('.fixed-table-footer').find('tr');
                for (var c in aoColumn) {
                    var key = aoColumn[c].field;
                    if (aoColumn[c].iscount) {
                        for (var v in data.count_row) {
                            if (key == v) {
                                tr.find('td').eq(c).children('div').first().html(data.count_row[v]);
                                break;
                            }
                        }
                    }
                }
            }

            if (tbParams != undefined && tbParams.loadsuccess) {
                tbParams.loadsuccess(data);
            }
        }
    });

    return $btTable;
}

$.ListTable = function(tb,pageid,url,columns){
	if(tb==undefined)
	{
		alert('请填写表格id');
		return false;
	}
	
	if(url==undefined)
	{
		alert('请求的url不能为空！');
		return false;
	}
	
	if(columns.length<=0)
	{
		alert('列参数不能为空！');
		return;
	}
	
	if(url.indexOf('?')<0)
	{
		url+='?a=a';
	}
	
	$('#'+tb).html('');
	$('#'+pageid).html('');
	
	$.ajax({
		url: url+'&page=1&pagesize='+pagesize, //serverUrl+'SkuAutoTurn/List?order=asc&page=1&pagesize='+pagesize,
		type:'Get',
		data:{},
		success:function(data){
			formathead();
			
			formatColumn(data);
			
			//分页
			formatPage(data,pageid);
		},
		complete:function(){
			//alert('调用完成！');
		}
	})	
	
	function formatPage(data,pageid)
	{
		$('#'+pageid).jqPaginator({
			totalPages: data.pagecount,
			visiblePages: 10,
			currentPage: 1,
			first: '<li class="first"><a href="javascript:void(0);">首页<\/a><\/li>',
			prev: '<li class="prev"><a href="javascript:void(0);"><i class="arrow arrow2"><\/i>上一页<\/a><\/li>',
			next: '<li class="next"><a href="javascript:void(0);">下一页<i class="arrow arrow3"><\/i><\/a><\/li>',
			last: '<li class="last"><a href="javascript:void(0);">末页<\/a><\/li>',
			page: '<li class="page"><a href="javascript:void(0);">{{page}}<\/a><\/li>',
			onPageChange: function (num, type) {
				if(type!='init')
				{
					$.ajax({
						url:url+'&pagesize='+pagesize+'&page='+num,//serverUrl+'/SkuAutoTurn/List?order=asc&page='+num+'&pagesize='+pagesize,
						type:'Get',
						data:{},
						success:function(data){
							$('#'+tb).find('tbody').remove();
							formatColumn(data);
						},
						complete:function(){
							//alert('调用完成！');
						}
					})	
				}
			}
		});
	}
	
	function formathead()
	{
		//Add Header Begin
		var cols = columns;
		if(cols.length<=0)
		{
			alert('列参数不能为空！');
			return;
		}
		var thead='<thead><tr>';
		for(var i=0;i<cols.length;i++)
		{
			thead+=('<th>'+cols[i].title+'</th>');
		}
		thead+='</tr></thead>';
		
		$('#'+tb).append(thead);
		//End Add Header
	}
	
	function formatColumn(data)
	{
		var cols = columns;
		if(cols.length<=0)
		{
			alert('列参数不能为空！');
			return;
		}
		
		//Add Body
		var tbody='<tbody>';
		for(var i=0;i<data.rows.length;i++)
		{
			tbody+='<tr>';
			for(var c=0;c<cols.length;c++)
			{
				var rows = data.rows[i];
				$.each(rows,function(j){
					if(j==cols[c].field)
					{
						tbody+=('<td>'+rows[j]+'</td>');
					}
				})
			}
			tbody+='</tr>';
		}
		tbody+='</tbody>';
		$('#'+tb).append(tbody);
	}
	
}

$.submit = function (data) {
    if (data.url == undefined || data.url == "") {
        alert("url不能为空！");
        return
    }

    var load_index;
    $.ajax({
        url: data.url,
        type: data.type||'GET',
        data: data.paramData,
        contentType: data.contenttype ||'application/x-www-form-urlencoded',
        async: data.async||true,
        headers: { Authorization: $.cookie("BailunToken")},
        beforeSend: function (request) {
            if (!data.noloading)
            {
                //load_index = layer.load();
            }
        },
        success: function (result) {
            if (result != undefined && result.statusCode == '401') {
                parent.window.location = parent.window.location;
            }

            try {
                if (!data.noloading)
                {
                    //layer.close(load_index);
                }
            }
            catch (e) {

            }

            if (data.func) {
                data.func(result)
            } else {
                alert("提交成功！");
            }
        },
        complete: function () {
            try {
                if (!data.noloading)
                {
                    //layer.close(load_index);
                }
                
            }
            catch (e) {

            }
        }
    })
};

function layer_show(title, url, w, h) {
    if (title == null || title == '') {
        title = false;
    };
    if (url == null || url == '') {
        url = "404.html";
    };
    if (w == null || w == '') {
        w = '800px';
    };
    if (h == null || h == '') {
        h = ($(window).height() - 50) + 'px';
    };
    layer.open({
        type: 2,
        area: [w, h],
        fix: false, //不固定
        maxmin: true,
        shade: 0.4,
        title: title,
        content: url
    });
}

function layer_close() {
    var index = parent.layer.getFrameIndex(window.name);
    parent.layer.close(index);
}

function getUrlParam(name) {
	var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象
	var r = window.location.search.substr(1).match(reg);  //匹配目标参数
	if (r != null) return unescape(r[2]); return ''; //返回参数值
}

function showdetail(title, url) {
    layer_show(title, url, '90%', '90%');
}

function numFormat(num) {
    var res = num.toString().replace(/\d+/, function (n) { // 先提取整数部分
        return n.replace(/(\d)(?=(\d{3})+$)/g, function ($1) {
            return $1 + ",";
        });
    })
    return res;
}

function login() {
    var token = getUrlParam('token');

    if (token != '') {
        if (baseUrl.indexOf('bailuntec') >= 0) {
            $.cookie('BailunToken', token, { expires: 1, domain: 'bailuntec.com' });
            window.location = baseUrl;
        }
        else {
            $.cookie('BailunToken', token, { expires: 1, domain: 'localhost' });
            window.location = baseUrl;
        }
    }
    else {
        token = $.cookie('BailunToken');

        if (token == '' || token == undefined || token==null) {
            window.location = "http://sso.bailuntec.com/?returnUrl=" + baseUrl;
            return false;
        }
    }
}

function login_localhost() {
    var token = getUrlParam('token');

    if (token != '') {
        $.cookie('BailunToken', token, { expires: 1, domain: 'localhost' });
        window.location = 'http://localhost:59628/';
    }
    else {
        token = $.cookie('BailunToken');

        if (token == '' || token == undefined || token == null) {
            window.location = "http://sso.bailuntec.com/?returnUrl=http://localhost:59628/";
            return false;
        }
    }
}


function logout() {
    $.removeCookie('BailunToken');
    window.location = "http://sso.bailuntec.com/?returnUrl=" + baseUrl;
}
