
var permDelete = $("#perm-delete").val();//删除权限
var permEdit = $("#perm-edit").val();//编辑权限
/**
 * 邮箱配置 
 * 2018/5/3 by liufang
 */
$(function(){
	var tpl = {
			"addTpl": '<div class="dialog-wp">\
				<div class="mask"></div>\
				<div class="dialog dialog-email-con">\
					<div class="title-wp">\
						<span>添加邮件账号</span>\
						<span class="close-btn"></button>\
					</div>\
					<div class="dialog-email-wp">\
						<div class="d-email-wrapper-top">\
							<h2 class="title">账号设置</h2>\
					<% if(list!=null&&list.length>1){ %>\
							<div class="email-item">\
							<span class="tips">项目</span>\
							<input class="orgId e-item-text" name="orgId" id="orgId" placeholder="请选择项目" autocomplete="off"/>\
		        			<span class="select_wrap _hide"></span>\
						</div>\
					<%}else if(list!=null&&list.length==1){%>\
						<input type="hidden" id="orgId" value="<%=list[0].id %>" org__id="<%=list[0].id %>"/>\
					<%}%>\
						<div class="email-item">\
								<span class="tips">邮件地址</span>\
								<input type="text" class="e-item-text email-address" placeholder="请输入邮件地址" />\
								<input type="text"  style="display: none" />\
							</div>\
							<div class="email-item">\
								<span class="tips">密码</span>\
								<input type="password" style="display: none"/>\
								<input type="password" class="e-item-text email-psd" placeholder="请输入密码"/>\
							</div>\
							<div class="email-item">\
								<span class="tips">发件名称</span>\
								<input type="text" class="e-item-text email-name" placeholder="请输入发件名称"/>\
							</div>\
				     	</div>\
						<div class="d-email-wrapper-btm">\
							<h2 class="title">服务配置</h2>\
							<div class="email-item">\
								<span class="tips">SMTP服务器</span>\
								<input type="text" class="e-item-text email-server" placeholder="请输入SMTP服务器"/>\
							</div>\
							<div class="email-item">\
								<span class="tips"></span>\
								 <div class="checkbox-wp">\
								   <span class="checkbox-input">\
									 <input type="checkbox" id="wx" class="check-item email-ssl" />\
									  <span class="checkbox-inner"></span>\
								   </span>		\
								   <label class="checkbox-con" for="wx">SSL</label>\
								</div>\
								<span class="port-tips">端口</span>\
								<input type="text" class="port-text"/>\
							</div>\
				     	</div>\
						<div class="d-email-btns">\
							<button class="cancel-add-btn btn-white">取消</button>\
							<button class="sure-add-btn btn-red">保存</button>\
						</div>\
					</div>\
				</div>\
			</div>	',
			"updateTpl": '<div class="dialog-wp">\
				<div class="mask"></div>\
				<div class="dialog dialog-email-con">\
					<div class="title-wp">\
						<span>添加邮件账号</span>\
						<span class="close-btn"></button>\
					</div>\
					<div class="dialog-email-wp">\
						<div class="d-email-wrapper-top">\
							<h2 class="title">账号设置</h2>\
				<% if(list!=null&&list.length>1){ %>\
					<div class="email-item">\
					   <span class="tips">选择项目</span>\
					   <input class="orgId e-item-text" name="orgId" id="orgId" placeholder="请选择项目" autocomplete="off" value="<%=data.orgName %>" org__id="<%=data.orgId %>"/>\
		        		<span class="select_wrap _hide"></span>\
					</div>\
				<% }else if(list!=null&&list.length==1){ %>\
					<input type="hidden" id="orgId" value="<%=data.orgId %>" org__id="<%=data.orgId %>"/>\
				<%}%>\
							<div class="email-item">\
								<span class="tips">邮件地址</span>\
								<input type="text" class="e-item-text email-address" placeholder="请输入邮件地址" value="<%=data.email_address%>" data-createtime="<%=data.createTime%>" data-creator="<%=data.creator%>"/>\
							</div>\
							<div class="email-item">\
								<span class="tips">密码</span>\
								<input type="password" class="e-item-text email-psd" placeholder="请输入密码" value="<%=data.password%>"/>\
							</div>\
							<div class="email-item">\
								<span class="tips">发件名称</span>\
								<input type="text" class="e-item-text email-name" placeholder="请输入发件名称" value="<%=data.send_email_name%>"/>\
							</div>\
				     	</div>\
						<div class="d-email-wrapper-btm">\
							<h2 class="title">服务配置</h2>\
							<div class="email-item">\
								<span class="tips">SMTP服务器</span>\
								<input type="text" class="e-item-text email-server" placeholder="请输入SMTP服务器" value="<%=data.smtp_server%>"/>\
							</div>\
							<div class="email-item">\
								<span class="tips"></span>\
								 <div class="checkbox-wp">\
								   <span class="checkbox-input">\
									 <input type="checkbox" id="wx" class="check-item email-ssl" <%if(!!data.stmp_encrypted){%>checked <%}%>/>\
									  <span class="checkbox-inner"></span>\
								   </span>		\
								   <label class="checkbox-con" for="wx">SSL</label>\
								</div>\
								<span class="port-tips">端口</span>\
								<input type="text" class="port-text" value="<%=data.stmp_port%>"/>\
							</div>\
				     	</div>\
						<div class="d-email-btns">\
							<button class="cancel-add-btn btn-white">取消</button>\
							<button class="sure-add-btn btn-red">保存</button>\
						</div>\
					</div>\
				</div>\
			</div>	',
		
						 
	};
	
	var layer;
	var table;
	var Index = 0;
	var wxList;
	layui.use('layer', function(){
		   layer = layui.layer;  
	});   
	var appSend = {
			init: function(){
				this.render();
				this.bindEvent();
				this.getOrgList();
			},
			render: function(){
				this.rendertable();
				
			},
			bindEvent: function(){
				var _this = this;
				var a=$("#orgList").val();
				//重置
				$(".set-btn").on("click",function(){
					$("#conditionform select").val("0");
				});
				//添加模板
				$(".add-temp-btn").on("click",function(){
					//显示 弹窗
					$("body").append(template.render(tpl.addTpl)({list: wxList}));
					//关闭弹窗
					$(".close-btn,.cancel-add-btn").on("click",function(){
						$(".dialog-wp").remove();
					});
					//确认添加
					$(".sure-add-btn").on("click",function(){
						_this.ajaxAddTemp();
					})
					
				})
				// 模糊搜索
				_this.search_fuzzy()
				
			},
			// 模糊搜索事件
			search_fuzzy: function(){
				$('body').on("input",'.default-select.orgId',function(event){
					var _this = $(this)
					cjqt.search_fuzzy.event_input(_this,'org__id','org__span',$("#contextPath").val(),'/admin/templ/getOrgListByName')
				});
				$('body').on("focus",'.default-select.orgId',function(event){
					var _this = $(this)
					cjqt.search_fuzzy.event_focus(_this,'org__id','org__span',$("#contextPath").val(),'/admin/templ/getOrgListByName')
				});
				$('body').on('blur','.default-select.orgId',function(event) {
					var _this = $(this)
					cjqt.search_fuzzy.event_blur(_this,'org__id')
				});
				$('body').on('click','.default-select.orgId~.select_wrap>.org__span', function(event) {
					event.preventDefault();
					event.stopPropagation();
					/* Act on the event */
					var _this = $(this)
					cjqt.search_fuzzy.event_click(_this,'org__id','.default-select.orgId')
				});

				$('body').on("input",'.e-item-text#orgId',function(event){
					var _this = $(this)
					cjqt.search_fuzzy.event_input(_this,'org__id','org__span',$("#contextPath").val(),'/admin/templ/getOrgListByName')
				});
				$('body').on("focus",'.e-item-text#orgId',function(event){
					var _this = $(this)
					cjqt.search_fuzzy.event_focus(_this,'org__id','org__span',$("#contextPath").val(),'/admin/templ/getOrgListByName')
				});
				$('body').on('blur','.e-item-text#orgId',function(event) {
					var _this = $(this)
					cjqt.search_fuzzy.event_blur(_this,'org__id')
				});
				$('body').on('click','.e-item-text#orgId~.select_wrap>.org__span', function(event) {
					event.preventDefault();
					event.stopPropagation();
					/* Act on the event */
					var _this = $(this)
					cjqt.search_fuzzy.event_click(_this,'org__id','.e-item-text#orgId')
				});
			},
			getOrgList: function(){
				$.ajax({
					   type: "post",
					   url: $("#contextPath").val()+ "/admin/templ/getOrgList", 
					   success: function(data){
						   if(data.code == '200'){
							  wxList = data.data;
						   }   
					   },
					   error: function(){   
					   }
			   });
			},
			rendertable: function(){
				var _this = this;
				layui.use('table', function(){
					  table = layui.table;
					  
					  //方法级渲染
					  table.render({
					    elem: '#LAY_table_user'
					    ,url: $("#contextPath").val()+ "/admin/templ/getEmailSettingList"
					    ,skin: 'nob' //行边框风格
				    		  ,even: true //开启隔行背景
				    		  ,size: 'lg' //小尺寸的表格
					    ,cols: [[
					      {
				    		   field:'createTime', 
				    		   title: '序号',
				    		   templet: '#indexTpl',
				    		   width: '10%'
				    	  } ,{
				    		   field:'orgName', 
				    		   title: '项目名称',
				    		   width: '20%'
				    	  },{
				    		  field:'email_address',
				    		  title: '邮件地址',
				    		  width: '20%'
			    		  },{
			    			  field:'send_email_name', 
			    			  title: '发件名称', 
			    			  width:'15%'
		    			  },{
		    				  field:'smtp_server', 
		    				  title: '发件服务器',
		    				  width:'15%'
	    				  },{
	    					  field:'id', 
	    					  title: '操作', 
	    					  width:'20%',
	    					  fixed: 'right', 
	    					  templet: function(data){
	    						  var str = '';
	    						  if (permEdit == 1){
                                      str += '<button class="t-btn t-red-btn t-edit-btn" data-id='+data.id+' >配置</button>';
								  }
	    						  if (permDelete == 1){
                                      str += '<button class="t-btn t-white-btn t-del-btn" data-id='+data.id+' >删除</button>';
								  }

	    						  return str;
	    					  }
	  					  }
						  ]]
						    ,id: 'testReload'
						    ,page: true,
						    method: 'post',
						    where: {wechatAccountId: $(".wx-num").val()},
						    response: {
						    	  statusName: 'code' //数据状态的字段名称，默认：code
						    	  ,statusCode: 200 //成功的状态码，默认：0
						    	  ,countName: "count"//数据总数的字段名称，默认：count
						    	  ,dataName: "data" //数据列表的字段名称，默认：data
						    	}   ,
						    done: function(res, curr, count){
//						        //如果是异步请求数据方式，res即为你接口返回的信息。
						    	//删除
						    	$(".t-del-btn").on("click",function(){
						    		var id = $(this).data("id");
						    		_this.ajaxDelTemp(id,function(){
						    			Index = 0;
						    			 table.reload('testReload', {
											  page: {
											    curr: 1 //重新从第 1 页开始
											  }
										}); 
						    		})
						    	});
						    	//编辑
						        $(".t-edit-btn").on("click",function(){
						        	var id = $(this).data("id")
						        	//显示详情弹窗
						        	_this.showEditDialog(id,function(data){
						        		console.log(data);
						        		//显示 弹窗
										$("body").append(template.render(tpl.updateTpl)({list: wxList,data: data}));
										//关闭弹窗
										$(".close-btn,.cancel-add-btn").on("click",function(){
											$(".dialog-wp").remove();
										});
										//保存
										$(".sure-add-btn").on("click",function(){
											_this.ajaxAddTemp(id,function(){
												Index = 0;
												table.reload('testReload', {
													  page: {
													    curr: 1 //重新从第 1 页开始
													  }
												}); 
											})
										})
						        	})
						        })
						      }
					  });
					  //查询
					  $('#conditionform  .search-btn').on('click', function(){
						  Index = 0;
						  table.reload('testReload', {
							  where: { //设定异步数据接口的额外参数，任意设
								  orgIds: $(".orgId").attr('org__id')
							  }
							  ,page: {
							    curr: 1 //重新从第 1 页开始
							  }
						}); 
					  });
					});
			},
			/**
			 * 删除模板
			 * @param id 模板id
			 * @param callback
			 */
			ajaxDelTemp: function(id,callback){
				layer.confirm('确定删除?', {
					  btn: ['确定', '取消'] 
					}, function(index, layero){
						 layer.close(index); //如果设定了yes回调，需进行手工关闭
						 $.ajax({
							   type: "post",
							   url: $("#contextPath").val()+ "/admin/templ/deleteEmailConfig", 
							   data: {
								   "emailCongifId": id
							   },
							   success: function(data){
								   var data = JSON.parse(data);
								   if(data.code == 200){
									   callback();
								   }   
							   },
							   error: function(){   
							   }
					   });
					}, function(index){
						
					});	
			},
			/**
			 * 添加模板
			 * @param id
			 * @param callback
			 */
			ajaxAddTemp: function(id,callback){
				//邮件地址
				var email_address = $(".email-address").val();
				if(!email_address){
					layer.alert("请输入邮件地址");
					return false;
				};
				//创建人
				var creator = $(".email-address").data("creator");
				//项目
				// var options=$("#orgId option:selected");
				// var orgId = options.val();
                var orgId = $(".dialog-wp #orgId").attr('org__id');
				//创建时间
				var createTime = $(".email-address").data("createtime");	
			   //密码
			   var password = $(".email-psd").val();
			   if(!password){
					layer.alert("请输入密码");
					return false;
				};
			   	
				  //收件人姓名
				  var 	send_email_name = $(".email-name").val();
				  if(!send_email_name){
					  layer.alert("请输入发件名称");
					  return false;
				  };
	//		
				 //服务器
				var smtp_server = $(".email-server").val();
				if(!smtp_server){
					layer.alert("请输入SMTP服务器");
					return false;
				}
	//			//端口
			   var 	stmp_port = $(".port-text").val();
	//			 //ssl
			   var stmp_encrypted = $('.email-ssl').is(':checked')? 1 : 0;
			   $.ajax({
				   type: "post",
				   url: $("#contextPath").val()+ "/admin/templ/saveAndUpdateEmailConfig", 
				   data: {
					   "id": id,
					   "email_address": email_address,
					   "password": password,
					   "send_email_name": send_email_name,
					   "smtp_server": smtp_server,
					   "stmp_port": stmp_port,
					   "stmp_encrypted": stmp_encrypted,
					   "orgId":orgId,
//					   "creator": creator,
//					   "createTime": createTime
				   },
				   success: function(data){
					   var data = JSON.parse(data);
					   if(data.code == 200){
						   $(".dialog-wp").remove();
						   Index = 0;
						   table.reload('testReload', {
								  page: {
								    curr: 1 //重新从第 1 页开始
								  }
							}); 
					   }   
				   },
				   error: function(){   
				   }
		   });
			},
			/**
			 * 编辑模板
			 * @param id
			 * @param callback
			 */
			showEditDialog: function(id,callback){
				var _this = this;
				 $.ajax({
					   type: "post",
					   url: $("#contextPath").val()+ "/admin/templ/getEmailSetInfo", 
					   data: {
						   "emailCongifId": id
					   },
					   success: function(data){
						   var data = JSON.parse(data);
						   if(data.code == 200){
							  callback(data.data);
						   }   
					   },
					   error: function(){   
					   }
			   });
			}
	};
	appSend.init();
})