var imagePath = "";
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;  //新增窗口高度
var languageType = "chinese";
//var status = ['报名成功','缴费成功','书籍发放','DC号','准考证打印','发票寄送','证书寄送'];
var subjectArray = [];
var statusArray = [];
var activePhase;
//var registerTypeArray = ['首次报名','补考报名','延考及恢复'];
var rows=[];

//扩展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() {
	divHeight = $("#queryDiv").height();
	dataGridWidth = $("#queryDiv").width();
	dataGridHeight = divHeight + 45;
	
	bodyWidth = document.body.clientWidth;
	bodyHeight = document.documentElement.clientHeight;
	addWinWidth = (bodyWidth/100)*80;
	addWinHeight = (addWinWidth/16)*9;
	//初始状态为关闭
	$("#addNewsWinId").window({closed:true});
	$("#exportWindow").window({closed:true});
	$("#editStatusWinId").window('close');
	$("#addEmailInfoWinId").window('close');
	$("#emailSendWinId").window('close');
	//初始状态是隐藏
	$("#newsTypeId01").hide();//无用
	$("#newsTypeId02").hide();
	//获得相应数据，在jsp中定义的JD
    //var statusData=JD.statusJson;
    var subjectData=JD.subjectJson;
    var statusData=JD.statusJson;
    //获得相应数据长度
    var length1 = 0;
    var length2 = 0;
    $.each(statusData,function(n,v){length1++});
    $.each(subjectData,function(n,v){length2++});
    statusArray = new Array(length1);
    subjectArray = new Array(length2);
    //根据相应数据长度以及值进行数组的赋值
    $.each(statusData,function(n,v){statusArray[n]= v.dataName;});
    $.each(subjectData,function(n,v){subjectArray[n]= v.dataName;});
    //初始化下来菜单用于增删改查数据
    $.each(JD.phases, function (n, v) {
        if (v.active) {
            activePhase = v.id;
        }
    });
    
    initDataTable();
	serverIp = document.location.hostname;
	initInputWidth();

    initExportWindow();

    $.each(subjectArray,function(n,v){
        var href = "/admin/business/registerManage/exporgExcel2?phase="+activePhase+"&flagExt=0&subject2=" +(n+6)+
            "&fields=submitTime,dcNumber,title,dateOfBirth,gender_en,name_en,company_en,address_en,country,phone,email,city_en,subject2,name,address,invoiceType,invoiceTitle";
        var html="<a href='"+href+"' class='exp-btn'>"+v+"</a>";
        $(".quick-export").append(html);
    })
});
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);
        }
    });
}
//导出为excel exportExl()
function exportExl(){
    var name = $("#query-name").val();
    var subject2 = $("#query-subject").datebox('getValue');
    var phase = $("#query-phase").datebox('getValue');
    var status2 = $("#query-status").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");
        };
    });
    name = encodeURI(encodeURI(name));
    location.href="/admin/business/registerManage/exporgExcel2?name="+name+"&subject2="+subject2+"&status2="+status2
    +"&fields="+out+"&flagExt=0&phase="+phase;
    $("#exportWindow").window('close');
}

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 : "延考恢复报名用户列表",
        queryParams : {
            phase:activePhase
        },
		url : '/admin/business/registerManage/queryAllRegisterInfo?flagExt=0',
		columns : [ [ {
			field : 'ck',
			title : 'id',
			width : 15, 
			checkbox : true
		},{
			field : 'name_en',
			title : '英文名',
			align : 'left',
			width : 20,
            formatter:function(val,row){
            	return "<a href=\"javascript:viewData("+row.id+")\">"+row.name_en+"</button>";
            }
		}, {
			field : 'name',
			title : '中文名',
			align : 'center',
			width : 30
		}, {
			field : 'subject2',
			title : '报名科目',
			align : 'center',
            formatter:function(val,row){
                return subjectArray[val-6];
            },
			width : 30
		}, {
            field : 'registerStatus2',
            title : '报名状态',
            align : 'center',
            formatter:function(val,row){
                return statusArray[val];
            },
            width : 30
        }, {
            field : 'email',
            title : '邮箱',
            align : 'center',
            width : 30
        }, {
            field : 'submitTime',
            title : '提交时间',
            align : 'center',
            formatter:function(val,row){
                if(val==''||val==null){
                    return "";
                }
                return new Date(parseInt(val)).format("yyyy-MM-dd hh:mm:ss");
            },
            width : 20
        }] ],
		onDblClickRow : function(index, row) { // 双击"任一行"执行
		},
		onLoadSuccess : function(data) { // 加载成功之后执行
		}
	});
}

