/**
 * 邮件发布
 * 2018/4/20 by liufang
 */
$(function () {
	var layer;
	var editor;
	layui.use('layer', function () {
		layer = layui.layer;
	});
	var tpl = {
		"attachTpl": '\
						<div class="attach-item" data-url="<%= url %>" data-name="<%= name%>">\
 							<span class="attach-item-name"><%= name%></span>\
 							<span class="a-item-del-btn"></span>\
 						</div>\
						',
		"attachListTpl": '<% for(var i =0;i<list.length;i++){%>\
							<div class="attach-item" data-url="<%= list[i].split(";")[0] %>" data-name="<%= list[i].split(";")[1]%>">\
								<span class="attach-item-name"><%= list[i].split(";")[1]%></span>\
								<span class="a-item-del-btn"></span>\
							</div>\
						   <%}%>	\
						',
		"exportTpl": '<div class="dialog-wp">\
				<div class="mask"></div>\
				<div class="dialog dialog-export-con">\
					<div class="title-wp">\
						<span>txt导入</span>\
						<span class="close-btn"></button>\
					</div>\
					<div class="dialog-export-wp">\
						<div class="d-export-top">\
							<input type="text" class="e-name" placeholder="未选择文件" readonly/>\
							<div class="e-file-wp">\
								<input class="file-txt-input" id="txtFile" type="file" name="uploadfile"/>\
								<button class="file-btn">选择文件</button>\
							</div>\
						</div>\
						<div class="export-tips"><span class="red">*</span>TXT文档自定义导入，每行一个号码，换行显示</div>\
						<button class="btn-big-red export-sure-btn">导入</button>\
					</div>\
				</div>\
			</div>	',
		emailList: '<option value="">选择发件邮箱</option>\
					<% for(var i=0;i<list.length;i++){ %>\
						<option value="<%=list[i].id%>"><%=list[i].email_address%></option>\
					<% } %>\
				'

	}
	var contextPath = $("#contextPath").val()
	var orgList = [];
	var appPublish = {
		init: function () {
			this.render();
			this.bindEvent();
			this.getOrgList();
		},
		render: function () {
			var _this = this;
			editor = new UE.ui.Editor({
				imageActionName: 'ueAction',
				imageFieldName: "uploadfile",
				fileActionName: "ueAction",
				fileFieldName: "uploadfile",
				fileAllowFiles: [
					".png", ".jpg", ".jpeg", ".gif", ".bmp",
					".flv", ".swf", ".mkv", ".avi", ".rm", ".rmvb", ".mpeg", ".mpg",
					".ogg", ".ogv", ".mov", ".wmv", ".mp4", ".webm", ".mp3", ".wav", ".mid",
					".rar", ".zip", ".tar", ".gz", ".7z", ".bz2", ".cab", ".iso",
					".doc", ".docx", ".xls", ".xlsx", ".ppt", ".pptx", ".pdf", ".txt", ".md", ".xml"
				],
				imageAllowFiles: [".png", ".jpg", ".jpeg", ".gif", ".bmp"],
				/* 上传图片格式显示 */
				imageUrlPrefix: contextPath //contextPath
			});
			editor.render("myeditor");
			editor.ready(function () {
				editor.setHeight(370);
				//					editor.addListener("afterUpfile",_this._afterUpfile);	
			});
			//请求发件人邮箱
			$(".orgId").on("change", function () {
				var id = $(this).val();
				_this.ajaxEmail(id);
			});
			//获取邮件id
			var id = this.getQueryString("id")
			if (!!id) {
				this.ajaxDetail(id)
			}
		},
		bindEvent: function () {
			var _this = this;
			//清空目标邮箱
			$(".clear-btn").on("click", function () {
				$(".email-list").val("");
			});
			//重号过滤
			$(".filter-btn").on("click", function () {
				_this.filter_phone_data();
			});
			//清空邮件内容
			$(".c-clear-btn").on("click", function () {
				var ue = UE.getEditor('myeditor');
				ue.setContent('');
			});
			//添加附件
			$(".file-input").on("change", function () {
				var name = $(this)[0].files[0].name;
				_this.addAttach(name);
			});
			//提交发送
			$(".e-sure-btn").on("click", function () {
				_this.submitEmail();
			})
			//导入
			$(".export-btn").on("click", function () {
				$("body").append(template.render(tpl.exportTpl));
				$(".close-btn").on("click", function () {
					$(".dialog-wp").remove();
				});
				//选择文件
				$(".file-txt-input").on("change", function () {
					_this.chooseFile($(this));
				});
				$(".export-sure-btn").on("click", function () {
					if (!$(".d-export-top .e-name").val()) {
						layer.alert("请先选择导入的文件")
					} else {
						_this.sureSubmitFile();
					}

				})
			});

		},
		getOrgList: function () {
			$.ajax({
				type: "post",
				url: contextPath + "/admin/templ/getOrgList",
				success: function (data) {
					if (data.code == '200') {
						orgList = data.data;
					}
				},
				error: function () {}
			});
		},
		/**
		 * 添加附件
		 * @param name
		 */
		addAttach: function (name) {
			var _this = this;
			$.ajaxFileUpload({
				url: contextPath + "/notice/emailSend/uploadFile", //用于文件上传的服务器端请求地址
				secureuri: false, //是否需要安全协议，一般设置为false
				fileElementId: 'attach_File', //文件上传域的ID
				dataType: 'String', //返回值类型 一般设置为json
				success: function (data, status) //服务器成功响应处理函数
				{
					// console.log(data,222);
					var data = JSON.parse(data);
					//选择文件
					$(".file-input").on("change", function () {
						var name = $(this)[0].files[0].name;
						_this.addAttach(name);
					});
					if (data.code == '200') {
						var name = data.data.split(";")[1];
						$(".attach-list").append(template.render(tpl.attachTpl)({
							name: name,
							url: data.data
						}));
						//删除附件
						$(".a-item-del-btn").on("click", function () {
							$(this).closest(".attach-item").remove();
						})
					} else {
						alert(data.msg);

					}
				}
			})
		},
		_afterUpfile: function (t, result) {
			var fileName = '';
			$(".attach-list").append(template.render(tpl.attachTpl)({
				result: result
			}));
			//删除附件
			$(".a-item-del-btn").on("click", function () {
				$(this).closest(".attach-item").remove();
			})
		},
		/**
		 * 重号过滤
		 */
		filter_phone_data: function () {
			var _this = this;
			var content = $('.email-list').val();
			var phones = new Array();
			phones = content.split('\n');

			var f_phones = _this.unique(phones);
			var str = "";
			for (var i = 0; i < f_phones.length; i++) {
				var element = f_phones[i];
				if (element != "" && i < f_phones.length - 1) {
					str += element + "\n"
				} else {
					str += element;
				}
			}

			$('.email-list').val(str);
		},
		/**
		 * 过滤重号
		 * @param str 邮箱号
		 */
		unique: function (arr) {
			var result = [],
				hash = {};
			for (var i = 0, elem;
				(elem = arr[i]) != null; i++) {
				if (!hash[elem]) {
					result.push(elem);
					hash[elem] = true;
				}
			}
			return result;
		},
		/**
		 * 提交邮箱
		 * 
		 */
		submitEmail: function () {
			//邮件消息id
			var id = $(".e-sure-btn").data("id");
			//校区id
			var orgId = $("#orgId").val();
			if (!orgId) {
				layer.msg("请选择校区");
				return false;
			};
			//发件人邮箱id
			var emailaccount_id = $(".send-email-num").val();
			//主题
			var email_theme = $(".email-theme-input").val();
			//收件箱
			var recipient_email = $(".email-list").val().split('\n').join(";");
			//邮箱内容
			var ue = UE.getEditor('myeditor');
			var email_centent = ue.getContent();
			var contentTxt = ue.getContentTxt();;
			//附件地址
			var urlList = [];
			$(".attach-item").each(function (index, ele) {
				var str = $(ele).data("url")
				urlList.push(str)
			})
			var attach_ment = urlList.join(",");
			if (!emailaccount_id) {
				layer.alert("请选择发件人邮箱");
				return false;
			}
			if (!email_theme) {
				layer.alert("请输入邮件主题");
				return false;
			};
			if (!recipient_email) {
				layer.alert("请输入目标邮箱");
				return false;
			};
			if (!email_centent) {
				layer.alert("请输入邮箱内容");
				return false;
			}
			$(".e-sure-btn").attr("disabled", true)
			$.ajax({
				type: "post",
				url: contextPath + "/notice/emailSend/saveOrUpdate",
				data: {
					"email_theme": email_theme,
					"recipient_email": recipient_email,
					"email_centent": email_centent,
					"attach_ment": attach_ment,
					"emailaccount_id": emailaccount_id,
					"id": !!id ? id : '',
					"orgId": orgId,
					contentTxt: contentTxt
				},
				success: function (data) {
					var data = JSON.parse(data);
					if (data.code == '200') {
						if (!!id) {
							window.location.href = contextPath + '/notice/audit/noticeEmailVerify';
						} else {
							ue.setContent('');
							$(".email-list,.email-theme-input,.send-email-num").val("");
							$(".attach-list").html("");
							layer.msg('提交发送成功！');
						}

					} else {
						layer.msg(data.msg)
					}
					$(".e-sure-btn").attr("disabled", false)
				},
				error: function (error) {
					$(".e-sure-btn").attr("disabled", false)
					layer.msg('error')
				}
			});

		},
		/**
		 * 请求邮箱
		 * @param id 尚美id
		 * @param 选中邮箱id
		 */
		ajaxEmail: function (id, emailaccount_id) {
			if (!!id) {
				$.ajax({
					type: "post",
					url: contextPath + "/notice/emailSend/getUserEmail",
					data: {
						orgIds: id
					},
					success: function (data) {
						var data = JSON.parse(data);
						if (data.code == '200') {
							$(".send-email-num").html(template.render(tpl.emailList)({
								list: data.data.items
							}));
							if (!!emailaccount_id) {
								$(".send-email-num").val(emailaccount_id);
							}
						} else {
							layer.msg(data.msg)
						}
					},
					error: function (error) {
						layer.msg('error')
					}
				});
			} else {
				$(".send-email-num").html(template.render(tpl.emailList)({
					list: []
				}))
			}

		},
		/**
		 * 
		 * 选择导入文件
		 * @param $this
		 */
		chooseFile: function ($this) {
			var fileName = $(".file-txt-input").val();
			var name = $this[0].files[0].name;
			var extension = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length);
			if (extension == "txt") {
				if (fileName == null || fileName == "") {
					layer.alert("导入数据为空!");
					return;
				} else {
					$(".d-export-top .e-name").val(name);
				}
			} else {
				alert("请上传txt格式的文件");
			}
		},
		//确定上传文件
		sureSubmitFile: function () {
			var _this = this;
			$.ajaxFileUpload({ 
				url: contextPath + "/notice/emailSend/txtToEmail", //用于文件上传的服务器端请求地址
				secureuri: false, //是否需要安全协议，一般设置为false
				fileElementId: 'txtFile', //文件上传域的ID
				dataType: 'String', //返回值类型 一般设置为json
				success: function (data, status) //服务器成功响应处理函数
				{
					// console.log(data, 111);
					var data = JSON.parse(data);
					//选择文件
					$(".file-txt-input").on("change", function () {
						_this.chooseFile($(this));
					});
					if (data.code == '200') {
						for (var i = 0; i < data.data.length; i++) {
							$(".email-list").val($(".email-list").val() + '\n' + data.data[i]);
						};
						$(".filter-btn").click();
						$(".dialog-wp").remove();
					} else {
						alert(data.msg);

					}
				},
				error: function (data, status, e) //服务器响应失败处理函数
				{
					console.log(data,222);
				}
			})
		},
		/**
		 * 获取详情
		 * @param id
		 */
		ajaxDetail: function (id) {
			var _this = this;
			$.ajax({
				type: "post",
				url: contextPath + "/notice/emailSend/getDetail",
				data: {
					"id": id
				},
				success: function (data) {
					var data = JSON.parse(data);
					if (data.code == 200) {
						$(".e-sure-btn").data("id", data.data.id);
						$("#orgId").val(data.data.orgId);
						//
						$(".email-list").val(data.data.recipient_email.split(';').join("\n"));
						$(".email-theme-input").val(data.data.email_theme);
						_this.ajaxEmail(data.data.orgId, data.data.emailaccount_id);
						editor.ready(function () {
							var ue = UE.getEditor('myeditor');
							ue.setContent(data.data.contentTxt);
						})

						_this.renderExtraFile(data.data.attach_ment)

					} else {
						layer.msg(data.msg)
					}
				},
				error: function (error) {
					layer.msg('error')
				}
			});
		},
		/**
		 * 渲染附件
		 * @param attach_ment
		 */
		renderExtraFile: function (attach_ment) {
			if (!!attach_ment) {
				var attachList = attach_ment.split(",");
				$(".attach-list").append(template.render(tpl.attachListTpl)({
					list: attachList
				}));
				//删除附件
				$(".a-item-del-btn").on("click", function () {
					$(this).closest(".attach-item").remove();
				})
			}

		},
		/**
		 * 获取url的参数
		 * @paran name 参数名称
		 */
		getQueryString: function (name) {
			var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
			var r = window.location.search.substr(1).match(reg);
			if (r != null) return unescape(r[2]);
			return null;
		},
	};
	appPublish.ajaxEmail($("#orgId").val());
	appPublish.init();
})