var divHeight = ""; // 查询面板高度
var dataGridWidth = ""; // 查询面板宽度
var dataGridHeight = "";
var bodyWidth = 0;
var bodyHeight = 0;
var editor1 = null;
var operation = "";
var serverIp = "";
var addWinWidth = 0;  //新增窗口宽度
var addWinHeight = 0;  //新增窗口高度

//扩展Date的format方法
Date.prototype.format = function (format) {
    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(format)) {
        format = format.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    }
    for (var k in o) {
        if (new RegExp("(" + k + ")").test(format)) {
            format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));
        }
    }
    return format;
};

$(function() {
    $.ajaxSetup({
        cache:false
    });
	divHeight = $("#queryDiv").height();
	dataGridWidth = $("#queryDiv").width();
	dataGridHeight = divHeight + 28;
	
	bodyWidth = document.body.clientWidth;
	bodyHeight = document.documentElement.clientHeight;
	addWinWidth = (bodyWidth/100)*80;
	addWinHeight = (addWinWidth/16)*9;
	
	$("#addNewsWinId").window('close');
	$("#exportWindow").window('close');
	$("#newsTypeId01").hide();
	$("#newsTypeId02").hide();

    initDataTable();
	serverIp = document.location.hostname;
	initInputWidth();

    initExportWindow();
})
function initExportWindow(){
    $(".dropable .ele .up").on("click",function(){
        $from = $(this).parent().parent();
        $to = $from.prev(".block");
        if($to.length>0){
            $to.insertAfter($from);
        }
    });
    $(".dropable .ele .down").on("click",function(){
        $from = $(this).parent().parent();
        $to = $from.next(".block");
        if($to.length>0){
            $to.insertBefore($from);
        }
    });
}
function exportExl(){
    var name = $("#query-name").val()
    var status = $("#query-status").combobox('getValue');
    var start = $("#query-start").datebox('getValue');
    var end = $("#query-end").datebox('getValue');
    var queryParams = null;

    var out ='';
    $(".dropable .block").each(function(){
        if ($(this).find("input").get(0).checked) {
            if (out.length>0) {
                out+=",";
            };
            out+=$(this).find(".ele-name").attr("val");
        };
    });
    console.log(out);

    name = encodeURI(encodeURI(name));
    location.href="/admin/business/registerManage/exporgExcel2?name="+name+"&status="+status+"&startDate="+start+"&endDate="+end
    +"&fields="+out;
}
function initDataTable(){
	var h = document.documentElement.clientHeight;
	$("#registersTable").datagrid({
		height : h - dataGridHeight,
		nowrap : true,
		striped : true,
		pagination : true,
		rownumbers : true,
		pageList : [15,20,30,40,50],
		autoRowHeight : false, 
		fitColumns : true,  
		title : "期数列表",
		url : '/admin/business/phaseManage/query',
		columns : [ [ {
			field : 'ck',
			title : 'id',
			width : 15, 
			checkbox : true
		}, {
            field : 'active',
            title : '是否启用',
            align : 'center',
            formatter:function(val,row){
                if(val||val=='true'){
                    return "&radic;";
                }else{
                    return "X";
                }
            },
            width : 10
        },{
			field : 'name',
			title : '名称',
			align : 'left',
			width : 20
		}, {
            field : 'time',
            title : '考试时间',
            align : 'center',
            formatter:function(val,row){
                if(val==''||val==null){
                    return "";
                }
                return new Date(parseInt(val)).format("yyyy-MM-dd");
            },
            width : 20
        }] ],
		onDblClickRow : function(index, row) { // 双击"任一行"执行
		},
		onLoadSuccess : function(data) { // 加载成功之后执行
		}
	});
}

/**
 * 初始化各输入框宽度
 */
function initInputWidth(){
    $("#titleId02").attr("style","width:"+ fixLongWidth()+"px");
	$("#labelId").attr("style","width:"+ fixLongWidth()+"px");
	$("#synopsisId").attr("style","width:"+ fixLongWidth()+"px;height:50px;");
	$("#sortId01").attr("style","width:"+ (fixShortWidth())+"px");
	$("#sourceId").attr("style","width:"+ (fixShortWidth())+"px");
	$("#titleId00").attr("style","width:"+ (fixShortWidth())+"px");
}
 
//查询
function queryData() {
	var name = $("#query-name").val();
	var queryParams = null;

    $("#registersTable").datagrid({
        queryParams : {
            name : name
        }
    });
}
//清空查询条件
function clearQueryForm(){
	$("#queryFormId").form('clear');
}
 
//打开新增窗口
function openAddWin(){
	initInputWidth();
    $('#newsForm')[0].reset();

    operation = "add";
	$("#main_area").height(addWinHeight);
	$("#addNewsWinId").window({
		title : '新增期数信息',
		width : addWinWidth,
		height : addWinHeight, 
		left : (dataGridWidth - addWinWidth)/2,
		top : (bodyHeight - addWinHeight)/2,
		closable : true, // 否显示关闭按钮
		collapsible : false, // 是否显示折叠按钮
		minimizable : false, // 是否显示最小化按钮
		maximizable : false, // 是否显示最大化按钮
		close : true, // 初始是否关闭
		modal : true 
	});  
	imagePath = ""; 
	$("#newsForm").form('clear');
	$("#saveButton01").show();
	$("#addNewsWinId").window('open');
}
//打开导出窗口
function openExportWin(){
    $("#exportWindow").window({
        title : '选择导出信息',
        left : "10%",
        top : "10%",
        height : addWinHeight/5*4,
        width : addWinWidth*0.3,
        closable : true, // 否显示关闭按钮
        collapsible : false, // 是否显示折叠按钮
        minimizable : false, // 是否显示最小化按钮
        maximizable : false, // 是否显示最大化按钮
        close : true, // 初始是否关闭
        modal : true
    });
    $("#exportWindow").window('open');
}