function view(val,row){
    return "<a href=\"javascript:viewData("+row.id+")\">"+row.name_en+"</button>";
}
/**
 * 初始化各输入框宽度
 */
function initInputWidth(){
	$("#standby1Id").attr("style", "width:" + fixShortWidth() + "px"); 
	$("#name00Id").attr("style", "width:" + fixShortWidth() + "px");
	$("#nameId").attr("style", "width:" + fixShortWidth() + "px");
	$("#postId").attr("style", "width:" + fixShortWidth() + "px");
	$("#companyId").attr("style", "width:" + fixShortWidth() + "px");
	$("#company_enId").attr("style", "width:" + fixShortWidth() + "px");
	$("#addressId").attr("style", "width:" + fixShortWidth() + "px");
	$("#address_enId").attr("style", "width:" + fixShortWidth() + "px");
	$("#phoneId").attr("style", "width:" + fixShortWidth() + "px");
	$("#titleId").attr("style", "width:" + fixShortWidth() + "px");
	$("#mobileTelId").attr("style", "width:" + fixShortWidth() + "px");
	$("#phoneId").attr("style", "width:" + fixShortWidth() + "px");
	$("#emailId").attr("style", "width:" + fixShortWidth() + "px");
	$("#email_enId").attr("style", "width:" + fixShortWidth() + "px");
	$("#invoiceTitleId").attr("style", "width:" + fixShortWidth() + "px");
	$("#addressNameId").attr("style", "width:" + fixShortWidth() + "px");
	$("#telephoneId").attr("style", "width:" + fixShortWidth() + "px");
	$("#bankAddressId").attr("style", "width:" + fixShortWidth() + "px");
	$("#bankAccountId").attr("style", "width:" + fixShortWidth() + "px");
	$("#trTaxpayerNumId").attr("style", "width:" + fixShortWidth() + "px");
	$("#dcNumberId").attr("style", "width:" + fixShortWidth() + "px");
	$("#countryId").attr("style", "width:" + fixShortWidth() + "px");
	
	$("#city_enId").combobox({
		url : '/admin/metadataManage/getMetadatasList?dataType=encityType',
        valueField : 'id',
        textField : 'text',
        panelHeight:'auto',
        width : fixShortWidth()+4
	});
	$("#cityId").combobox({
		url : '/admin/metadataManage/getMetadatasList?dataType=cityType',
		valueField : 'id',
        textField : 'text',
        panelHeight:'auto',
        width : fixShortWidth()+4
	});
	$("#genderId").combobox({
		valueField : 'id',
        textField : 'text',
        panelHeight:'auto',
        width : fixShortWidth()+4
	});
	$("#gender_enId").combobox({
		valueField : 'id',
        textField : 'text',
        panelHeight:'auto',
        width : fixShortWidth()+4
	});
	$("#invoiceTypeId").combobox({
		url : '/admin/metadataManage/getMetadatasList?dataType=invoiceType',
		valueField : 'id',
        textField : 'text',
        panelHeight:'auto',
        width : fixShortWidth()+4
	});
	$("#genderId").combobox({
		url : '/admin/metadataManage/getMetadatasList?dataType=gender',
		valueField : 'id',
        textField : 'text',
        panelHeight:'auto',
        width : fixShortWidth()+4
	});
	$("#gender_enId").combobox({
		url : '/admin/metadataManage/getMetadatasList?dataType=engender',
		valueField : 'id',
        textField : 'text',
        panelHeight:'auto',
        width : fixShortWidth()+4
	});
	$("#payTimeId").datebox({
		width : fixShortWidth()+4,
		valueField : 'id',
		panelHeight:'auto',
        textField : 'text'
	});
	$("#date1").datebox({
		width : fixShortWidth()+4,
		valueField : 'id',
        textField : 'text'
	});
	$("#date2").datebox({
		width : fixShortWidth()+4,
		valueField : 'id',
        textField : 'text'
	});
	$("#appreciationTaxTypeId").combobox({
		width : fixShortWidth()+4,
		panelHeight:'auto'
	});
	$("#registerStatus2Id").combobox({
		width : fixShortWidth()+4,
		data:JD.statusJson,
        valueField : 'dataNameId',
        textField : 'dataName',
		panelHeight:'auto',
	});
	$("#registerStatusId00").combobox({
		width : fixShortWidth()+4,
		data:JD.statusJson,
        valueField : 'dataNameId',
        textField : 'dataName',
		panelHeight:'auto',
	});
	$("#registerStatus200Id").combobox({
		width : fixShortWidth()+4,
		data:JD.statusJson,
        valueField : 'dataNameId',
        textField : 'dataName',
		panelHeight:'auto',
	});
	$("#phaseId").combobox({
		data:JD.phases,
        valueField:'id',
        textField:'name',
        panelHeight:'auto',
        width : fixShortWidth()+4,
	})
	$("#subject2Id").combobox({
		data:JD.subjectJson,
        valueField : 'dataNameId',
        textField : 'dataName',
        panelHeight:'auto',
        width : fixShortWidth()+4,
	})
	$("#subject200Id").combobox({
		data:JD.subjectJson,
        valueField : 'dataNameId',
        textField : 'dataName',
        panelHeight:'auto',
        width : fixShortWidth()+4,
	})
	
	$("#emailSenderId").combobox({
		 width : fixLongWidth()+4,
		 panelHeight:'auto',
	})
	$("#emailTitleId").attr("style","width:" + (fixLongWidth()) + "px");
	$("#emailContentId").attr("style", "width:" + (fixLongWidth()) + "px");
}

