/**
 * 微信发布
 * 2021/7/30  此版本是微信模板审核 ，里面内容支持编辑
 */
$(function () {
  var layer;
  var editor;
  var coverFile;
  var noticeType;
  var contentType = 1;
  var detailApproveTyp="";
  var announceArr =[],graphArr = [];//临时存储搜素对象数组
  layui.use('layer', function () {
    layer = layui.layer;
  });
  //  layui.use('upload', function () {
  //    upload = layui.upload;
  //  });
  var tpl = {
    wxTpl: '<option value="">选择微信公众号</option>\
					<%for(var i=0;i<list.length;i++){%>\
						<option value="<%=list[i].ID%>"><%=list[i].name%></option>\
					<%}%>',
    tempTpl: '<option value="">选择模板消息</option>\
				<%for(var i=0;i<list.length;i++){%>\
					<option value="<%=list[i].id%>"><%=list[i].name%></option>\
				<%}%>',
    "settingTpl": '\
				<% for(var i=0;i<list.length;i++){%>\
			 		<div class="choose-infor-item clearfloat other-params">\
			 			<span class="wx-tips"><%=list[i].name %></span>\
			 			<%if(!!tempalteData && tempalteData.length>0){%>\
			 			  <input type="text" class="wx-input" value="<%=tempalteData[i].value%>" data-param="<%=list[i].name %>" data-key="<%=list[i].param_key %>" placeholder="请输入<%=list[i].name %>"/>\
			 			<%}else{%>  \
			 			  <input type="text" class="wx-input" value="" data-param="<%=list[i].name %>" data-key="<%=list[i].param_key %>" placeholder="请输入<%=list[i].name %>"/>\
			 			<%}%>  \
			 		</div>\
				<%}%>\
		 		<div class="choose-infor-item clearfloat">\
		 			<span class="wx-tips">原文链接</span>\
		 			<input type="text" class="wx-input wx-link" placeholder="请输入原文链接" value="<%=url%>"/>\
        </div>\
        <div class="choose-infor-item clearfloat">\
          <span class="wx-tips">发送对象</span>\
          <div class="public-item-con">\
            <div class="radio-wp radio-block" >\
              <span class="radio-input">\
                <input type="radio" id="pb-item" data-type="1"  class="radio-item" name="public" <%if(type==1){%> checked <%}%> />\
                <span class="radio-inner"></span>\
              </span>		\
              <label class="radio-con" for="pb-item">项目所有用户<span style="font-weight:normal">（关注公众号并登录过服务之窗的用户才能收到模版消息）</span></label>\
            </div>\
            <div class="radio-wp radio-block" >\
              <span class="radio-input">\
                <input type="radio" id="pb-some" data-type="2" class="radio-item" name="public" <%if(type==2){%> checked <%}%>>\
                <span class="radio-inner"></span>\
              </span>\
              <label class="radio-con" for="pb-some">项目部分用户</label>\
            </div>\
		    	<div class="radio-wp radio-block" >\
				<span class="radio-input">\
					<input type="radio" id="pb-export" data-type="3" class="radio-item" name="public" <%if(type==3){%> checked <%}%>>\
					<span class="radio-inner"></span>\
				</span>		\
				<label class="radio-con" for="pb-export">导入用户</label>\
				<div class="file-wp">\
					<input class="file-btn" type="file" />\
					<button class="btn-export-white" >导入</button>\
				</div>\
				<button class="btn-download-white download-mode">下载模板</button>\
			</div>\
            <div class="search-select-wp"></div>\
          </div>\
        </div>\
         ',
      searchTpl: '<div class="search-wp">\
        <div class="s-input-wp">\
          <input class="s-input" type="text" placeholder="输入内容以搜索" />\
          <span class="s-icon"></span>\
        </div>\
        <div class="choosed-person-wp"></div>\
        <div class="project-person-list"></div>\
      </div>'	,
    "chooseTpl": '<div class="choosed-person">\
        <span class="choosed-tip">已选用户：</span>\
        <% for(var i=0;i<list.length;i++){%>\
          <div class="person-item" data-userid="<%=list[i].userId%>" data-openid="<%=list[i].openId%>" >\
            <span class="person"><%=list[i].name%>  <%=list[i].mobile%></span>\
            <span class="peoject-del-btn" data-userid="<%=list[i].userId%>" ></span>\
          </div>\
        <%}%>\
        </div>'	,
        "projectTpl": '<div class="project-person-item">\
        <% for(var j=0;j<list.length;j++){%>\
          <div class="checkbox-wp">\
            <span class="checkbox-input">\
              <input type="checkbox" id="project-<%=list[j].userId%>" <%if(userIds.indexOf(list[j].userId+"")!=-1){%> checked <%}%> class="check-item" name="project-p-<%=list[j].userId%>" data-openid="<%=list[j].openId%>" data-name="<%=list[j].name%>"  data-mobile="<%=list[j].mobile%>" data-userid="<%=list[j].userId%>"/>\
              <span class="checkbox-inner"></span>\
            </span>\
            <label class="checkbox-con" for="project-<%=list[j].userId%>"> <%=list[j].name%>  <%=list[j].mobile%> <%=list[j].orgName%> </label>\
          </div>\
        <%}%>\
      </div>'	,
      exportPersonTpl: '<div class="export-list-wp">\
    	  <div class="clear-btn">清空</div>\
    	  <div class="project-person-item">\
        <% for(var j=0;j<list.length;j++){%>\
          <div class="checkbox-wp" >\
            <span class="checkbox-input">\
              <input type="checkbox" id="project-<%=list[j].id%>" checked class="check-item" name="project-p-<%=list[j].id%>" data-id="<%=list[j].id%>" data-name="<%=list[j].name%>"  data-mobile="<%=list[j].mobile%>"  data-virtname="<%=list[j].virtName%>"/>\
              <span class="checkbox-inner"></span>\
            </span>\
            <label class="checkbox-con" for="project-<%=list[j].id%>"> <%=list[j].name%>  <%=list[j].mobile%> <%=list[j].virtName%> </label>\
          </div>\
        <%}%>\
      </div>\
    	  </div>'	,
    link: '\
         <span class="tips">banner图片</span>\
             <div class="layui-upload width-470" style="overflow: hidden">\
               <div class="layui-upload-list img-style">\
                   <img class="layui-upload-img" id="demo1" style="width:100%;height:100%">\
                   <p id="demoText"></p>\
         </div>\
         <div class="clearfloat">\
             <button type="button" class="layui-btn btn-img-red float-right margin-left-10" id="delete">删除图片</button>\
             <button type="button" class="layui-btn float-right" id="test1">上传图片</button>\
           </div>\
             </div>\
             <div class="summary">\
             <span class="tips" style="margin-right: 34px">跳转链接</span>\
             <div class="layui-input-block" style="margin-left: 0">\
                 <textarea name="desc" placeholder="请输入摘要" class="layui-textarea" style="overflow: hidden;width: 50%" id="textarea"></textarea>\
             </div>\
         </div>\
         <div class="btns-wp">\
                 <button class="btn-white submit-btn">预览</button>\
                 <button class="btn-red submit-btn" id="submit-btn">提交发送</button>\
             </div>',
    graphic: '\
         <div class="titles-wp clearfloat">\
                 <span class="tips" style="margin-right: 62px;">主题</span>\
                 <input class="editot-input title-con" type="text" />\
               </div>\
               <div class="content-wp clearfloat" style="padding-left: 90px;">\
                 <div id="myeditor"></div>\
               </div>\
               <span class="tips">banner图片</span>\
               <div class="layui-upload width-470" style="overflow:hidden">\
                 <div class="layui-upload-list img-style">\
                   <img class="layui-upload-img" id="demo1" style="width:100%;height:100%">\
                   <p id="demoText"></p>\
           </div>\
           <div class="clearfloat">\
             <button type="button" class="layui-btn btn-img-red float-right margin-left-10" id="delete">删除图片</button>\
             <button type="button" class="layui-btn float-right" id="test1">上传图片</button>\
           </div>\
               </div>\
               <div class="summary">\
                 <span class="tips">banner图片</span>\
                 <div class="layui-input-block" style="margin-left: 0">\
                   <textarea name="desc" placeholder="请输入摘要" class="layui-textarea" style="overflow: hidden;width: 50%" id="textarea"></textarea>\
                 </div>\
               </div>\
               <div class="btns-wp">\
                 <button class="btn-white submit-btn">预览</button>\
                 <button class="btn-red submit-btn" id="submit-btn">提交发送</button>\
               </div>',
               "typeTpl": '<option value="">选择审核类型</option>\
					<% for(i=0;i<data.length;i++){%> \
						<option value="<%=data[i].id%>"><%=data[i].name%></option>\
						<%}%>'	,
            "typeTpl": '<option value="">选择审核类型</option>\
            <% for(i=0;i<data.length;i++){%> \
              <option value="<%=data[i].id%>"><%=data[i].name%></option>\
              <%}%>'	   

  }

  var orgList = [];
  var contextPath = $("#contextPath").val()
  var appPublish = {
    init: function () {
      this.renderWx()
      this.bindEvent();
     

    },
    renderWx: function () {
      var _this = this;
      var id = this.getQueryString("id");
      _this.renderOrgList();
     
      if (!!id) {
        this.ajaxDetail(id);
      }
    },
    renderEditor: function () {},
    bindEvent: function () {
      var _this = this;
      //提交微信发送
      $(".submit-btn").on("click", function () {
        _this.ajaxWxSubmit();
      });
      //点击返回
			$(".edit-back-btn").on("click",function(){
        window.location.href= contextPath+ '/notice/audit/noticeWxVerify';
     })
  	
      // 模糊搜索
      _this.search_fuzzy()
    },
    // 模糊搜索事件
    search_fuzzy: function(){
      $('body').on("input",'#orgId',function(event){
        var _this = $(this)
        cjqt.search_fuzzy.event_input(_this,'org__id','org__span',contextPath,'/admin/templ/getOrgListByName')
      });
      $('body').on("focus",'#orgId',function(event){
        var _this = $(this)
        cjqt.search_fuzzy.event_focus(_this,'org__id','org__span',contextPath,'/admin/templ/getOrgListByName')
      });
      $('body').on('blur','#orgId',function(event) {
        var _this = $(this)
        cjqt.search_fuzzy.event_blur(_this,'org__id')
      });
      $('body').on('click','.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')
      });
    },
    getApprovalTypeList(orgid){
      var _this=this
			$.ajax({
				type: "post",
				url: $("#contextPath").val() + "/notice/approval/getApprovalType",
				data: {
					"orgId": orgid
				},
				success: function (data) {
					if (data.code == 200) {
						$("#approvalType").html(template.render(tpl.typeTpl)(data));
            console.log("detailApproveTyp",_this.detailApproveTyp)
            $("#approvalType").val(_this.detailApproveTyp);
            
					} else {
						layer.msg(data.msg)
					}
				},
				error: function (error) {
					layer.msg('error')
				}
			});
		},
   //调用项目列表接口，如果是1个的话就显示审核
		getProjectList(){
      var	_this = this
			$.ajax({
				type: "post",
				url: $("#contextPath").val() + "/admin/templ/getOrgList",
				success: function (data) {
					if (data.code == 200) {
						if(data.data.length==1){
							_this.getIfCanApproval(data.data[0].id)
						}
					} else {
					}
				},
				error: function (error) {
					layer.msg('error')
				}
			});
		},
		getIfCanApproval(orgid){
      var _this=this
			$.ajax({
				type: "post",
				url: $("#contextPath").val() + "/notice/approval/getSetByOrgId",
				data: {
					"orgId":  orgid
				},
				success: function (data) {
					if (data.code == 200) {
						if(data.data.isOpen==1){//显示审核下拉列表
							$(".approvalStyle").show();
              _this.getApprovalTypeList(orgid)
						}else{////不显示审核下拉列表
							$(".approvalStyle").hide();
						}
					} else {
						layer.msg(data.msg)
					}
				},
				error: function (error) {
					layer.msg('error')
				}
			});
		},
    /**
     * 渲染项目
     * 
     */
    renderOrgList: function () {
      var _this = this;
      $(".org-list").on("change", function () {
        var id = $(this).val();
        if (id) {
          _this.renderWxNum(id);
        } else {
          $(".wx-list").html($("<option value=''>选择微信公众号</option>"))
        }

      })
      // $.ajax({
      //   type: "post",
      //   url: contextPath + "/admin/templ/getOrgList",
      //   success: function (data) {
      //     if (data.code == '200') {
      //   	orgList=data.data;
      //
      //     } else {
      //       layer.msg(data.msg)
      //     }
      //   },
      //   error: function (error) {
      //     layer.msg('error')
      //   }
      // });
    },


    //渲染搜索列表
		renderSearchList: function(){
			var _this = this;
			projectOrgId = '';
			//var orgId = '';
			var singleDom = $('.single-orgid')
			if(singleDom.length){
				projectOrgId = $("#orgId").attr('org__id');
				if (!orgId) {
					layer.msg("请选择项目");
					return false;
				};
			}else{
				if(!orgArr.length){
					layer.msg("请选择项目");
					return
				}
				$.each(orgArr,function(index, el) {
					if(index==orgArr.length-1){
						projectOrgId += el._org_id;
					}else{
						projectOrgId += el._org_id + ',' 
					}
				});	
			};
    },
    		/*
		 * 搜索事件
		 * @param type 1-公告 2-图文
		 */
		searchEvent(type){
			var _this = this;
			$('.s-input').keydown(function(e){
				var $dom = $(this).closest(".search-select-wp")
			    if(e.keyCode==13){
			        _this.getProjectSearch($dom,1,function(data){
			        	var idArr = []
			        	for(var i=0;i<announceArr.length;i++){
			        		idArr.push(announceArr[i].userId)
			        	};
			        	
			        	_this.searchChooseEvent(1,$dom,data,idArr)
			        });
			    }
			});
			$(".s-icon").on("click",function(){
				var $dom = $(this).closest(".search-select-wp")
				_this.getProjectSearch($dom,1,function(data){
					var idArr = []
		        	for(var i=0;i<announceArr.length;i++){
		        		idArr.push(announceArr[i].userId)
		        	}
		        	_this.searchChooseEvent(1,$dom,data,idArr)
		        });
			})
    },
    /**
		 * 点击搜索或者enter触发事件 //根据项目获取部分用户
		 * @param $dom 搜索框的父元素
		 * @param type 1-正常搜索 2-复现搜索
		 * @param callback 回调，搜索框的事件
		*/
		getProjectSearch($dom,type,callback){
			
			var _this = this;
			if(type==1){
        if (!$("#orgId").attr('org__id')) {
          layer.msg("请选择项目");
          return false;
        };
			}
			$.ajax({
				url: contextPath + '/notice/publicno/getUserByOrgId',
				type: "POST",
				dataType: "json",
				data: {
					orgIds: $("#orgId").attr('org__id'),//项目Id 以逗号分隔 最后面不要带逗号
					name: $(".search-wp .s-input").val(),//姓名、手机号、项目名 模糊搜索，默认传""
				},
				success: function (data) {
					if(data.code == 200 && data.data){
						callback(data.data)
					}else{
						layer.msg(data.msg);
					}
				},
				error: function(err){

				}
			});
    },
    /**
		 * 搜索事件
		 * @param type 1-正常搜索 2-复现搜索
		 * @param $dom 搜索框的父元素
		 * @param projectList 项目部分数据数组
		 */
		searchChooseEvent: function(type,$dom,projectList,chooseUserIds){
			var _this = this;
			if(type==1){
				$dom.find(".project-person-list").html(template.render(tpl.projectTpl)({list: projectList,userIds:chooseUserIds.join(",").split(',')}));
//				debugger
//				for(var i=0;i<projectList.length;i++){//userIds.indexOf(list[j].userId+"")!=-1
//					console.log(projectList[i].userId,chooseUserIds,chooseUserIds.indexOf(projectList[i].userId)!=-1);
//				}
//				$.each(projectList,function(ind,val){
//					if((chooseUserIds).indexOf(val.userId+'') !=-1){
//						announceArr.push({
//							userId:val.userId,
//							openId:val.openId,
//							name: val.name,
//							mobile:val.mobile
//						});
//					}
//				});
			}else{
				$dom.find(".project-person-list").html(template.render(tpl.projectTpl)({list: projectList,userIds:chooseUserIds.split(',')}));
				$.each(projectList,function(ind,val){
					if((chooseUserIds.split(',')).indexOf(val.userId+'') !=-1){
						announceArr.push({
							userId:val.userId,
							openId:val.openId,
							name: val.name,
							mobile:val.mobile
						});
					}
				});
				$dom.find(".choosed-person-wp").html(template.render(tpl.chooseTpl)({list: announceArr}));
				//删除选择用户
					$(".peoject-del-btn").on("click",function(){
						var userId = $(this).data("userid");
						$(this).closest(".person-item").remove();
						var arr = [];//临时数组
						$.each(announceArr,function(index,value){
							if(value.userId != userId){
								arr.push(value);
							}
						});
						announceArr = arr;
						$(".choose-infor-list #project-"+userId).prop("checked", false);
						if(announceArr.length==0){
							$dom.find(".choosed-person-wp").html("")
						}
					})	
			}
			$dom.find(".check-item").on("click",function(){
				var userId = $(this).data("userid");
				var openId = $(this).data("openid");
				var name = $(this).data("name");
				var mobile = $(this).data("mobile");
				//点击选择用户
				if($(this).prop("checked")){
					announceArr.push({
						userId:userId,
						openId:openId,
						name: name,
						mobile:mobile
					});
					$dom.find(".choosed-person-wp").html(template.render(tpl.chooseTpl)({list: announceArr}));
					console.log('before',announceArr)
					announceArr = _this.removalArr(announceArr);
					console.log('after',announceArr)
				}else{
					var arr = [];//临时数组
					$.each(announceArr,function(index,value){
						if(value.userId != userId){
							arr.push(value);
						}
					});
					announceArr = arr;
					$dom.find(".choosed-person-wp").html(template.render(tpl.chooseTpl)({list: announceArr}));
					if(announceArr.length==0){
						$dom.find(".choosed-person-wp").html("")
					}
				};
				//删除选择用户
				$(".peoject-del-btn").on("click",function(){
					var userId = $(this).data("userid");
					$(this).closest(".person-item").remove();
					var arr = [];//临时数组
					$.each(announceArr,function(index,value){
						if(value.userId != userId){
							arr.push(value);
						}
					});
					announceArr = arr;
					$(".choose-infor-list #project-"+userId).prop("checked", false);
					if(announceArr.length==0){
						$dom.find(".choosed-person-wp").html("")
					}
				})
			})
    },
        /**
     * 对象数组去重
     */
		removalArr: function  (arrData){
			var hash = {};
			arrData = arrData.reduce(function(item, next) {
			    hash[next.name] ? '' : hash[next.name] = true && item.push(next);
			    return item
			}, [])
			return arrData;
		}, 
    /**
     * 渲染公众号
     * @param orgId
     * @param type 'update' 修改微信消息 'add'或者'' 新增微信消息
     * @param wxId 公众号id
     * @param templateId 模板id
     * @param tempalteData 模板数据
     * @param url 原文链接
     * @param allData 详情全部数据
     */
    renderWxNum: function (orgId, type, wxId, templateId, tempalteData, url,allData) {
      var _this = this;
      $.ajax({
        type: "post",
        url: contextPath + "/notice/wxtemplateMessage/getPublicList",
        data: {
          orgIds: orgId
        },
        success: function (data) {
          var data = JSON.parse(data);
          if (data.code == '200') {
            $(".wx-list").html(template.render(tpl.wxTpl)({
              list: data.data
            }));
            if (type == 'update') {
              $(".wx-list").val(wxId);
              _this.renderTemp(wxId, templateId, tempalteData, url,allData);
            }
            $(".wx-list").on("change", function () {
              var id = $(this).val();
              if (id) {
                _this.renderTemp(id);
              } else {
                $(".temp-list").html($("<option value=''>选择消息模板</option>"))
              }

            })
          } else {
            layer.msg(data.msg)
          }
        },
        error: function (error) {
          layer.msg('error')
        }
      });
    },
    /**
     * 渲染模板
     * @param id 公众哈id
     *  @param templateId 模板id
     * @param tempalteData 模板数据
     * @param url 原文链接
     */
    renderTemp: function (id, templateId, tempalteData, url,allData) {
      var _this = this;
      $.ajax({
        type: "post",
        url: contextPath + "/notice/wxtemplateMessage/getTemplateList",
        data: {
          id: id
        },
        success: function (data) {
          var data = JSON.parse(data);
          if (data.code == '200') {
            $(".temp-list").html(template.render(tpl.tempTpl)({
              list: data.data
            }));
            if (!!templateId) {
              $(".temp-list").val(templateId);
              _this.renderProperty(templateId, tempalteData, url,allData);
            }
            $(".temp-list").on("change", function () {
              var id = $(this).val();
              _this.renderProperty(id);
            })
          } else {
            layer.msg(data.msg)
          }
        },
        error: function (error) {
          layer.msg('error')
        }
      });
    },
    /**
     * 渲染模板属性
     * @param  id
     * @param tempalteData 模板数据
     * @param url 原文链接
     */
    renderProperty: function (id, tempalteData, url,allData) {
      var _this = this;
      if (!id) {
        $(".choose-infor-list").html(template.render(tpl.settingTpl)({
          list: []
        }));
      //选择导入用户下载模板
    	$(".download-mode").on("click",function(){
    		location.href=contextPath+"/upload/NoticeUser.xlsx";
    	})
    	
          //选择项目部分用户
        $("#main-content-mode-wp .radio-block .radio-item").on("click",function(){
          var type = $("#main-content-mode-wp").find("input:radio[name='public']:checked").data("type");
          if(type==2){
            if (!$("#orgId").attr('org__id')) {
              layer.msg("请选择项目");
              return false;
            };
            announceArr = []
            $('#main-content-mode-wp  .file-btn').off("")
            //
            $("#main-content-mode-wp .search-select-wp").html(template.render(tpl.searchTpl));
            _this.searchEvent(1)
          }else if(type==3){
        	   $("#main-content-mode-wp .search-wp").remove();
				$("#main-content-mode-wp  .file-btn").on("change",function(){
					var $this = $(this);
					var fileName = $(this).val();
					var extension = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length);
					if (extension == "xlsx") {
						if (fileName == null || fileName == "") {
							layer.alert("数据导入为空,请按照模板填写资料后再导入!");
							return;
						};
						if (!$("#orgId").attr('org__id')) {
		                    layer.msg("请选择项目");
		                    return false;
		                  };
						_this.uploadUsers($this[0].files[0],$("#orgId").attr('org__id'))
					}else{
						layer.alert("请上传xlsx格式的文件");
					}
				})
			}else{
				$('#main-content-mode-wp  .file-btn').off("")
			$("#main-content-mode-wp .export-list-wp").remove();
            $("#main-content-mode-wp .search-wp").remove();
          }
        });
        return false;
      } else {
        $.ajax({
          type: "post",
          url: contextPath + "/notice/wxtemplateMessage/getTemplateConfig",
          data: {
            id: id
          },
          success: function (data) {
            var data = JSON.parse(data);
            if (data.code == '200') {
              var type = allData && allData.data1 && allData.data1.receive_type
              $(".choose-infor-list").html(template.render(tpl.settingTpl)({
                list: data.data,
                tempalteData: tempalteData,
                url: url,
                type: type ? type : 0,
              }));
              //选择导入用户下载模板
          	$(".download-mode").on("click",function(){
          		location.href=contextPath+"/upload/NoticeUser.xlsx";
          	})
          		if(type && type==3){
          			 $("#main-content-mode-wp .search-select-wp").html(template.render(tpl.exportPersonTpl)({list:allData.data5}));
					 $(".clear-btn").on("click",function(){
			          		$("#main-content-mode-wp .search-select-wp").html("")
		          	 })
          			$("#main-content-mode-wp  .file-btn").on("change",function(){
    					var $this = $(this);
    					var fileName = $(this).val();
    					var extension = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length);
    					if (extension == "xlsx") {
    						if (fileName == null || fileName == "") {
    							layer.alert("数据导入为空,请按照模板填写资料后再导入!");
    							return;
    						};
    						if (!$("#orgId").attr('org__id')) {
    		                    layer.msg("请选择项目");
    		                    return false;
    		                  };
    						_this.uploadUsers($this[0].files[0],$("#orgId").attr('org__id'))
    					}else{
    						layer.alert("请上传xlsx格式的文件");
    					}
    				})
          		}else if(type && type ==2){
          			$("#main-content-mode-wp .search-select-wp").html(template.render(tpl.searchTpl));
          			_this.searchEvent(1)
					_this.getProjectSearch($(".search-select-wp"),2,function(allData1){
						var userIds = [];
						allData.data5.forEach(function(ele,index){
							userIds.push(ele.id)
						})
			        	_this.searchChooseEvent(2,$(".search-select-wp"),allData1,userIds.join(","))
			        });
          		}
              //选择项目部分用户
              $("#main-content-mode-wp .radio-block .radio-item").on("click",function(){
                var type = $("#main-content-mode-wp").find("input:radio[name='public']:checked").data("type");
                if(type==2){
                  if (!$("#orgId").attr('org__id')) {
                    layer.msg("请选择项目");
                    return false;
                  };
                  announceArr = []
                  $('#main-content-mode-wp  .file-btn').off("")
                  $("#main-content-mode-wp .search-select-wp").html(template.render(tpl.searchTpl));
                  _this.searchEvent(1)
                }else if(type==3){
                	 $("#main-content-mode-wp .search-wp").remove();
    				$("#main-content-mode-wp  .file-btn").on("change",function(){
    					var $this = $(this);
    					var fileName = $(this).val();
    					var extension = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length);
    					if (extension == "xlsx") {
    						if (fileName == null || fileName == "") {
    							layer.alert("数据导入为空,请按照模板填写资料后再导入!");
    							return;
    						};
    						if (!$("#orgId").attr('org__id')) {
    		                    layer.msg("请选择项目");
    		                    return false;
    		                  };
    						_this.uploadUsers($this[0].files[0],$("#orgId").attr('org__id'))
    					}else{
    						layer.alert("请上传xlsx格式的文件");
    					}
    				})
    			}else{
    				$('#main-content-mode-wp  .file-btn').off("")
    				$("#main-content-mode-wp .export-list-wp").remove();
    	            $("#main-content-mode-wp .search-wp").remove();
                }
              });
            } else {
              layer.msg(data.msg)
            }
          },
          error: function (error) {
            layer.msg('error')
          }
        });
      }
    },
    /**
     * 提交发送微信信息
     * 
     */
    ajaxWxSubmit: function () {
      var _this=this
      //微信消息id
      var id = $(".submit-btn").data("id");
      //项目id
      var orgId = $("#orgId").attr('org__id');
      if (!orgId) {
        layer.msg("请选择项目");
        return false;
      };
      //微信公众号
      var wx = $(".wx-list").val();
      if (!wx) {
        layer.msg("请选择微信公众号");
        return false;
      };
      //消息模板
      var wechat_template_id = $(".temp-list").val();
      if (!wechat_template_id) {
        layer.msg("请选择消息模板");
        return false;
      };
      //标题
      var title = $(".temp-list option:selected").text();
      //				if(!title){
      //					layer.alert("请输入标题");
      //					return false;
      //				}
      //原文链接
      var url = $(".wx-link").val();
      if (url) {
        var regTxt = url.match(/^http:\/\//);
        var regTxts = url.match(/^https:\/\//);
        if (!regTxt && !regTxts) {
          layer.msg("输入有效链接");
          flag = false
          return false;
        }
      }

      //				if(!url){
      //					layer.alert("请输入原文链接");
      //					return false;
      //				}
      //其他参数
      var param1, param2, param3, param4, param5, param6, param7,
        key1, key2, key3, key4, key5, key6, key7,
        value1, value2, value3, value4, value5, value6, value7;
      var flag = true;
      $(".other-params").each(function (index, ele) {
        var value = $(ele).find(".wx-input").val();
        var key = $(ele).find(".wx-input").data("key");
        var param = $(ele).find(".wx-input").data("param")
        if (!value) {
          layer.msg("除原文链接外所有项都为必填");
          flag = false
          return false;
        }
        flag = true;
        (index == 0) && (param1 = param);
        (index == 0) && (key1 = key);
        (index == 0) && (value1 = value);
        (index == 1) && (param2 = param);
        (index == 1) && (key2 = key);
        (index == 1) && (value2 = value);
        (index == 2) && (param3 = param);
        (index == 2) && (key3 = key);
        (index == 2) && (value3 = value);
        (index == 3) && (param4 = param);
        (index == 3) && (key4 = key);
        (index == 3) && (value4 = value);
        (index == 4) && (param5 = param);
        (index == 4) && (key5 = key);
        (index == 4) && (value5 = value);
        (index == 5) && (param6 = param);
        (index == 5) && (key6 = key);
        (index == 5) && (value6 = value);
        (index == 6) && (param7 = param);
        (index == 6) && (key7 = key);
        (index == 6) && (value7 = value);
      })
      if (!flag) {
        return false;
      }
      var userIds = "";
      var receiveType = null;
      if(!$("#main-content-mode-wp").find("input:radio[name='public']:checked").data("type")){
        layer.msg("请选择发布对象");
        return false;
      }else if($("#main-content-mode-wp").find("input:radio[name='public']:checked").data("type")==2){
        if($(".person-item").length ==0 || $(".person-item").length <1){
          layer.msg("请选择用户,且用户不得少于两个！！");
          return false;
        }else{
          var useridArr =[];
          $(".person-item").each(function(index,ele){
            useridArr.push($(ele).data("userid"));
          })
          userIds = useridArr.join(",");
          receiveType = 2
        }
      }else if($("#main-content-mode-wp").find("input:radio[name='public']:checked").data("type")==3){
    	 
		 var beforeIds = []
		 var hasList = $(".export-list-wp .checkbox-wp");
		 if(hasList && hasList.length>0){
			 for(var i=0;i<hasList.length;i++){
				 if(hasList.eq(i).find("input").prop("checked")){
					 var $dom = hasList.eq(i).find("input")
					 beforeIds.push($dom.data("id"))
				 }
			 } 
		 }else{
			 layer.msg("请选择导入用户！");
	          return false;
		 }
		 userIds = beforeIds.join(",");
    	 receiveType = 3
      }else if($("#main-content-mode-wp").find("input:radio[name='public']:checked").data("type")==1){
        receiveType = 1
      }

      $.ajax({
        type: "post",
        url: contextPath + "/notice/wxtemplateMessage/saveOrUpdate",
        data: {
          wechat_template_id: wechat_template_id,
          orgId: orgId,
          title: title,
          url: url,
          receive_user_id: userIds,
          receive_type: receiveType,
          approvalType: $("#approvalType").val()?$("#approvalType").val():'',

          "param1": param1,
          "key1": key1,
          "value1": value1,
          "param2": param2,
          "key2": key2,
          "value2": value2,
          "param3": param3,
          "key3": key3,
          "value3": value3,
          "param4": param4,
          "key4": key4,
          "value4": value4,
          "param5": param5,
          "key5": key5,
          "value5": value5,
          "param6": param6,
          "key6": key6,
          "value6": value6,
          "param7": param7,
          "key7": key7,
          "value7": value7,
          id: !!id ? id : ''
        },
        success: function (data) {
          var data = JSON.parse(data);
          if (data.code == '200') {
             //调用审核接口
             _this.postApprovel(id)
          } else {
            layer.msg(data.msg)
          }
        },
        error: function () {
          layer.alert("审核失败")
        }
      });
    },
    //
    postApprovel(id){
      var id = $(".submit-btn").data("id");
      var type = $(".radio-item.status:checked").data("status")
	  var auditOpinion = $(".summary-con-wx").val()
      $.ajax({
        type: "post",
        async: false,
        url: contextPath + "/notice/wxtemplateMessage/approvalNew",
        async:false,
        data: {
          "id": id,
		  "state": type,
          "approvalOpinion":auditOpinion
        },
        success: function (data) {
        	console.log("返回",data.code)
        	if (data.code == '200') {
    			 console.log("返回",'11111')
    			 layer.msg('审核成功！')
    			 window.location.href = contextPath + '/notice/audit/noticeWxVerify';
			} else {
				console.log("返回",data.code=='100')
				layer.msg(data.msg)
			}
        },
        error: function (error) {
        	console.log("返回",'error')
          layer.msg('error')
        }
      });
    },
 
    /**
     * 获取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;
    },
    ajaxDetail: function (id) {
      var _this = this;
      $.ajax({
        type: "post",
        url: contextPath + "/notice/wxtemplateMessage/getDetail",
        data: {
          "id": id
        },
        success: function (data) {
          var data = JSON.parse(data);
          if (data.code == 200) {
            var result = data.data;
            $(".submit-btn").data("id", result.data1.id)
            $("#orgId").val(result.orgName);
            $("#orgId").attr("org__id",result.orgId);
            _this.detailApproveTyp=result.data1.approvalType
            _this.getProjectList();
            console.log("detailApproveTyp",_this.detailApproveTyp)
            _this.renderWxNum(result.data1.orgId, 'update', result.data3.id, result.data4.id, result.data2, result.data1.url,result)
          } else {
            layer.msg(data.msg)
          }
        },
        error: function (error) {
          layer.msg('error')
        }
      });
    },
    uploadUsers: function(file,orgId){
		var formData = new FormData();
		formData.append("orgId", orgId);
		formData.append("excelFile", file);
		$.ajax({
			url: contextPath + '/notice/publicno/importUserInfo',
			type: "POST",
			data: formData,
			cache: false, // 不缓存
			processData: false, // 告诉jQuery不要去处理发送的数据
			contentType: false, // 告诉jQuery不要去设置Content-Type请求
			success: function (data) {
				$("#main-content-mode-wp  .file-btn").val("")
				if(data.code == 200 || data.code ==300){
					 var res = data.data;
					 var beforeList = [];
					 var beforeMobiles = []
					 var hasList = $(".export-list-wp .checkbox-wp");
					 if(hasList && hasList.length>0){
						 for(var i=0;i<hasList.length;i++){
							 if(hasList.eq(i).find("input").prop("checked")){
								 var $dom = hasList.eq(i).find("input")
								 beforeList.push({
									 id: $dom.data("id"),
									 name: $dom.data("name"),
									 mobile: $dom.data("mobile"),
									 virtName: $dom.data("virtname"),
								 })
								 beforeMobiles.push($dom.data("mobile"))
							 }
						 } 
					 }
//					 console.log(beforeMobiles);debugger
					 for(var j=0;j<res.length;j++){
						 if(beforeMobiles.indexOf(+res[j].mobile) == -1){
							 beforeList.push(res[j])
						 }
					 }
//					 beforeList = .concat(res);
					 if(beforeList.length>0){
						 $("#main-content-mode-wp .search-select-wp").html(template.render(tpl.exportPersonTpl)({list:beforeList}));
						 $(".clear-btn").on("click",function(){
				          		$("#main-content-mode-wp .search-select-wp").html("")
			          	 })
					 }
					 
		          	 if(data.code == 300){
		          		 layer.msg(data.msg,{
		          			  time: 5000 //2秒关闭（如果不配置，默认是3秒）
		          			});
		          	 }
//				}else if(data.code == 300){
////					 $("#main-content-mode-wp .search-select-wp").html(template.render(tpl.exportPersonTpl)({list:beforeList}));
//					 $(".clear-btn").on("click",function(){
//			          		$("#main-content-mode-wp .search-select-wp").html("")
//		          	 })
//					 layer.msg(data.msg);
				}else{
					layer.msg(data.msg);
				}
			},
			error: function(err){
				$("#main-content-mode-wp  .file-btn").val("")
			}
		});
	}
  };
  appPublish.renderWxNum($("#orgId").attr('org__id'));
  appPublish.init();
})