
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-wx-con">\
					<div class="title-wp">\
						<span>模板配置</span>\
						<span class="close-btn"></button>\
					</div>\
					<div class="dialog-wx-wp">\
						<div class="dialog-wx-wrapper">\
							<div class="d-wx-top">\
								<% if(list!=null&&list.length>1){ %>\
								<div class="d-wx-wp d-wx-num-wp">\
									<span class="tips">校区</span>\
									<input class="orgId e-item-text d-item-wp" name="orgId" id="orgId" placeholder="请选择校区" autocomplete="off"/>\
					    			<span class="select_wrap _hide"></span>\
								</div>\
								<%}else if(list!=null&&list.length==1){%>\
									<input type="hidden" class="orgId e-item-text" id="orgId" value="<%=list[0].id %>" org__id="<%=list[0].id %>"/>\
								<%}%>\
								<div class="d-wx-wp d-wx-num-wp">\
									<span>公众号</span>\
									<select class="d-wx-num">\
										<option value="">请选择公众号</option>\
									</select>\
								</div>\
								<div class="d-wx-wp d-wx-name-wp">\
									<span>模板名称</span>\
									<input class="d-wx-name" placeholder="请输入模板名称"/>\
								</div>\
								<div class="d-wx-wp d-wx-id-wp">\
									<span>模板ID</span>\
									<input class="d-wx-id" placeholder="请输入模板ID"/>\
								</div>\
							</div>\
							<div class="d-wx-btm">\
								<h3 class="title">属性配置</h3>\
								<div class="wx-property-list">\
									<div class="wx-property-item clearfloat">\
										<div class="item-name-wp">\
											<span class="name">第一字段名称</span>\
											<input class="item-name-text"/>\
										</div>\
										<div class="item-keyword-wp">\
											<span class="key">关键字</span>\
											<input class="item-key-text"/>\
										</div>\
										<div class="del-property-btn ">删除</div>\
									</div>\
									<div class="wx-property-item clearfloat">\
										<div class="item-name-wp">\
											<span class="name">第二字段名称</span>\
											<input class="item-name-text"/>\
										</div>\
										<div class="item-keyword-wp">\
											<span class="key">关键字</span>\
											<input class="item-key-text"/>\
										</div>\
										<div class="del-property-btn ">删除</div>\
									</div>\
									<div class="wx-property-item clearfloat">\
										<div class="item-name-wp">\
											<span class="name">第三字段名称</span>\
											<input class="item-name-text"/>\
										</div>\
										<div class="item-keyword-wp">\
											<span class="key">关键字</span>\
											<input class="item-key-text"/>\
										</div>\
										<div class="del-property-btn ">删除</div>\
									</div>\
									<div class="wx-property-item clearfloat">\
										<div class="item-name-wp">\
											<span class="name">第四字段名称</span>\
											<input class="item-name-text"/>\
										</div>\
										<div class="item-keyword-wp">\
											<span class="key">关键字</span>\
											<input class="item-key-text"/>\
										</div>\
										<div class="del-property-btn ">删除</div>\
									</div>\
								</div>\
								<div class="add-property-btn">添加字段＋</div>\
							</div>\
				     	</div>\
						<div class="d-wx-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-wx-con">\
					<div class="title-wp">\
						<span>模板配置</span>\
						<span class="close-btn"></button>\
					</div>\
					<div class="dialog-wx-wp">\
						<div class="dialog-wx-wrapper">\
							<div class="d-wx-top">\
				<% if(list!=null&&list.length>1){ %>\
				<div class="d-wx-wp d-wx-num-wp">\
					<span class="tips">校区</span>\
					<input class="orgId e-item-text d-item-wp" 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="<%=list[0].id %>" org__id="<%=list[0].id %>"/>\
				<%}%>\
								<div class="d-wx-wp d-wx-num-wp">\
									<span>公众号</span>\
									<select class="d-wx-num" data-createtime="<%=data.wxTemplInfo.createTime%>" data-creator="<%=data.wxTemplInfo.creator%>">\
										<option value="">请选择公众号</option>\
										\
									</select>\
								</div>\
								<div class="d-wx-wp d-wx-name-wp">\
									<span>模板名称</span>\
									<input class="d-wx-name" placeholder="请输入模板名称" value="<%=data.wxTemplInfo.name%>"/>\
								</div>\
								<div class="d-wx-wp d-wx-id-wp">\
									<span>模板ID</span>\
									<input class="d-wx-id" placeholder="请输入模板ID"  value="<%=data.wxTemplInfo.templateid%>"/>\
								</div>\
							</div>\
							<div class="d-wx-btm">\
								<h3 class="title">属性配置</h3>\
								<div class="wx-property-list">\
									<% for(var j=0;j<data.paramList.length;j++){%>\
										<div class="wx-property-item clearfloat">\
											<div class="item-name-wp">\
												<span class="name">第<%=numFormat(j)%>字段名称</span>\
												<input class="item-name-text"  value="<%=data.paramList[j].name%>"/>\
											</div>\
											<div class="item-keyword-wp">\
												<span class="key">关键字</span>\
												<input class="item-key-text" value="<%=data.paramList[j].param_key%>"/>\
											</div>\
											<div class="del-property-btn <%if((j+1==data.paramList.length) && (data.paramList.length >4) ){%>active<%}%>">删除</div>\
										</div>\
									<%}%>\
								</div>\
								<div class="add-property-btn">添加字段＋</div>\
							</div>\
				     	</div>\
						<div class="d-wx-btns">\
							<button class="cancel-add-btn btn-white">取消</button>\
							<button class="sure-add-btn btn-red">保存</button>\
						</div>\
					</div>\
				</div>\
			</div>	',
			"selectTpl": '<option value="">选择公众号</option>\
						<%for (var i=0;i<list.length;i++){ %>\
							<option value="<%=list[i].ID %>"><%= list[i].name %></option>\
						 <% } %>',
        "itemTpl": '<option value="">选择校区</option>\
						<%for (var i=0;i<list.length;i++){ %>\
							<option value="<%=list[i].id %>"><%= list[i].name %></option>\
						 <% } %>',
			"propertyTpl": '<div class="wx-property-item clearfloat">\
										<div class="item-name-wp">\
											<span class="name">第<%=num %>字段名称</span>\
											<input class="item-name-text"/>\
										</div>\
										<div class="item-keyword-wp">\
											<span class="key">关键字</span>\
											<input class="item-key-text"/>\
										</div>\
										<div class="del-property-btn active">删除</div>\
									</div>'		,
		"updateSelectTpl": '<option value="">请选择公众号</option>\
			<%for (var i=0;i<list.length;i++){ %>\
				<option value="<%=list[i].ID %>" <%if(id==list[i].ID){ %>selected <%}%>><%= list[i].name %></option>\
			<% } %>'
						 
	};
	
	var TEM_NUM = ["一","二","三","四","五","六","七"];
	var layer;
	var wxList = [];
	var orgList = [];
	var table;
	var Index = 0;
	template.helper('numFormat', function (num) {
        return TEM_NUM[num] ;
    });
	
	layui.use('layer', function(){
		   layer = layui.layer;  
	});   
	var appSend = {
			init: function(){
				this.render();
				this.bindEvent();
				this.getOrgList();
			},
			render: function(){
				 this.renderSelect();
				this.rendertable();
				
			},
			bindEvent: function(){
				var _this = this;
				
				//重置
				$(".set-btn").on("click",function(){
					
					$("#conditionform select,#conditionform input").val("");
					$("#orgId").attr('org__id','');
					_this.againRenderTable();
				});
				//添加模板
				$(".add-temp-btn").on("click",function(){
					//显示 弹窗
					$("body").append(template.render(tpl.addTpl)({list:orgList}));
					//选择校区
					$(".d-item-wp").on("change",function(){
						var that = this;
						
						
						setTimeout(function(){
							var id = $(that).attr('org__id');
							
                            _this.renderSelect(id,'add');
						},200)
						
					})
					//关闭弹窗
					$(".close-btn,.cancel-add-btn").on("click",function(){
						$(".dialog-wp").remove();
					});
					//确认添加
					$(".sure-add-btn").on("click",function(){
						_this.ajaxAddTemp();
					});
					
					//校区
// 				$("#orgId").on("change",function(){
// 					var val = $(this).val();
// 					console.log(val);
// 					if(!val){
// //						$(".repair-type-detail").html($("<option value=''>选择维修小类</option>"));
// 					}else{
// //						_this.ajaxType(val);
// 					}
// 				})
					
					//添加字段
					$(".add-property-btn").on("click",function(){
						var length = $(".wx-property-item").length;
						if(length>=4 && length<7){
							$(".wx-property-item").eq(length-1).find(".del-property-btn").removeClass("active");
							var temp = template.render(tpl.propertyTpl)({num: TEM_NUM[length]});
							$(".wx-property-list").append(temp);
							$(".del-property-btn").on("click",function(){
								if($(".wx-property-item").length>5){
									$(this).closest(".wx-property-item").prev(".wx-property-item").find(".del-property-btn").addClass("active");
								}
								$(this).closest(".wx-property-item").remove();
								
							})
						}
						
					})

				})
				// 模糊搜索
				_this.search_fuzzy()
			},
			// 模糊搜索事件
			search_fuzzy: function(){
				var __this = this;
				$('body').on("input",'#orgId',function(event){
					var _this = $(this)
					cjqt.search_fuzzy.event_input(_this,'org__id','org__span',$("#contextPath").val(),'/admin/templ/getOrgListByName')
				});
				$('body').on("focus",'#orgId',function(event){
					var _this = $(this)
					cjqt.search_fuzzy.event_focus(_this,'org__id','org__span',$("#contextPath").val(),'/admin/templ/getOrgListByName')
				});
				$('body').on('blur','#orgId',function(event) {
					var _this = $(this)
					cjqt.search_fuzzy.event_blur(_this,'org__id')
				});
				$('body').on('click','#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','#orgId')
				});

				$('body').on("input",'.d-item-wp',function(event){
					var _this = $(this)
					cjqt.search_fuzzy.event_input(_this,'org__id','org__span',$("#contextPath").val(),'/admin/templ/getOrgListByName')
				});
				$('body').on("focus",'.d-item-wp',function(event){
					
					var _this = $(this)
					cjqt.search_fuzzy.event_focus(_this,'org__id','org__span',$("#contextPath").val(),'/admin/templ/getOrgListByName')
				});
				$('body').on('blur','.d-item-wp',function(event) {
					var _this = $(this)
					cjqt.search_fuzzy.event_blur(_this,'org__id')
				});
				$('body').on('click','.d-item-wp~.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','.d-item-wp',{},__this.changeEvent,__this)
				});
			},
			getOrgList: function(){
				var _this = this;
				$.ajax({
					   type: "post",
					   url: $("#contextPath").val()+ "/admin/templ/getOrgList", 
					   success: function(data){
						   if(data.code == '200'){
							  orgList = data.data;
							  // $("#orgId").html(template.render(tpl.itemTpl)({list: data.data}));
							  if(orgList.length==1){
								  var orgId=orgList[0].id;
								  _this.renderSelect(orgId);
							  }
							  $("#orgId").on("change",function(){
							  		var that = this
							  		setTimeout(function(){
							  			var id = $(that).attr('org__id');
                                  		_this.renderSelect(id);
							  		},200)
							  	 
							  })
						   }   
					   },
					   error: function(){   
					   }
			   });
			},
			//
			/**
			 * 渲染公众号select
			 * @param id 校区id
			 * @param type 'add'新增
			 * @param itemId 校区id
			 */
			renderSelect: function(id,type,itemId){
				if(!!id){
                    $.ajax({
                        type: "post",
                        url: $("#contextPath").val()+ "/notice/wxtemplateMessage/getPublicList",
						data: {
                            orgIds: id
						},
                        success: function(data){
                            var data = JSON.parse(data);
                            if(data.code == '200'){
                            	if(type=='add'){
                                    $(".d-wx-num").html(template.render(tpl.selectTpl)({list: data.data}));
								}else if(type=="update"){
                            		//updateSelectTpl
                                    $(".d-wx-num").html(template.render(tpl.updateSelectTpl)({list: data.data,id:itemId}));
								}else{
                                    $(".wx-num").html(template.render(tpl.selectTpl)({list: data.data}));
								}

                                // wxList = data.data;
                            }
                        },
                        error: function(){
                        }
                    });
				}else{
                    if(type=='add'){
                        $(".d-wx-num").html(template.render(tpl.selectTpl)({list: []}));
					}else if(type=="update"){
                        $(".d-wx-num").html(template.render(tpl.selectTpl)({list: []}));
					}else{
                        $(".wx-num").html(template.render(tpl.selectTpl)({list: []}));
					}


				}

			},
			changeEvent: function(id,_this){
				console.log(this);
				 _this.renderSelect(id,'add');
			},
			rendertable: function(){
				var _this = this;
				layui.use('table', function(){
					  table = layui.table;
					  
					  //方法级渲染
					  table.render({
					    elem: '#LAY_table_user'
					    ,url: $("#contextPath").val()+ "/admin/templ/getWxTemplList"
					    ,skin: 'nob' //行边框风格
				    		  ,even: true //开启隔行背景
				    		  ,size: 'lg' //小尺寸的表格
					    ,cols: [[
					      {
				    		   field:'Index', 
				    		   title: '序号',
				    		   templet: '#indexTpl',
				    		   width: '10%'
				    	  },{
				    		  field:'orgName',
				    		  title: '校区名称',
				    		  width:'20%'
			    		  },{
				    		  field:'pubName',
				    		  title: '公众号',
				    		  width:'10%'
			    		  },{
			    			  field:'name', 
			    			  title: '模板名称', 
			    			  width:'10%'
		    			  },{
		    				  field:'templateid', 
		    				  title: '模板ID', 
		    				  width: '15%'
	    				  },{
	    					  field:'createTime', 
	    					  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: {},
						    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', {
											  where: { //设定异步数据接口的额外参数，任意设
												  wechatAccountId: $(".wx-num").val()
											  }
											  ,page: {
											    curr: 1 //重新从第 1 页开始
											  }
										}); 
						    		})
						    	});
						    	//编辑
						        $(".t-edit-btn").on("click",function(){
						        	var id = $(this).data("id")
						  
						        	//显示详情弹窗
						        	_this.showEditDialog(id,function(){
						        		Index = 0;
						        		table.reload('testReload', {
											  where: { //设定异步数据接口的额外参数，任意设
												  wechatAccountId: $(".wx-num").val()
											  }
											  ,page: {
											    curr: 1 //重新从第 1 页开始
											  }
										}); 
						        	})
						        })
						      }
					  });
					  //查询
					  $('#conditionform  .search-btn').on('click', function(){
						  Index = 0;
						  // console.log($(".wx-num").val())
						  // console.log($("#orgId").val())
						  table.reload('testReload', {
							  where: { //设定异步数据接口的额外参数，任意设
								  wechatAccountId: $(".wx-num").val(),
								  orgIds: $("#orgId").attr('org__id')?$("#orgId").attr('org__id'):''
							  }
							  ,page: {
							    curr: 1 //重新从第 1 页开始
							  }
						}); 
					  });
					});
			},
			/*重新渲染table*/
			againRenderTable: function(option){
				 Index = 0;
				  
				  table.reload('testReload', {
					  where: { //设定异步数据接口的额外参数，任意设
						  wechatAccountId: $(".wx-num").val(),
						  orgIds: $("#orgId").attr('org__id')?$("#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/deleteWxTemplConfig", 
							   data: {
								   "wxTemplId": id
							   },
							   success: function(data){
								   var data = JSON.parse(data);
								   if(data.code == 200){
									   callback();
								   }   
							   },
							   error: function(){   
							   }
					   });
					}, function(index){
						
					});	
			},
			/**
			 * 添加模板
			 * @param id
			 * @param callback
			 */
			ajaxAddTemp: function(callback,id){
				//校区
				var orgId = $(".orgId.e-item-text").attr("org__id");
//				var options=$("#orgId option:selected");
//				var orgId = options.val();
				//公众号id
				var wechat_account_id = $(".d-wx-num").val();
				if(!wechat_account_id){
					layer.alert("请选择公众号");
					return false;
				};
				//创建人
				var creator = $(".d-wx-num").data("creator");
				//创建时间
				var createTime = +$(".d-wx-num").data("createtime");
				//模板名称
				var name = $(".d-wx-name").val();
				if(!name){
					layer.alert("请输入模板名称");
					return false;
				};
				//模板id
				var templateid = $(".d-wx-id").val();
				if(!templateid){
					layer.alert("请输入模板id");
					return false;
				}
				//属性配置
				var flag = true;
				var param1,param2,param3,param4,param5,param6,param7,key1,key2,key3,key4,key5,key6,key7;
				$(".wx-property-item").each(function(index,ele){
					var name = $(ele).find(".item-name-text").val();
					var key = $(ele).find(".item-key-text").val();
					if(!(name && key)){
						layer.alert("字段名称和关键字不能为空");
						flag = false;
						return false;
					};
					flag= true;
					(index == 0) && (param1 = name) ;
					(index == 0) && (key1 = key);
					(index == 1) && (param2 = name) ;
					(index == 1) && (key2 = key);
					(index == 2) && (param3 = name) ;
					(index == 2) && (key3 = key);
					(index == 3) && (param4 = name) ;
					(index == 3) && (key4 = key);
					(index == 4) && (param5 = name) ;
					(index == 4) && (key5 = key);
					(index == 5) && (param6 = name) ;
					(index == 5) && (key6 = key);
					(index == 6) && (param7 = name) ;
					(index == 6) && (key7 = key);
				});
				if(!flag){
					return false;
				};
				
				 $.ajax({
					   type: "post",
					   url: $("#contextPath").val()+ "/admin/templ/saveAndUpdateWxTempl", 
					   data: {
//						   "creator": creator,
//						   "createTime": createTime,
						   orgId:orgId,
						   "id": id,
						   "wechat_account_id": wechat_account_id,
						    "name": name,
						   	"templateid": templateid,
						   	 "param1": param1,
						   	 "key1": key1,
						   	 "param2": param2,
						   	 "key2": key2,
						   	 "param3": param3,
						   	 "key3": key3,
						   	 "param4": param4,
						   	 "key4": key4,
						   	 "param5": param5,
						   	 "key5": key5,
						   	 "param6": param6,
						   	 "key6": key6,
						   	 "param7": param7,
						   	 "key7": key7
					   },
					   success: function(data){
						   var data = JSON.parse(data);
						   if(data.code == 200){
							   $(".dialog-wp").remove();
							   callback && callback();
							   if(!callback){
								   Index = 0;
								   table.reload('testReload', {
										  where: { //设定异步数据接口的额外参数，任意设
											  wechatAccountId: $(".wx-num").val(),
											  // orgId:orgId
										  }
										  ,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/getWxTemplInfo", 
					   data: {
						  "wxTemplId": id
					   },
					   success: function(data){
						   var data = JSON.parse(data);
						   if(data.code == 200){
							 //显示 弹窗
								$("body").append(template.render(tpl.updateTpl)({list:orgList,data: data.data}));
                               _this.renderSelect(data.data.orgId,'update',data.data.wxTemplInfo.wechat_account_id);
								//选择校区
                               $(".d-item-wp").on("change",function(){
                               		var that = this
                               		setTimeout(function(){
                               			var id = $(that).attr('org__id');
                               			_this.renderSelect(id,'add');
                               		},200)
                                   
                               })
								//关闭弹窗
								$(".close-btn,.cancel-add-btn").on("click",function(){
									$(".dialog-wp").remove();
								});
								//确认添加
								$(".sure-add-btn").on("click",function(){
									_this.ajaxAddTemp(callback,id);
								})
								//删除字段
								$(".del-property-btn").on("click",function(){
									if($(".wx-property-item").length>5){
										$(this).closest(".wx-property-item").prev(".wx-property-item").find(".del-property-btn").addClass("active");
									}
									$(this).closest(".wx-property-item").remove();	
								})
								//添加字段
								$(".add-property-btn").on("click",function(){
									var length = $(".wx-property-item").length;
									if(length>=4 && length<7){
										$(".wx-property-item").eq(length-1).find(".del-property-btn").removeClass("active");
										var temp = template.render(tpl.propertyTpl)({num: TEM_NUM[length]});
										$(".wx-property-list").append(temp);
										$(".del-property-btn").on("click",function(){
											if($(".wx-property-item").length>5){
												$(this).closest(".wx-property-item").prev(".wx-property-item").find(".del-property-btn").addClass("active");
											}
											$(this).closest(".wx-property-item").remove();
											
										})
									}
									
								})
							   
						   }   
					   },
					   error: function(){   
					   }
			   });	
			}
			
	};
	appSend.init();
})