var g_user_id="";
var g_user_name="";
var g_duty_role = 0;
var g_token = "";
var g_cur_item = "";
Date.prototype.format = function(fmt) { 
     var o = { 
        "M+" : this.getMonth()+1,                 //月份 
        "d+" : this.getDate(),                    //日 
        "h+" : this.getHours(),                   //小时 
        "m+" : this.getMinutes(),                 //分 
        "s+" : this.getSeconds(),                 //秒 
        "q+" : Math.floor((this.getMonth()+3)/3), //季度 
        "S"  : this.getMilliseconds()             //毫秒 
    }; 
    if(/(y+)/.test(fmt)) {
            fmt=fmt.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length)); 
    }
     for(var k in o) {
        if(new RegExp("("+ k +")").test(fmt)){
             fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));
         }
     }
    return fmt; 
} 


$(function ()
{
	$(".dialog").mousedown(function(e)
	{
		var endx=0;
		var endy=0;
		//获取div的初始位置，要注意的是需要转整型，因为获取到值带px
		var left= parseInt($("#show_data").css("left"));
		var top = parseInt($("#show_data").css("top"));
		//获取鼠标按下时的坐标，区别于下面的es.pageX,es.pageY
		var downx=e.pageX;
		var downy=e.pageY;  //pageY的y要大写，必须大写！！
		// 鼠标按下时给div挂事件
		$(document).bind("mousemove",function(es)
		{
			//es.pageX,es.pageY:获取鼠标移动后的坐标
			var endx = es.pageX-downx+left;  //计算div的最终位置
			var endy = es.pageY-downy+top;
			$(".dialog").css("left",endx+"px");
			$(".dialog").css("top",endy+"px");
		})
	})
})

$(function ()
{
	$(".dialog").mouseup(function()
	{
		//鼠标弹起时给div取消事件
		$(document).unbind("mousemove")
	})
})


function get_opt_val(opt_name)
{
	return $("input[name='" + opt_name + "']:checked").val();
}

function get_sel_val(sel_name)
{
	return $("#" + sel_name).val();
}

function get_token()
{
	var token = g_token;
	if(token == "")
	{
		token = window.parent.document.getElementById("token").value;
	}
	return token;
}

//导出---------------------------------------------------

var idTmr;
function getExplorer() {
	var explorer = window.navigator.userAgent;
	//ie
	if (!!window.ActiveXObject || "ActiveXObject" in window) {
		return 'ie';
	}
		//firefox
	else if (explorer.indexOf("Firefox") >= 0) {
		return 'Firefox';
	}
		//Chrome
	else if (explorer.indexOf("Chrome") >= 0) {
		return 'Chrome';
	}
		//Opera
	else if (explorer.indexOf("Opera") >= 0) {
		return 'Opera';
	}
		//Safari
	else if (explorer.indexOf("Safari") >= 0) {
		return 'Safari';
	}
}

function exportExcel(tableid, fileName) {
	if (getExplorer() == 'ie') {
		try {
			var objTb = $("#" + tableid + "");
			myWindow = window.open('', '', 'width=800px,height=400px');
			myWindow.document.write("<html><head><link rel='stylesheet' type='text/css' href='css/jsonTbl.css' /></head><body><table id='jsonTbl'>" + objTb.html() + "</table></body></html>");
			myWindow.document.execCommand('saveas', '', fileName + ".xls");
			myWindow.close();
		} catch (e) {
			//print("Nested catch caught " + e);
		} finally {
			idTmr = window.setInterval("Cleanup();", 1);
		}

	}
	else {
		tableToExcel(tableid, fileName)
	}
}
function Cleanup() {
	window.clearInterval(idTmr);
	CollectGarbage();
}
var tableToExcel = (function () {
	var uri = 'data:application/vnd.ms-excel;base64,',
			template = '<html><head><meta charset="UTF-8"></head><body><table>{table}</table></body></html>',
			base64 = function (s) { return window.btoa(unescape(encodeURIComponent(s))) },
			format = function (s, c) {
				return s.replace(/{(\w+)}/g,
						function (m, p) { return c[p]; })
			}
	return function (table, fileName) {
		if (!table.nodeType) table = document.getElementById(table)
		var ctx = { worksheet: fileName || fileName, table: table.innerHTML }
		window.location.href = uri + base64(format(template, ctx))
	}
})()

