/**
 * app公告发布
 * 2018/4/20 by liufang
 */
$(function () {
  var layer;
  var ERROR_OK = 200; //请求200
  var contextPath = $("#contextPath").val(); //请求前缀
  var editorC;
  var id ;
  var orgId = $('#orgId').attr('org__id');
  var fileIds = "";
  var arrList = []
  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>\
		  			<% 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 class="head-title"><%=title%></div>\
					  		</div>\
					  		<div class="notice-detail-con-wp">\
						  		<div class="notice-title-and-date">\
								  	<div class="title"><%=title%></div>\
						  		</div>\
						  		<div class="content"><%=con%></div>\
							</div>\
					  </div>  	\
			  		</div>\
			  		</div>\
			  		<div class="notice-con-right" >\
			  			<% if(!showTab){%>\
				  			<div class="notice-tabs clearfloat">\
				  				\
				  			</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>\
					  			<% 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>\
						  			<% if(showTip){%>\
						  				<div class="notice-tip" >提示：点击banner可查看跳转效果。</div>\
						  			<%}%>\
						  		</div>\
						  	</div>\
						  </div>'
  }

  var appPublish = {
    init: function () {
      this.render();
      this.bindEvent();
    },
    render: function () {
      var _this = this;
      id = _this.getQueryString("id");
      _this.renderEditor();
      if (!!id) {
        _this.ajaxDetail(id)
      }
    },
    bindEvent: function () {
      var _this = this;
      $("#graphic .radio-wp").on("click", function() {
				var type = $(".radio-wp .type:checked").data("status");
				if (type == 1) {
					$(".service-line").show();
					$(".source-file").hide();
				} else {
          $(".service-line").hide();
          $(".source-file").show();
          orgId = $('#orgId').attr('org__id')
          // 文件列表
          _this.get_file_list(orgId);
				}
      })
      // $("#orgId").change(function(){
      //   var type = $(".radio-wp .type:checked").data("status");
      //   if(type == 2){
      //     _this.get_file_list($("#orgId").val());
      //   }
      // })
      // 文件上传
			layui.use('upload', function () {
				var $ = layui.jquery,
          upload = layui.upload;
				var demoListView = $('#demoList'),
					uploadListIns = upload.render({
						elem: '#testList',
						url: $("#contextPath").val() + '/admin/enter/uploadFile',
            before: function(){    
              var data = {};    
              data.type = '25';  
              data.orgId = $('#orgId').val();    
              this.data = data;  
            },
						accept: 'file',
						multiple: true,
						auto: false,
						bindAction: '#testListAction',
						choose: function (obj) {
              if(!$('#orgId').val()){
                layer.msg("请先选择项目");
              }else{
                var files = this.files = obj.pushFile(); //将每次选择的文件追加到文件队列
                //读取本地文件
                obj.preview(function (index, file, result) {
                  var tr = $(['<tr id="upload-' + index + '">', '<td>' + file.name + '</td>', '<td>等待上传</td>', '<td>', '<button class=" layui-btn-xs demo-reload layui-hide">重传</button>', '<button class=" layui-btn-xs layui-btn-danger demo-delete">删除</button>', '</td>', '</tr>'].join(''));

                  // 单个重传
                  tr.find('.demo-reload').on('click', function () {
                    obj.upload(index, file);
                  });

                  //删除
                  tr.find('.demo-delete').on('click', function () {
                    delete files[index]; //删除对应的文件
                    tr.remove();
                    uploadListIns.config.elem.next()[0].value = ''; //清空 input file 值，以免删除后出现同名文件不可选
                  });
                  demoListView.append(tr);
                });
              }
						},
						done: function (res, index, upload) {
							if (res.code == "200") { //上传成功
                // $("#demoList").html(' ');
                arrList.push(res.data.id)
								var tr = demoListView.find('tr#upload-' + index),
									tds = tr.children();
								tds.eq(1).html('<span style="color: #5FB878;">已上传</span>');
                delete this.files[index];
								if(JSON.stringify(this.files) == "{}"){
									_this.get_file_list($('#orgId').attr('org__id'));
								}
								// tds.eq(2).html(''); //清空操作
								// if(	_this.delete_success_file(id)){
								// return delete this.files[index]; //删除文件队列已经上传成功的文件
								// }
							}
							this.error(index, upload);
						},
						error: function (index, upload) {
							var tr = demoListView.find('tr#upload-' + index),
								tds = tr.children();
							tds.eq(1).html('<span style="color: #FF5722;">上传失败</span>');
							tds.eq(2).find('.demo-reload').removeClass('layui-hide'); //显示重传
						}
					});
      })
      //发布banner图文消息绑定事件
      _this.bannerImageBindEvent();
      // 模糊搜索
			_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')
			});
		},
    //渲染编辑器
    renderEditor: function () {
      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 .submit-btn").on("click", function () {
        _this.noticeSubmit($("#graphic"), 'add');
      })
      //预览
      $("#graphic .preview-btn").on("click", function () {
        _this.noticeSubmit($("#graphic"), 'preview');
      })
      // 取消
      $(".cancel-btn").on("click",function(){
        window.location.href = contextPath + '/admin/aboutOrg/list';
      })
    },
    /**
     * 提交app公告
     * @param $dom 
     * @param func add新建 preview 预览
     */
    noticeSubmit: function ($dom, func) {
      console.log(fileIds)
      var _this = this;
      var params = {
        orgId: "",//项目
        title: "",//标题
        content: "",//内容
        id: "",//修改id
        hotLineName: "",//名称
        hotLine: "",//服务热线
        type: "",//类型
        fileIds: ""//文件
      };
      // 项目选择
      var orgId = $('#orgId').attr('org__id');
      if (!orgId) {
        layer.msg("请选择项目");
        return false;
      };
      params.orgId = orgId;
      var type = $(".radio-wp .type:checked").data("status");
      params.type = type;
      if (type == 1) {
        var hotLineName = $dom.find(".hotLineName").val()
        if (!hotLineName) {
          layer.msg("请输入名称");
          return false;
        };
        params.hotLineName = hotLineName;
        var hotLine = $dom.find(".hotLine").val()
        if (!hotLine) {
          layer.msg("请输入服务热线");
          return false;
        };
        params.hotLine = hotLine;
      } else {
        //标题
        var title = $dom.find(".title-con").val();
        if (!title) {
          layer.msg("请输入标题");
          return false;
        };
        params.title = title;
        //内容
        var ue;
        ue = UE.getEditor('myeditor_c');
        var content = ue.getContent();
        var contentTxt = ue.getContentTxt();
        if (!content) {
          layer.msg("请输入内容");
          return false;
        };
        params.content = content;
        //文件
        params.fileIds = fileIds;
      }
      
      if(!!id){
        params.id = id;
      }
      if (func == 'add') {
        console.log(params);
        _this.ajaxCreateApp(params, ue, $dom);
      } else {
        _this.previewPhone();
      }

    },
    /**
     * 新增
     */
    ajaxCreateApp: function (params) {
      var _this = this;
      $.ajax({
        type: "post",
        url: contextPath + "/admin/aboutOrg/addOrUpdateAboutOrg",
        data: params,
        success: function (data) {
          if (data.code == ERROR_OK) {
            window.location.href = contextPath + '/admin/aboutOrg/list';
          } else {
            layer.msg(data.msg)
          }
        },
        error: function () {
          layer.msg('error')
        }
      });
    },
    /**
     * 预览
     * 
     */
    previewPhone: function () {
      var wx = {
        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 = {
      //   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();
      // });
      $(".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 + "/admin/aboutOrg/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;
      $("#orgId").val(data.orgName);
      $('#orgId').attr('org__id',data.orgId)
      $("#graphic .title-con").val(data.title);
      $("#graphic .hotLineName").val(data.hotLineName);
      $("#graphic .hotLine").val(data.hotLine);
      if(data.type == 2){
        $(".radio-wp .type:last").attr('checked', 'checked');
        $(".service-line").hide();
        $(".source-file").show();
        orgId = $('#orgId').attr('org__id')
        fileIds = data.fileIds
        let arr = fileIds.split(";")
        arrList.concat(arr)
        console.log(arr,'arrList')
        // 文件列表
        _this.get_file_list(orgId);
        editorC.ready(function () {
          var ue = UE.getEditor('myeditor_c');
          ue.setContent(data.content);
        })
      }else{
        $(".service-line").show();
        $(".source-file").hide();
      }
    },
    	/**
		 * 获取已上传的文件列表
		 * 
		 */
		get_file_list: function (orgId) {
      if(fileIds==''){
        fileIds = arrList.join(";")
      }else{
        if(arrList.length>0){
          fileIds = fileIds + ";"+arrList.join(";")
        }else{
          fileIds = fileIds
        }
      }
			$("#demoList").html('');
			var orderIn = "";
			$.ajax({
				type: "post",
				url: contextPath + "/admin/enter/getFileList",
				data: {
					"type": '25',
          'orgId': orgId,
          'fileIds': fileIds?fileIds: '0'
				},
				success: function (data) {
					console.log(data, 666);
					if (data.code == "200") {
            let fileList = data.data;
            // let arr = []
						$.each(fileList, function (index, value) {
							var trs = "";
							trs += "<tr id=''><td>" + value.fileName + "</td><td>已上传</td><td><button class=' layui-btn-xs layui-btn-danger demo-delete deleteBtn' onclick='editPosition(" + value.id + ");'>删除</button></td></tr>";
              orderIn += trs;
              // arr.push(value.id)
						});
            $("#demoList").append(orderIn);
            // fileIds = arr.join(";")
					}
				},
				error: function () {
					return false
				}
			});
    },
  };
  editPosition = function (id) {
		$.ajax({
			type: "post",
			url: $("#contextPath").val() + "/admin/enter/deleteFile",
			data: {
				"id": id,
				'orgId': $('#orgId').attr('org__id')
			},
			success: function (data) {
				// console.log(data, 555);
				if (data.code == '200') {
          fileIds = ""
          arrList.forEach((item,index) => {
            if(item == id){
              arrList.splice(index,1)
            }
          })
          console.log(arrList)
					appPublish.get_file_list();
				}
			},
			error: function () {

			}
		});
	}
  appPublish.init();
})