var tables; //表格
var emailTheme; //主题
var start; //时间
var auditingNameType; //审核状态0未审核，1审核
var addNameType; //工单状态
var index = 0;

$(document).ready(function() {
	laydate.skin('blue');
	laydate({
		elem: '#start_0',
		event: 'focus'
	});
	laydate({
		elem: '#start_1',
		event: 'focus'
	});
	tables = $('#tableEmail' + index + '');
	//  emailTheme = $('#emailTheme_'+index+'');
	//  start = $('#start_'+index+'').val();
	//  auditingNameType = $('#auditingNameType_'+index+'').val();
	//  addNameType = $('#addNameType_'+index+'').val();
	type = index;
	initTable(tables, type);
	$('.ul_tab li').click(function() {
		index = $(this).index();
		tables = $('#tableEmail' + index + '');
		//emailTheme = $('#emailTheme_'+index+'');
		//start = $('#start_'+index+'').val();
		//auditingNameType = $('#auditingNameType_'+index+'').val();
		//addNameType = $('#addNameType_'+index+'').val();
		type = index;
		initTable(tables, type);
	});
})

function initTable(tables, type) {
	//先销毁表格
	tables.bootstrapTable('destroy');
	//初始化表格,动态从服务器加载数据
	tables.bootstrapTable({
		method: "get", //使用get请求到服务器获取数据
		url: huayi.config.callcenter_url + "EmailSend/GetEmailMessageList", //获取数据的Servlet地址
		contentType: "application/x-www-form-urlencoded",
		striped: true, //表格显示条纹
		pagination: true, //启动分页
		pageSize: 10, //每页显示的记录数
		pageNumber: 1, //当前第几页
		pageList: [10, 20, 50, 100], //记录数可选列表
		search: false, //是否启用查询
		showColumns: false, //显示下拉框勾选要显示的列
		showRefresh: false, //显示刷新按钮
		sidePagination: "server", //表示服务端请求
		//设置为undefined可以获取pageNumber，pageSize，searchText，sortName，sortOrder
		//设置为limit可以获取limit, offset, search, sort, order
		queryParamsType: "undefined",
		queryParams: function queryParams(params) { //设置查询参数
			var param = {
				page: params.pageNumber,
				pagesize: params.pageSize,
				/*: emailTheme; //主题
				stime: start, //时间
				auditingNameType: auditingNameType,  //审核状态 （1已审核，0未审核）
				addNameType: addNameType,  //工单状态（1已添加，0未添加）*/
				isAudit: type,
				token: $.cookie("token")
			};
			return param;
		},
		onLoadSuccess: function(data) { //加载成功时执行
			//layer.msg("加载成功");
			var result = data.rows;
			if (result) {
				for (var k = 0; k < result.length; k++) {
					/*$(document).on('click','.lookEmail_'+index+'_'+k+'',{resultData: result[k]},look);*/
					$('.lookEmail_' + index + '_' + k + '').on('click', {
						resultData: result[k]
					}, look);
				}
			}
		},
		onLoadError: function() { //加载失败时执行
			//layer.msg("加载数据失败", { time: 1500, icon: 2 });
		}
	});
}

var html =
	'<div class="treeTable emailDetail">' +
	'<h3 class="con_title"></h3>' +
	'<span class="eid" style="display:none"></span>' +
	'<div class="con_message">' +
	'<span>发件人：</span>' +
	'<sapn class="cjr">-</sapn>' +
	'<span>邮件地址：</span>' +
	'<sapn class="wid">-</sapn>' +
	'<span>日期：</span>' +
	'<sapn class="time">-</sapn>' +
	'</div>' +
	'<span class="contentDetails" style="display:none"></span>' +
	'<table class="con_content table table-striped table-hover">' +
	'<tr style="background-color: #fff;">' +
	'<td class="contentDetail" style="border-top: none;text-indent: 0em;">' +
	'</td>' +
	'</tr>' +
	'<tr style="background-color: #f3f3f4;">' +
	'<td class="content">' +
	'附件' +
	'</td>' +
	'</tr>' +
	'<tr style="background-color: #fff;">' +
	'<td class="contentUrl">' +
	'<p></p>' +
	'</td>' +
	'</tr>' +
	'</table>' +
	'<p style="margin-top: 20px;">' +
	'<input type="hidden" id="fileurl" />' +
	'<button class="btns auditing">审核邮件</button>' +
	'<button class="btns addEmail">添加工单</button>' +
	'</p>' +
	'</div>';