//导出为excel exportExl()
function exportExl(){
    var name = $("#name00Id").val();
    var status2 = $("#registerStatus200Id").combobox('getValue');
    var phase = $("#phaseId").combobox('getValue');
    var subject2 = $("#subject200Id").combobox('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");
        };
    });
    name = encodeURI(encodeURI(name));
    location.href="/admin/business/registerManage/exporgExcel2?name="+name+"&subject2="+subject2+"&status2="+status2
    +"&fields="+out+"&flagExt=0&phase="+phase;
    $("#exportWindow").window('close');
}

//查询
function queryData() {
    var name = $("#name00Id").val();
    var status = $("#registerStatus200Id").combobox('getValue');
    var phase = $("#phaseId").combobox('getValue');
    var subject = $("#subject200Id").combobox('getValue');
    var queryParams = null;
    console.log(phase);
    $("#registersTable").datagrid({
        queryParams : {
            name : name,
            phase:phase,
            status2:status,
            subject2:subject
        }
    });
}

//清空查询条件
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 = ""; 
	$("#imageID").attr("src","../.."+imagePath+";width:30px;height:30px");
	$("#newsForm").form('clear');
	$("#saveButton01").show();
	$("#addOrUpdate").show();//显示DC号
	$("#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, // 是否显示最大化按钮
        modal : true
    });
    $("#exportWindow").window('open');
}

