/**
 * app公告发布
 * 2018/4/20 by liufang
 */
$(function () {
  var layer;
  var contentType = ''; //发布内容
  var ERROR_OK = 200; //请求200
  var contextPath = $("#contextPath").val(); //请求前缀
  var picture = '';
  var fileType = '';
  var typeImg = "";
  var editorA, editorB, editorC;
  layui.use('layer', function () {
    layer = layui.layer;
  });
  template.config("escape", false);
  var tpl = {
    noticeTpl: '<div class="notice-wrapper">\
		  	<div class="notice-mask"></div>\
		  	<div class="notice-close-btn"></div>\
		  	<div class="notice-content clearfloat">\
		  		<div class="notice-con-left"></div>\
		  		<div class="notice-con-right">\
		  			<div class="notice-tabs clearfloat">\
		  				<div class="tab tab-left active">微信端预览</div>\
		  				<div class="tab tab-right">app端预览</div>\
		  			</div>\
		  			<% if(showTip){%>\
		  				<div class="notice-tip" >提示：点击banner可查看跳转效果。</div>\
		  			<%}%>\
		  		</div>\
		  	</div>\
		  </div>',
    noticeDetailTpl: '<div class="notice-wrapper notice-detail-tpl notice-detail-tpl-<%=type%>">\
			  	<div class="notice-mask"></div>\
			  	<div class="notice-close-btn"></div>\
			  	<div class="notice-content clearfloat">\
			  		<div class="notice-con-left">\
					  <div class="notice-detail-wp">\
					  	<div class="notice-detail-con">\
						  	<div class="notice-detail-top">\
						  		<div class="back-btn"></div>\
					  		</div>\
					  		<div class="notice-detail-con-wp">\
						  		<div class="notice-title-and-date">\
								  	<div class="title"><%=title%></div>\
							  		<div class="date">04-12 10:30 &nbsp;&nbsp;编辑人：学友</div>\
						  		</div>\
						  		<div class="content"><%=con%></div>\
							</div>\
					  </div>  	\
			  		</div>\
			  		</div>\
			  		<div class="notice-con-right" >\
			  			<% if(!showTab){%>\
				  			<div class="notice-tabs clearfloat">\
				  				<div class="tab tab-left <%if(type=="detail"){%> active <%}%>">微信端预览</div>\
				  				<div class="tab tab-right <%if(type=="main"){%> active <%}%>"">app端预览</div>\
				  			</div>\
			  			<%}%>\
			  			<% if(showTip){%>\
			  				<div class="notice-tip" >提示：点击banner可查看跳转效果。</div>\
			  			<%}%>\
			  		</div>\
			  	</div>\
			  </div>',
    appTpl: '<div class="notice-wrapper app-tpl">\
				  	<div class="notice-mask"></div>\
				  	<div class="notice-close-btn"></div>\
				  	<div class="notice-content clearfloat">\
				  		<div class="notice-con-left">\
						  <div class="app-wp">\
						 	<div class="app-con">\
						 		<div class="banner-wp"  style="background-image: url( <%=banner%>)"></div>\
						 	</div>\
						 </div>\
				  		</div>\
				  		<div class="notice-con-right">\
				  			<div class="notice-tabs clearfloat">\
				  				<div class="tab tab-left ">微信端预览</div>\
				  				<div class="tab tab-right active">app端预览</div>\
				  			</div>\
				  			<% if(showTip){%>\
				  				<div class="notice-tip" >提示：点击banner可查看跳转效果。</div>\
				  			<%}%>\
				  		</div>\
				  	</div>\
				  </div>',
    wxTpl: '<div class="notice-wrapper wx-tpl">\
					  	<div class="notice-mask"></div>\
					  	<div class="notice-close-btn"></div>\
					  	<div class="notice-content clearfloat">\
					  		<div class="notice-con-left">\
								  <div class="wx-wp">\
								 	<div class="wx-con">\
							 		<div class="banner-wp"  style="background-image: url( <%=banner%>)"></div>\
							 	</div>\
							 </div>\
					  		</div>\
					  		<div class="notice-con-right">\
					  			<div class="notice-tabs clearfloat">\
					  				<div class="tab tab-left active">微信端预览</div>\
					  				<div class="tab tab-right">app端预览</div>\
					  			</div>\
					  			<% if(showTip){%>\
					  				<div class="notice-tip" >提示：点击banner可查看跳转效果。</div>\
					  			<%}%>\
					  		</div>\
					  	</div>\
					  </div>',
    noticeListTpl: '<div class="notice-wrapper notice-list-tpl">\
						  	<div class="notice-mask"></div>\
						  	<div class="notice-close-btn"></div>\
						  	<div class="notice-content clearfloat">\
						  		<div class="notice-con-left">\
									  <div class="notice-list-wp">\
									 	<div class="notice-list-con">\
										<div class="notice-item-wp">\
									 		<div class="banner-wp" style="background-image: url( <%=banner%>)"></div>\
									 		<div class="banner-descript"><%=title%></div>\
									 	</div>\
									</div>\
								</div>\
						  		</div>\
						  		<div class="notice-con-right">\
						  			<div class="notice-tabs clearfloat">\
						  				<div class="tab tab-left active">微信端预览</div>\
						  				<div class="tab tab-right">app端预览</div>\
						  			</div>\
						  			<% if(showTip){%>\
						  				<div class="notice-tip" >提示：点击banner可查看跳转效果。</div>\
						  			<%}%>\
						  		</div>\
						  	</div>\
						  </div>'
  }

  var appPublish = {
    init: function () {
      this.render();
      this.bindEvent();
    },
    render: function () {
      var _this = this;
      var id = _this.getQueryString("id");
      _this.renderEditor();
      if (!!id) {
        _this.ajaxDetail(id)
      }

    },
    bindEvent: function () {
      var _this = this;
      //选择发布内容变化
      $("#content").on("change", function () {
        //图文类型： 1 图文消息 ；2 跳转链接
        contentType = $(this).val();
        // console.log(contentType);
        if (!contentType) {
          $(".img-wrapper").css("background-image", "url(../../images/admin/notice_cover.png)");
          $(".app-publish-wrapper").hide();
        } else if (contentType == 1) {
          $(".img-wrapper").css("background-image", "url(../../images/admin/notice_cover.png)");
          $(".app-publish-wrapper").eq(1).show().siblings().hide();
        } else if (contentType == 2) {
          $(".img-wrapper").css("background-image", "url(../../images/admin/notice_cover.png)");
          $(".app-publish-wrapper").eq(0).show().siblings().hide();
        }
      });
      //发布banner图文消息绑定事件
      _this.bannerImageBindEvent();
      //发布banner跳转链接绑定事件
      _this.bannerLinkBindEvent();
    },
    //渲染编辑器
    renderEditor: function () {
      //banner的图文消息编辑器
      editorC = 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
      });
      editorC.render("myeditor_c");
      editorC.ready(function () {
        editorC.setHeight(400);
      });
    },


    //发布banner图文消息绑定事件
    bannerImageBindEvent: function () {
      var _this = this;
      //上传图片
      $("#graphic #inputImage").on("change", function (e) {
        var $dom = $(this)
        // $(".alert").css("display","block")
        _this.uploadImage($dom, e)
      });
      //提交发送
      $("#graphic .submit-btn").on("click", function () {
        _this.noticeSubmit(2, $("#graphic"), 'add');
      })
      //预览
      $("#graphic .preview-btn").on("click", function () {
        _this.noticeSubmit(2, $("#graphic"), 'preview');
      })
    },
    //发布banner跳转链接绑定事件
    bannerLinkBindEvent: function () {
      var _this = this;
      //上传图片
      $("#link #inputImage").on("change", function (e) {
        var $dom = $(this)
        // $(".alert").css("display","block")
        _this.uploadImage($dom, e)
      });
      //提交发送
      $("#link .submit-btn").on("click", function () {
        _this.noticeSubmit(3, $("#link"), 'add');
      })
      //预览
      $("#link .preview-btn").on("click", function () {
        _this.noticeSubmit(3, $("#link"), 'preview');
      })
    },
    /**
     * 上传图片
     * @param $dom 上传按钮dom
     * @param e 上传文件信息
     */
    uploadImage: function ($dom, e) {
      var _this = this;
      var fileName = e.target.value;
      var file = e.target.files[0];
      var size = e.target.files[0].size;
      var suffixIndex = fileName.lastIndexOf(".");
      var suffix = fileName.substring(suffixIndex + 1).toUpperCase();
      fileType = suffix.toLowerCase();
      if (suffix != "BMP" && suffix != "JPG" && suffix != "JPEG" && suffix != "PNG" && suffix != "GIF") {
        layer.msg('请上传图片（格式BMP、JPG、JPEG、PNG等）!');
        return false;
      };
    },
    /**
     * 提交app公告
     * @param type创建公告类型 1 公告 2 banner图文链接 3 banner跳转链接 4 生成链接
     * @param $dom 
     * @param func add新建 preview 预览
     */
    noticeSubmit: function (type, $dom, func) {
      var _this = this;
      var formData = new FormData();
      var id = $("#noticeId").val();
      var idNo = _this.getQueryString("id");
      if (!idNo){
        idNo = "";
      }
      formData.append("id", idNo);
      var contentType = $("#content").val();
      formData.append("contentType", contentType);
      

     
    //封面图片
		if(type==1){
			let url = $(".announcement-item").eq(0).find("#showImg").data("url");
			if(!url){
				layer.msg("请上传封面图片");
				return false;
			};
			formData.append("coverUrl", url);
		}else if (type != 4) {
			let typeImg = "image/" + fileType;
			let coverFile;
			var picture = $dom.find("#showImg").attr("src");

			if (!picture) {
				if (type == 1) {
					layer.msg("请上传封面图片");
				} else {
					layer.msg("请上传banner图片");
				}
				return false;
			}
			if (!!id && picture.indexOf('data:image') <= -1) {
				formData.append("coverFile", "");
			} else {
				coverFile = upload(picture, typeImg || "image/png");
				formData.append("coverFile", coverFile.get("pictures"));
			}

		}
      //正文
      var ue;
      if (type != 3) {
        if (type == 2) {
          ue = UE.getEditor('myeditor_c');
        }
          var content = ue.getContent(); //公告正文(带html标签)
          var contentTxt = ue.getContentTxt();//公告正文(纯文本)
          if (!content) {
              layer.msg("请输入公告正文");
              return false;
          };
          formData.append("content", content);
          formData.append("contentTxt", contentTxt);
      }
      // 跳转链接
      if (type == 3) {
        var url_address = $dom.find(".link-con").val();
        if (!url_address) {
          layer.msg("请输入跳转链接");
          return false;
        } else {
          var regTxt = url_address.match(/^http:\/\//);
          var regTxts = url_address.match(/^https:\/\//);
          if (regTxt || regTxts) {
            formData.append("url_address", url_address);
          } else {
            layer.msg("请输入正确的跳转链接");
            return false;
          }
        }
      }
      if (func == 'add') {
        _this.ajaxCreateApp(type, formData, ue, $dom);
      } else {
        _this.previewPhone(type);
      }

    },
    /**
     * 发请求创建新的app公告
     * @param formdata 提交的数据
     * @param type banner图文链接 3 banner跳转链接
     * @param $dom
     * @param ue 编辑器
     */
    ajaxCreateApp: function (type, formData, ue, $dom) {
      var id = $("#noticeId").val();
      $.ajax({
        type: "post",
        url: contextPath + "/notice/appNotice/saveUpdateDiscoverBanner",
        data: formData,
        cache: false, // 不缓存
        processData: false, // 告诉jQuery不要去处理发送的数据
        contentType: false, // 告诉jQuery不要去设置Content-Type请求头
        success: function (data) {
          if (data.code == ERROR_OK) {
            layer.msg("发送成功")

              type != 3 && ue.setContent('');
              $(".img-wrapper").css("background-image", "url(../../images/admin/notice_cover.png)");
              if (type == 3) {
                $dom.find(".link-con").val("");
              };

              window.location.href = contextPath + '/notice/banner/discoverBannerPage';
          } else {
            layer.msg(data.msg)
          }
        },
        error: function () {

          layer.msg('error')
        }
      });
    },
    /**
     * 预览
     * @param type 2 banner图文链接 3 banner跳转链接
     */
    previewPhone: function (type) {
      if (type == 2) {
        var wx = {
          banner: picture,
          title: $("#graphic .title-con").val(),
          con: UE.getEditor('myeditor_c').getContent(),
          showTip: true
        };
        var wxDetail = {
          type: 'detail',
          title: $("#graphic .title-con").val(),
          con: UE.getEditor('myeditor_c').getContent(),
          showTip: true,
        }
        var app = {
          banner: picture,
          title: $("#graphic .title-con").val(),
          con: UE.getEditor('myeditor_c').getContent(),
          showTip: true,
        }
        var appDetail = {
          type: 'main',
          title: $("#graphic .title-con").val(),
          con: UE.getEditor('myeditor_c').getContent(),
          showTip: true,
        };
        //图文微信端
        $("body").append(template.render(tpl.wxTpl)(wx));

        //图文app端
        $("body").append(template.render(tpl.appTpl)(app));

        //图文微信端详情
        $("body").append(template.render(tpl.noticeDetailTpl)(wxDetail));

        //图文app端详情
        $("body").append(template.render(tpl.noticeDetailTpl)(appDetail));
        var $wx = $(".wx-tpl");
        var $wxDetail = $(".notice-detail-tpl-detail");
        var $app = $(".app-tpl");
        var $appDetail = $(".notice-detail-tpl-main");
        $wxDetail.hide();
        $app.hide();
        $appDetail.hide();
        //微信端和APP段banner跳转
        $wx.find(".banner-wp").on("click", function () {
          $wx.hide();
          $wxDetail.show();
          $app.hide();
          $appDetail.hide();
        });
        $app.find(".banner-wp").on("click", function () {
          $wx.hide();
          $wxDetail.hide();
          $app.hide();
          $appDetail.show();
        });
        //点击返回
        $wxDetail.find(".back-btn").on("click", function () {
          $wx.show();
          $wxDetail.hide();
          $app.hide();
          $appDetail.hide();
        });
        $appDetail.find(".back-btn").on("click", function () {
          $wx.hide();
          $wxDetail.hide();
          $app.show();
          $appDetail.hide();
        });
        //tab切换
        $wx.find(".tab-right").on("click", function () {
          $wx.hide();
          $wxDetail.hide();
          $app.show();
          $appDetail.hide();
        });
        $wxDetail.find(".tab-right").on("click", function () {
          $wx.hide();
          $wxDetail.hide();
          $app.show();
          $appDetail.hide();
        });
        $app.find(".tab-left").on("click", function () {
          $wx.show();
          $wxDetail.hide();
          $app.hide();
          $appDetail.hide();
        });
        $appDetail.find(".tab-left").on("click", function () {
          $wx.show();
          $wxDetail.hide();
          $app.hide();
          $appDetail.hide();
        });
      } else if (type == 3) {
        var wx = {
          banner: picture
        };
        var app = {
          banner: picture
        }
        //图文微信端
        $("body").append(template.render(tpl.wxTpl)(wx));

        //图文app端
        $("body").append(template.render(tpl.appTpl)(app));

        var $wx = $(".wx-tpl");

        var $app = $(".app-tpl");
        $app.hide();

        //tab切换
        $wx.find(".tab-right").on("click", function () {
          $wx.hide();

          $app.show();

        });
        $app.find(".tab-left").on("click", function () {
          $wx.show();

          $app.hide();

        });
      }
      $(".notice-mask,.notice-close-btn").on("click", function () {
        $(".notice-wrapper").remove();
      })
    },
    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/appNotice/getDetail",
        data: {
          "id": id
        },
        success: function (data) {
          if (data.code == 200) {
            _this.renderNotice(data.data)
          } else {
            layer.msg(data.msg)
          }
        },
        error: function (error) {
          layer.msg('error')
        }
      });
    },
    /**
     * 复现公告
     * @param data 详情数据
     */
    renderNotice: function (data) {
      var _this = this;
      $("#noticeId").val(data.id);
      // console.log(data,'编辑');
      // $("#orgId").val(data.orgId);
      //noticeType 公告类型： 1 公告 ；2 banner图；3 跳转链接；4 商圈banner
      //图文类型contentType： 1 图文消息 ；2 跳转链接
      if (data.contentType == 1) {
        $("#content").val(1);
        picture = data.coverUrl;
        $(".img-wrapper").css("background-image", "url(" + data.coverUrl + ")");
        $("#graphic #showImg").attr("src",data.coverUrl)
        $(".app-publish-wrapper").eq(1).show().siblings().hide();
        $("#graphic .title-con").val(data.title);
        editorC.ready(function () {
          var ue = UE.getEditor('myeditor_c');
          ue.setContent(data.content);
        })
        if (data.positionType == 0) {
          $('input:checkbox[name="app2"]').prop("checked", true);
          $('input:checkbox[name="wx2"]').prop("checked", true)
        } else if (data.positionType == 1) {
          $('input:checkbox[name="app2"]').prop("checked", true);

        } else if (data.positionType == 2) {
          $('input:checkbox[name="wx2"]').prop("checked", true)
        }
      } else if (data.contentType == 2) {
        $("#content").val(2);
        picture = data.coverUrl;
        $(".img-wrapper").css("background-image", "url(" + data.coverUrl + ")");
        $(".app-publish-wrapper").eq(0).show().siblings().hide();
        $("#link #showImg").attr("src",data.coverUrl)
        $(".link-con").val(data.urlAddress);
        if (data.positionType == 0) {
          $('input:checkbox[name="app3"]').prop("checked", true);
          $('input:checkbox[name="wx3"]').prop("checked", true)
        } else if (data.positionType == 1) {
          $('input:checkbox[name="app3"]').prop("checked", true);
        } else if (data.positionType == 2) {
          $('input:checkbox[name="wx3"]').prop("checked", true)
        }
      }
    }
  };
  appPublish.init();


  // 图片裁剪
  $("#imgCutConfirm").bind("click", function () {
	  var typeImg = "image/" + '';
		setTimeout(function () {
			 //控制图片大小不大于1M
			if($("#state").val()==2 && $("#content").val()==1 ){//图文
				if((upload($("#graphic #showImg").attr('src'), typeImg || "image/png").get("pictures")).size>1024*1024*1024){
					layer.alert('图片大小须在1M以内!');
					return false;
				};
			}else if($("#state").val()==2 && $("#content").val()==2 ){//跳转链接
				if(( upload($("#link #showImg").attr('src'), typeImg || "image/png").get("pictures")).size>1024*1024*1024){
					layer.alert('图片大小须在1M以内!');
					return false;
				};
			}
			if($("#state").val()!=1){
				$("#containerDiv").hide();
				$("#imgEdit").hide();
				$("#getCroppedCanvasModal").modal("hide");
			}
			
    }, 500)
  })
})