function formatDateField(selector,val){
    console.log(val);
    if(new RegExp("^[0-9]+$").test(val)){
        var d = new Date(parseInt(val)).format("yyyy-MM-dd");
        $(selector).val(d);
        $(selector).datebox("setValue",d);
    }
}
//打开修改窗口  
function openEditWin(){
	initInputWidth();
	operation = "edit";
	var rows = $('#registersTable').datagrid('getSelections');
	if(rows.length == 1){
		var row = $('#registersTable').datagrid('getSelected');
		$.post("/admin/business/phaseManage/queryById/" + row.id, function(data) {
			$("#newsForm").form('load', data);
			//$('#eventDateId').datebox('setValue',timestampformat(data.eventDate));
            formatDateField("#date1",data.time);
            $("#main_area").height((bodyHeight/5)*4);
		});
        $("#addNewsWinId").window({
            title : '修改报名信息',
            width : addWinWidth,
            height : addWinHeight,
            left : (dataGridWidth - addWinWidth)/2,
            top : (bodyHeight - addWinHeight)/2,
            closable : true, // 否显示关闭按钮
            collapsible : false, // 是否显示折叠按钮
            minimizable : false, // 是否显示最小化按钮
            maximizable : false, // 是否显示最大化按钮
            close : true, // 初始是否关闭
            modal : true
        });
        $("#saveButton01").show();
        $("#addNewsWinId").window('open');
	}else {
		$.messager.alert('提示', '请选中一条记录', 'info');
	}
}

//保存数据
function saveData(){
	var url = "";
	if('add' == operation){
		url = "/admin/business/phaseManage/addOrUpdate?operate="+operation;
		$('#newsForm').form('submit',{
			url: url,
			onSubmit: function(){
				return $(this).form('validate');
			},
			success: function(data){
				var data = eval("("+data+")");
				if (data.flag){
					$.messager.alert('提示', data.info, 'ok');
					closeWindow();
					initDataTable();
				} else {
					$.messager.alert("提示",data.info,'error');
				}
			}
		});    
	}
	if('edit' == operation){
        console.log("dddd");
		var row = $('#registersTable').datagrid('getSelected');
		url = "/admin/business/phaseManage/addOrUpdate?operate="+ operation+"&id="+row.id;
		$('#newsForm').form('submit',{
			url: url,
			onSubmit: function(){
				return $(this).form('validate');
			},
			success: function(data){
				var data = eval("("+data+")");
				if (data.flag){
					$.messager.alert('提示',data.info, 'ok');
					closeWindow();
					initDataTable();
				} else {
					$.messager.alert("提示",data.info,'error');
				}
			}
		}); 
	}
} 

function active(){
    var rows = $('#registersTable').datagrid('getSelections');
    if(rows.length == 1){
        var row = $('#registersTable').datagrid('getSelected');
        $.messager.confirm("启用","确定启用（每次报名只能启用一个）？",function(r){
            if (r){
                var postUrl = '/admin/business/phaseManage/active/'+row.id;
                $.post(postUrl,function(result){
                    if (result.flag){
                        $.messager.alert('提示',"启用成功！",'ok');
                        initDataTable();
                    } else {
                        $.messager.alert('提示',result.info,'error');
                        initDataTable();
                        return;
                    }
                },'json');
            }
        });
    }else{
        $.messager.alert('提示', '请选中一条记录', 'info');
    }
}
function inActive(){
    var rows = $('#registersTable').datagrid('getSelections');
    if (rows.length ==1 ){
        var row = $('#registersTable').datagrid('getSelected');
        $.messager.confirm("关闭","确定关闭（关闭之后报名页面不可访问）？",function(r){
            if (r){
                var postUrl = '/admin/business/phaseManage/inActive/'+row.id;
                $.post(postUrl,function(result){
                    if (result.flag){
                        $.messager.alert('提示',"关闭成功！",'ok');
                        initDataTable();
                    } else {
                        $.messager.alert('提示',result.info,'error');
                        initDataTable();
                        return;
                    }
                },'json');
            }
        });
    }else{
        $.messager.alert('提示', '请选中一条记录', 'info');
    }
}
//删除
function deleteNews(){
	var rows = $('#registersTable').datagrid('getSelections');
	if (rows.length !=0 ){
		var jsonIds = arrayTojson(rows);
		$.messager.confirm("删除","确定删除？",function(r){
			if (r){
				var postUrl = '/admin/business/phaseManage/deleteById';
				$.post(postUrl,{
					"ids":jsonIds},function(result){
					if (result.flag){
						$.messager.alert('提示',"数据删除成功！",'ok');
						initDataTable(); 
					} else {
						$.messager.alert('提示',"数据删除失败！",'error');
						initDataTable();
						return;
					}
				},'json');
			}
		});
	}else{ 
		$.messager.alert('提示', '请选中一条要删除记录', 'info');
	}
}
 
/**
 * id数组转换为json字符串
 */
function arrayTojson(arr) { 
	var jsonIds = "[";
	for ( var i = 0; i < arr.length; i++) {
		if (i == arr.length - 1) {
			jsonIds += arr[i].id;
		} else {
			jsonIds += arr[i].id + ",";
		}
	}
	jsonIds += "]";

	return jsonIds; 
}
//设置 long 宽度自适应   相对窗口
function fixLongWidth(){ 
	return addWinWidth*0.76;        
} 
           
//设置 short 宽度自适应
function fixShortWidth(){    
	return addWinWidth*0.284;            
} 
  
//关闭窗口
function closeWindow(){
	$("#addNewsWinId").window('close');
}