var tc;
//操作 添加查看详情
function emailDetail(val, row, index1) {
	/*return '<div class="lookEmail"><a onclick="look(\''+row.E_EmailId+'\')" title="查看详情"><i class="fa fa-navicon" style="margin-right:2px;"></i>详情</a></div>'*/
	return '<div class="lookEmail_' + index + '_' + index1 +
		'"><a title="查看详情"><i class="fa fa-navicon" style="margin-right:2px;"></i>详情</a></div>'
}
//通过现有的接口遍历 查看详情
function look(e) {
	var con = e.data.resultData;
	e.stopPropagation();
	e.preventDefault();
	if (con) {
		tc = layer.open({
			type: 1,
			title: '邮件详情',
			area: ['70%', '80%'], //宽高
			content: html
		});
		$('.eid').html(con.E_EmailId);
		$('.con_title').html(con.E_Title);
		$('.cjr').html(con.E_Email);
		$('.wid').html(con.E_Address);
		$('.time').html(con.E_EmailTime);
		$('.contentDetails').html(con.E_Content);
		$('.contentDetail').html(setHtmlReplace(con.E_Content));
		if ($('.contentDetails').html() == ' ') {
			$('.contentDetails').html('邮件内容为空。');
		}
		var fUrl = con.E_AttachmentsUrl;
		if (fUrl) {
			fUrl = fUrl.split(',');
			for (var j = 0; j < fUrl.length; j++) {
				fUrl[j] = fUrl[j].substring(1);
				var fileUrl = huayi.config.callcenter_url + fUrl[j];
				//$('.contentUrl').append('<p class="fieURL" onclick="downloadFile(\''+encodeURI(fileUrl)+'\')">'+fielUrl+'</p>');
				$('.contentUrl').append('<p class="fieURL"><a href="' + fileUrl + '" download="filename">' + fileUrl + '</a></p>');
			}

		} else {
			$('.contentUrl p:first-child').html('没有附件。');
		}
		$('#fileurl').val(con.E_AttachmentsUrl);
		//先审核，才可以添加工单
		if ((con.E_IsWorkOrder == 1) && (con.E_IsAudit == 1)) {
			$(".addEmail").attr('disabled', true);
			$(".auditing").attr('disabled', true);
		} else if ((con.E_IsWorkOrder != 1) && (con.E_IsAudit == 1)) {
			$(".addEmail").attr('disabled', false);
			$(".auditing").attr('disabled', true);
		} else if ((con.E_IsWorkOrder != 1) && (con.E_IsAudit != 1)) {
			$(".addEmail").attr('disabled', true);
			$(".auditing").attr('disabled', false);
		}
	}
}