function sum_col(tb_name, col)
{
	var arr=[];
    $("#" + tb_name +" tr").each(function(){
        arr.push($(this).find("td").eq(col).html());
    });
    return eval(arr.join("+"));
}

function sum_cols(tb_name, col, col_cnt)
{
	var sum_data = new Array();
	var fSum = 0;
	var i = 1;
	var tr = "<tr>"
			+"<th>总计</th>";
	for(i=1; i<col; i++)
	{
		tr += "<th>&nbsp;</th>"
	}
	for(i=col; i<col+col_cnt; i++)
	{
		fSum = sum_col(tb_name, i);
		tr += "<th>" + fSum + "</th>";
		if(i<col+col_cnt-1)
		{
			sum_data.push(fSum);
		}
	}
	tr += "</tr>";
	$('#'+tb_name).append(tr);
	return sum_data;
}

function rpt_chart(chart_name, y_title, c_data)
{
	var rpt_div = document.getElementById(chart_name);
	var chart = echarts.init(rpt_div);
	var opt =
	{
		title: {
			text: ''
		},
		animation:false,
		tooltip: {},
		toolbox: {
			show : true,
			feature : {
				mark : {show: true},
				saveAsImage : {show: true}
			}
		},
		grid:{
			width:'1000',
			left:'5%',
			right:'5%'
		},

		legend: {
			data:['yedu']
		},
		xAxis: {
			data: ['一月','二月','三月','四月','五月','六月','七月','八月','九月','十月','十一月','十二月']
		},
		yAxis : [
		{
			type : 'value',
			name: y_title,
			position: 'left',
			axisLabel : {formatter: '{value}'}
		},			
		],
		series: [
		{
			name: y_title,
			type: 'bar',
			data: c_data
//			data:[1,2,3,4,5,6,7,8,9,10,11,12]
		},
		]
	};
	chart.setOption(opt);
	$(window).resize(function() {
		//重置容器高宽
		chart.resize();
	})
}

function get_user_id()
{
	var user_id = g_user_id;
	if(user_id == "")
	{
		user_id = window.parent.document.getElementById("user_id").value;
	}
	return user_id;
}

function get_user_name()
{
	var user_name = g_user_name;
	if(user_name == "")
	{
		user_name = window.parent.document.getElementById("user_name").value;
	}
	return user_name;
}

function show_years(cboYear, years)
{
	var cur_day = new Date(); 
	var year = cur_day.getFullYear();
	var selected = " selected ";
	for(var i=0; i<years; i++)
	{
		$("#" + cboYear).append("<option value='"+(year-i)+"'" + selected + ">"+(year-i)+"</option>");
		selected = "";
	}	
}

function show_supply(sel_name, json)
{
	if (!json)
	{
		return;
	}	
	data = json.data;
	if(!data || data.length == 0)
	{
		return;
	}
	var selected = " selected ";
	for (var i = 0; i < data.length; i++) 
	{
		$("#" + sel_name).append("<option value='"+data[i]["id"]+"'" + selected + ">"+data[i]["ent_name"]+"</option>");
		selected = "";
	}
}

function get_supply_json(tp) 
{
	var token = get_token();
    var json = {
        "service": "web_bom/list_supply",
		"token": token,
		"params":
		{
			"type": tp
		}
    };
    return json;
}

function list_supply(sel_name, tp)
{
	$.ajax(
	{
　　　　url : g_url, 　   <!-- url  :请求地址 -->  
　　　　type : 'post',　　　　　　　　<!--type ：请求类型:post/get --> 
		xhrFields: {
                withCredentials: true // 这里设置了withCredentials
            },
		async:false,
　　　　data : JSON.stringify(get_supply_json(tp)),
	
	　　success:function(data)
		{
			var json = eval('(' + data + ')');
			show_supply(sel_name,json);
			
	　　},
		error:function (request, status, error)
		{
//			alert(error);
	　　}
	});
}

function show_date2()
{
	var cur_day = new Date(); 
	var start_day = new Date(); 
	start_day.setDate(cur_day.getDate() - 30);
	$("#s_day").val(start_day.format("yyyy-MM-dd"));
	$("#e_day").val(cur_day.format("yyyy-MM-dd"));
}

function get_max(arr)
{
	return Math.max.apply(null, arr);
}

function get_min(arr)
{
	return Math.min.apply(null, arr);
}