function formatDateField(selector,val){
    console.log(val);
    if(val!=''&&val!=undefined&&val!='undefined'){
        var d = new Date(parseInt(val));
        d.setTime(d.getTime() + 60*60*1000);
        $(selector).val(d.format("yyyy-MM-dd"));
        $(selector).datebox("setValue",d.format("yyyy-MM-dd"));
    }
}
//打开修改窗口  
function openEditWin(){
	initInputWidth();
	operation = "edit";
	var rows = $('#registersTable').datagrid('getSelections');
	if(rows.length == 1){
		var row = $('#registersTable').datagrid('getSelected');
		$.getJSON("/admin/business/registerManage/queryRegisterInfoById?registerInfo=" + row.id, function(data) {
			$("#newsForm").form('load', data);
			//$('#eventDateId').datebox('setValue',timestampformat(data.eventDate));
            formatDateField("#date1",data.birthday);
            formatDateField("#date2",data.dateOfBirth);
            $("#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();
        $("#addOrUpdate").show();//显示DC号
        $("#addNewsWinId").window('open');
	}else {
		$.messager.alert('提示', '请选中一条记录', 'info');
	}
}

//打开修改状态窗口
function openEditStatusWin(){
	rows = $('#registersTable').datagrid('getSelections');
	if(rows.length != 0){
		$("#editStatusWinId").window({
			title : '修改报名状态',
			width : addWinWidth/1.5,
			height : addWinHeight/3.5, 
			left : (dataGridWidth - addWinWidth),
			top : (bodyHeight - addWinHeight)*3,
			closable : true, // 否显示关闭按钮
			collapsible : false, // 是否显示折叠按钮
			minimizable : false, // 是否显示最小化按钮
			maximizable : false, // 是否显示最大化按钮
			close : true, // 初始是否关闭
			modal : true 
		});  
		$("#buttonId03").show();
		$("#buttonId04").show();
		$("#editStatusForm").form('clear');
		$("#editStatusWinId").window('open');
	}else {
		$.messager.alert('提示', '请选中要修改的记录', 'info');
	}
	
} 
//保存修改报名状态
function saveData2(){
	var jsonIds = arrayTojson(rows);
	var registerStatus=$('#registerStatusId00').combobox('getValue');
	var postUrl = '/admin/business/registerManage/updateStatus2';
	$.post(postUrl,{"ids":jsonIds,"registerStatus":registerStatus},function(result){
		if (result.flag){
			$.messager.alert('提示',"修改成功", 'ok');
			closeWindow2();
			initDataTable();
		} else {
			$.messager.alert("提示","修改失败",'error');
			return;
		}
	},'json');
} 

//打开查看窗口
function viewData(id){ 
	initInputWidth();
    $.getJSON("/admin/business/registerManage/queryRegisterInfoById?registerInfo=" + id, function(data) {
		$("#newsForm").form('load', data);
        formatDateField("#date1",data.birthday);
        formatDateField("#date2",data.dateOfBirth);
	});  
	$("#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").hide();
	$("#addNewsWinId").window('open');
}

//保存数据
function saveData(){
	var url = "";
	if('add' == operation){
		url = "/admin/business/registerManage/addOrUpdateRegisterInfo?operate="+operation+"&flagExt=0";
		$('#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();
                    queryData();
				} else {
					$.messager.alert("提示",data.info,'error');
				}
			}
		});    
	}
	if('edit' == operation){
        console.log("dddd");
		var row = $('#registersTable').datagrid('getSelected');
		url = "/admin/business/registerManage/addOrUpdateRegisterInfo?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();
                    queryData();
				} else {
					$.messager.alert("提示",data.info,'error');
				}
			}
		}); 
	}
} 

//删除
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/registerManage/deleteByIds';
				$.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; 
}

//打开邮件发送窗口
function openEmailWin() {
	rows = $('#registersTable').datagrid('getSelections');
	if (rows.length !=0 ){
		$("#main_area").height(addWinHeight);
		$("#addEmailInfoWinId").window({
			title : '新增邮件信息',
			resizable : false,
			width : addWinWidth,
			height : addWinHeight / 2,
			left : (dataGridWidth - addWinWidth) / 2,
			top : (bodyHeight - addWinHeight / 2) / 2,
			closable : true, // 否显示关闭按钮
			collapsible : false, // 是否显示折叠按钮
			minimizable : false, // 是否显示最小化按钮
			maximizable : false, // 是否显示最大化按钮
			close : true, // 初始是否关闭
			modal : true
		});
		$("#buttonSaveForAdd").show();
		$("#buttonCancelForAdd").show();
		$("#emailInfoForm").form('clear');
		$("#addEmailInfoWinId").window('open');
	}else{ 
		$.messager.alert('提示', '请选中发送邮件的对象', 'info');
	}
}

//发送邮件
function sendEmail() {
	$("#addEmailInfoWinId").window('close');
	$("#emailSendWinId").dialog('open');
	var jsonIds = arrayTojson(rows);
	$.ajax({
		url : '/base/emailSendManage/sendEmail?jsonIds=' + jsonIds,
		type : 'post',
		data : $("#emailInfoForm").serialize(),
		success : function(data) {
			if (data.flag) {
				$.messager.alert('提示', data.info, 'ok');
			} else {
				$.messager.alert("提示", data.info, 'error');
			}
			$("#emailSendWinId").window('close');
		}
	});
}
//设置 long 宽度自适应   相对窗口
function fixLongWidth(){ 
	return addWinWidth*0.66;        
} 
           
//设置 short 宽度自适应
function fixShortWidth(){    
	return addWinWidth*0.284;            
} 
  
//关闭窗口
function closeWindow(){
	$("#addNewsWinId").window('close');
}
function closeWindow2(){
	$("#editStatusWinId").window('close');
}