/*
function look(str){
	$.getJSON(huayi.config.callcenter_url + "EmailSend/GetEmailMessageList", {
		page: $('.page-number.active a').html(),
		pagesize: $('.page-size').html(),
		isAudit: index,
		token: $.cookie("token")
	}, function(result) {
		var con = result.rows;
		if(con.length > 0){
			//		console.log(con);
			//		console.log(con[0].E_EmailId);
			for(var i = 0; i < con.length; i++){
				if(str == con[i].E_EmailId){
						tc = layer.open({
						type: 1,
						title: '邮件详情',
						area: ['70%', '80%'], //宽高
						content: html
					});	
					$('.eid').html(con[i].E_EmailId);
					$('.con_title').html(con[i].E_Title);
					$('.cjr').html(con[i].E_Email);
					$('.wid').html(con[i].E_Address);
					$('.time').html(con[i].E_EmailTime);
					
					$('.contentDetail').html(con[i].E_Content);
					if($('.contentDetail').html() == ' '){
						$('.contentDetail').html('邮件内容为空。');
					}
					
					var fUrl = con[i].E_AttachmentsUrl;
					if(fUrl){
						fUrl = fUrl.split(',');
						for(var j = 0; j < fUrl.length; j++){
							fUrl[j] = fUrl[j].substring(1);
							var fileUrl = huayi.config.callcenter_url + fUrl[j];
							//$('.contentUrl').append('<p class="fieURL" onclick="downloadFile(\''+encodeURI(fileUrl)+'\')">'+fielUrl+'</p>');
							$('.contentUrl').append('<p class="fieURL"><a href="'+fileUrl+'" download="filename">'+fileUrl+'</a></p>');
						}
						
					}else{
						$('.contentUrl p:first-child').html('没有附件。');						
					}
					//先审核，才可以添加工单
					if((con[i].E_IsWorkOrder == 1) && (con[i].E_IsAudit == 1)){
						$(".addEmail").attr('disabled',true);  
						$(".auditing").attr('disabled',true);
					}else if((con[i].E_IsWorkOrder != 1) && (con[i].E_IsAudit == 1)){
						$(".addEmail").attr('disabled',false);  
						$(".auditing").attr('disabled',true);
					}else if((con[i].E_IsWorkOrder != 1) && (con[i].E_IsAudit != 1)){
						$(".addEmail").attr('disabled',true);  
						$(".auditing").attr('disabled',false);
					}
				}
			}
		}
	})	
}

*/


//通过新的接口 获取邮件信息列表
//function look(str){
//	$.getJSON(huayi.config.callcenter_url + "EmailSend/GetEmailInfoById", {
//		uid: str,
//		token: $.cookie("token")
//	}, function(result) {
//		var con = result.data;
//		if(result.state.toLowerCase() == "success") {
//			tc = layer.open({
//				type: 1,
//				title: '邮件详情',
//				area: ['70%', '80%'], //宽高
//				content: html
//			});	
//			$('.eid').html(con.E_EmailId);
//			$('.con_title').html(con.E_Title);
//			$('.cjr').html(con.E_Email);
//			$('.wid').html(con.E_Address);
//			$('.time').html(con.E_EmailTime);
//			$('.contentDetail').html(con.E_Content);
//			if($('.contentDetail').html() == ' '){
//				$('.contentDetail').html('邮件内容为空。');
//			}
//			
//			$('.contentUrl p').html(con.E_AttachmentsUrl);
//			if(!$('.contentUrl p').html()){
//				$('.contentUrl p').html('没有附件。');
//			}
//					
//			if(con.E_IsAudit == 1){
//				$('.addEmail').show(); //添加按钮
//			}else{
//				$('.auditing').show(); //审核按钮
//			}
//		}
//	})	
//}

//审核
$(document).on('click', '.auditing', function() {
	$.post(huayi.config.callcenter_url + "EmailSend/IsAudit", {
		E_EmailId: $('.eid').html(),
		E_Email: $('.wid').html(),
		E_Title: $('.con_title').html(),
		E_EmailTime: $('.time').html(),
		E_Content: $('.contentDetails').html(),
		E_AttachmentsUrl: $('#fileurl').val(),
		token: $.cookie("token")
	}, function(result) {
		var data = JSON.parse(result);
		if (data.state == "success") {
			tables = $('#tableEmail' + index + '');
			//emailTheme = $('#emailTheme_'+index+'');
			//start = $('#start_'+index+'').val();
			//auditingNameType = $('#auditingNameType_'+index+'').val();
			//addNameType = $('#addNameType_'+index+'').val();
			type = index;
			initTable(tables, type);
			$(".auditing").attr('disabled', true);
			$(".addEmail").attr('disabled', false);
			layer.msg("审核成功");
		}
	})
});