function date_part(tm_string)
{
	var pos = tm_string.indexOf(' ');
	if(pos > 0)
	{
		tm_string = tm_string.substring(0, pos);
	}
	return tm_string;
}

function get_date(tm_string)
{
	tm_string = tm_string.replace(/-/g, '/'); // "2010/08/01";
	return new Date(date_part(tm_string));	
}

function get_cur_date()
{
	var cur_day = new Date(); 
	return get_date(cur_day.format("yyyy-MM-dd"));
}

function get_cur_time_str()
{
	var cur_day = new Date(); 
	return cur_day.format("yyyy-MM-dd hh:mm:ss");
}

function get_cur_date_str()
{
	var cur_day = new Date(); 
	return cur_day.format("yyyy-MM-dd");
}

function get_days(start_time, end_time)
{
	var days = end_time - start_time;
	return days / (24*3600*1000) + 1;
}

function get_cur_percent(start_time, end_time)
{
	var total_days = get_days(start_time, end_time);
	var pass_days = get_days(start_time, get_cur_date());
//	alert(total_days + "," + pass_days);
	if(total_days <= 0.00001)
	{
		return 0.0;
	}
	return pass_days * 100.0 / total_days;
}

function show_src(src, sel_id)
{
	if(g_cur_item !="")
	{
		$("#"+g_cur_item).removeClass('layui-this');
	}
	$('#main').attr('src', src);
	$("#"+sel_id).addClass('layui-this');
	g_cur_item = sel_id;
}

function close_dlg(dlg)
{
	$(dlg).css("display", "none");
}

function show_login(json)
{
	if (!json)
	{
		alert("登录失败");
		return;
	}	
	data = json.data;
	if(!data || data.length == 0)
	{
		alert("登录失败");
		return;
	}

	g_token = json.token;
	g_user_id = data[0]["id"];
	g_user_name = data[0]["ent_name"];
	var co_stock = data[0]["co_stock"];
	var co_attach = data[0]["co_attach"];
	var co_bom = data[0]["co_bom"];
	$("#token").val(g_token);
	$("#user_id").val(g_user_id);
	$("#user_name").val(g_user_name);
	$("#user_login").css("display", "none");
	$("#role_head").empty();
	var first_url = "";
	var sel_id = "";	

	$("#role_head").append("<li class='layui-nav-item' id='purchase'><a href='#' onclick=\"show_src('purchase.html', 'purchase')\">我的订单</a></li>");
	if(co_stock == 1)
	{
		$("#role_head").append("<li class='layui-nav-item' id='purchase_stock'><a href='#' onclick=\"show_src('purchase_stock.html', 'purchase_stock')\">我的库存</a></li>");
	}
	if(co_attach == 1)
	{
		$("#role_head").append("<li class='layui-nav-item' id='purchase_file'><a href='#' onclick=\"show_src('purchase_file.html','purchase_file')\">我的文件</a></li>");
	}
	if(co_bom == 1)
	{
		$("#role_head").append("<li class='layui-nav-item' id='purchase_bom'><a href='#' onclick=\"show_src('purchase_bom.html','purchase_bom')\">我的BOM</a></li>");
	}
	$("#role_head").append("<li class='layui-nav-item' id='purchase_rpt'><a href='#' onclick=\"show_src('purchase_rpt.html', 'purchase_rpt')\">订单统计</a></li>");
	if(first_url == "")
	{
		first_url = "purchase.html";
		sel_id = "purchase";
	}
	
	if(first_url != "")
	{
		show_src(first_url, sel_id);
		g_cur_item = sel_id;
	}
}

function GetLoginJson() 
{
    var json = {
        "login":
		{
			"user": $("#userName").val(),
			"pwd": $("#pwd").val()
		}
    };
    return json;
}

function login() 
{
	$.ajax(
	{
　　　　url : g_url, 　   <!-- url  :请求地址 -->  
　　　　type : 'post',　　　　　　　　<!--type ：请求类型:post/get --> 
		xhrFields: {
                withCredentials: true // 这里设置了withCredentials
            },
		async:false,
　　　　data : JSON.stringify(GetLoginJson()),
	
	　　success:function(data)
		{
			var json = eval('(' + data + ')');
			show_login(json);
//				token_str = json.token;
//				document.getElementById('messages').innerHTML  += '<br />' + data ;
			
	　　},
		error:function (request, status, error)
		{
//			alert(error);
	　　}
	});
}