//添加
$(document).on('click', '.addEmail', function() {
	$.post(huayi.config.callcenter_url + "EmailSend/AddWorkOrderByEmail", {
		emailid: $('.eid').html(),
		email: $('.wid').html(),
		title: $('.con_title').html(),
		content: $('.contentDetails').html(),
		filesurl: $('#fileurl').val(), // 20190422添加 fanlogfei
		token: $.cookie("token")
	}, function(result) {
		var data = JSON.parse(result);
		if (data.state == "success") {
			tables = $('#tableEmail' + index + '');
			//emailTheme = $('#emailTheme_'+index+'');
			//start = $('#start_'+index+'').val();
			//auditingNameType = $('#auditingNameType_'+index+'').val();
			//addNameType = $('#addNameType_'+index+'').val();
			type = index;
			initTable(tables, type);
			$(".addEmail").attr('disabled', true);
			layer.msg("添加成功");
		}
	})

});

/*搜索*/
$(document).on('click', '#sc_btns_0', {
	indexParam: 0
}, searchEmail);
$(document).on('click', '#sc_btns_1', {
	indexParam: 1
}, searchEmail);

function searchEmail(e) {
	var index = e.data.indexParam;
	tables = $('#tableEmail' + index + '');
	//  emailTheme = $('#emailTheme_'+index+'');
	//  start = $('#start_'+index+'').val();
	//  auditingNameType = $('#auditingNameType_'+index+'').val();
	//  addNameType = $('#addNameType_'+index+'').val();
	type = index;
	initTable(tables, type);
}


//批量删除   先隐藏了误删
/*$(document).on('click','.allDel0',{indexParam:0},dellEmail);
$(document).on('click','.allDel1',{indexParam:1},dellEmail);

function dellEmail(e){
	var indexEmail = e.data.indexParam;
	var delId = $.map($('#tableEmail'+indexEmail+'').bootstrapTable('getSelections'), function (row) {
		return row.E_EmailId;
	});
    if (delId.length <= 0) {
        layer.confirm('请选择一项内容删除！', {
            btn: ['确定']
    	});
        return;
    } else {
   
    	var laye = layer.confirm('提示：删除该条信息的同时会删除126邮件信息到垃圾箱!', {
						btn: ['确定', '取消'] //可以无限个按钮
		}, function() {
			$.ajax({
				type:"post",
				url:huayi.config.callcenter_url + 'EmailSend/DelEmailByID',
				async:true,
				dataType:'json',
				data:{
					token:$.cookie("token"),
					uid:delId
				},
				success:function(data){
					if(data.state.toLowerCase()=='success'){
						layer.msg(data.message);
						inittableEmail();		
					}
					
				}
			});
		});
    }
}
*/


//编号
function setCode(val, row, index) {
	return index + 1;
}
//审核状态
function auditingType(val) {
	if (val == 1) {
		return '已审核';
	} else {
		return '未审核';
	}
}
//工单状态
function addType(val) {
	if (val == 1) {
		return '已添加';
	} else {
		return '未添加';
	}
}

//下载
function downloadFile(furl) {
	try {
		var elemIF = document.createElement("iframe");
		elemIF.src = furl;
		elemIF.style.display = "none";
		document.body.appendChild(elemIF);
	} catch (e) {
		layer.msg('下载出错');
	}
}

//字符串替换
function setHtmlReplace(MsgContent) {
	var Htmls = [{
			aHtml: /\ +/g,
			bHtml: ' '
		},
		{
			aHtml: /[ ]/g,
			bHtml: '&nbsp&nbsp&nbsp&nbsp&nbsp'
		},
		{
			aHtml: /[\r\n]/g,
			bHtml: '<BR>'
		}
	];
	$.each(Htmls, function(index, item) {
		var re = new RegExp(item.aHtml, "g");
		MsgContent = MsgContent.replace(re, item.bHtml);
	});
	return MsgContent;
}
