
var userType = '';
var companyArr = []; // 运营中心列表
var companyId = '';
var orgArr = []; // 项目列表

// 设备列表
$(function () {
  var contextPath = $("#contextPath").val()
  var table;
  var orgId = "";
  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>',
    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>\
				  			<% 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 api = {
    init: function () {
      userType = $("#userType").val();
      console.log('userType==', userType)
      this.render();
      this.bindEvent();
    },
    render: function () {
      this.rendertable();
    },
    bindEvent: function () {
      var _this = this;
      //重置
      $(".set-btn").on("click", function () {
        $("#conditionform select").val("");

        let contextPathURL = window.location.hostname === 'localhost' ? '//wx.palmnest.com/super_cloud' : "/super_cloud"
        if (userType == 1 || userType == 2|| userType == 6) {
          $("#conditionform input:not('#comdId')").val("");
          $('#comdId').val(companyArr[0].label).attr('comd__id', companyArr[0].value).attr('meetCode', companyArr[0].meetCode);
          companyId = $("#conditionform #comdId").attr('comd__id');
          _this.setOrgData(contextPathURL);
        } else {
          $("#conditionform input:not('#orgId')").val("");
          companyId = localStorage.getItem("companyId")
          _this.setOrgData(contextPathURL);
        }
      });
      // 新增
      $(".add-ele-btn").on("click", function () {
        window.location.href = $("#contextPath").val() + "/admin/aboutOrg/addOrUpdate"
      })


      let contextPath = window.location.hostname === 'localhost' ? '//wx.palmnest.com/super_cloud' : "/super_cloud"
      if (userType == 1 || userType == 2|| userType == 6) {
        _this.getCompanyList({}, contextPath)
        $('body').on("focus", '#comdId', function (event) {
          _this.setOrgCompanyData($('#comdId'), 'comd__id', 'comd__span' , companyArr);
        });
        $('body').on('blur', '#comdId', function (event) {
          var _that = $(this)
          cjqt.search_fuzzy.event_blur(_that, 'comd__id')
        });
        $('body').on('click', '.select_wrap>.comd__span', function (event) {
          event.preventDefault();
          event.stopPropagation();
          /* Act on the event */
          var _that = $(this)
          cjqt.search_fuzzy.event_click(_that, 'comd__id', '#comdId')
          companyId = $("#conditionform #comdId").attr('comd__id')
          _this.setOrgData(contextPath);
        });
        $('body').on("input",'#comdId',function(event){ // input内容变化执行
          _this.setFuzzyFilter($('#comdId').val(), companyArr, backData => {
            _this.setOrgCompanyData($('#comdId'), 'comd__id', 'comd__span' , backData);
          })
        });
      } else {
        companyId = localStorage.getItem("companyId")
        _this.setOrgData(contextPath);
      }

      // 模糊搜索
		// 	_this.search_fuzzy()
    },
    setOrgData: function(contextPath) {
      var _this = this;
      _this.getOrgList({
        pageNo: 1,
        pageSize: 9999,
        "conditions[companyId]": companyId
      }, contextPath)
      $('body').on("focus", '#orgId', function (event) {
        _this.setOrgCompanyData($('#orgId'), 'org__id', 'org__span' , orgArr);
      });
      $('body').on('blur', '#orgId', function (event) {
        var _that = $(this)
        cjqt.search_fuzzy.event_blur(_that, 'org__id')
      });
      $('body').on('click', '.select_wrap>.org__span', function (event) {
        event.preventDefault();
        event.stopPropagation();
        /* Act on the event */
        var _that = $(this)
        cjqt.search_fuzzy.event_click(_that, 'org__id', '#orgId')
      });
      $('body').on("input",'#orgId',function(event){
        _this.setFuzzyFilter($('#orgId').val(), orgArr, backData => {
          _this.setOrgCompanyData($('#orgId'), 'org__id', 'org__span' , backData);
        })
      });
    },
    // 获取运营中心数据
    getCompanyList: function (obj, contextPath) {
      var _this = this;
      companyArr = [];
      $.ajax({
        url: contextPath + '/api/organisation/company/getselectlist',
        type: "POST",
        dataType: "json",
        data: obj,
        success: function (data) {
          if (data.code == 200 && data.data) {
            companyArr = data.data;
            _this.setInputData($('#comdId'), 'comd__id', 'comd__span' , companyArr);
            companyId = $("#conditionform #comdId").attr('comd__id')
            _this.setOrgData(contextPath);
          } else {
            layer.msg(data.msg);
          }
        }
      });
    },
    // 获取项目数据
    getOrgList(obj, contextPath) {
      var _this = this;
      orgArr = [];
      $.ajax({
        url: contextPath + '/api/organisation/organization/getselectlist',
        type: "POST",
        dataType: "json",
        data: obj,
        success: function (data) {
          if (data.code == 200 && data.data) {
            orgArr = data.data;
            _this.setInputData($('#orgId'), 'org__id', 'org__span', orgArr);
          } else {
            layer.msg(data.msg);
          }
        }
      });
    },
    setInputData: function(_this, attrName, liClassName, dataArr) {
      // 先清空
      _this.attr(attrName, '')
      var html = ''
      if (dataArr.length) {
        _this.val(dataArr[0].label).attr(attrName, dataArr[0].value).attr('meetCode', dataArr[0].meetCode);
        if (attrName == 'org__id') {
          $('#conditionform  .search-btn').click();
        }
        $.each(dataArr, function (index, el) {
          var meetCode = el.meetCode || ''
          html += '<span class="' + liClassName + '" id="' + el.value + '" meetCode="' + meetCode + '">'
          html += el.label
          html += '</span>'
        });
        _this.parent().find('.select_wrap').empty().append(html);
      } else {
        _this.val('').attr(attrName, '').attr('meetCode', '');
        _this.parent().find('.select_wrap').empty().hide()
      }
    },
    setOrgCompanyData: function(_this, attrName, liClassName, dataArr) {
      var html = ''
      if (dataArr.length) {
        _this.parent().find('.select_wrap').show()
        $.each(dataArr, function (index, el) {
          var meetCode = el.meetCode || ''
          html += '<span class="' + liClassName + '" id="' + el.value + '" meetCode="' + meetCode + '">'
          html += el.label
          html += '</span>'
        });
        _this.parent().find('.select_wrap').empty().append(html)
      } else {
        _this.parent().find('.select_wrap').empty().hide()
      }
    },
    setFuzzyFilter: function (strLabel, dataArr, backData) {
      const fuzzyArr = dataArr; // 内容省略
      const objArr = [];
      fuzzyArr.forEach(item => {
        if (item.label.includes(strLabel)) {
          objArr.push(item);
        }
      });
      backData(objArr);
    },
    // 模糊搜索事件
		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')
			});
		},
    rendertable: function () {
      var _this = this;
      layui.use(['table', 'laydate', 'form'], function () {
        table = layui.table;
        var form = layui.form,
          layer = layui.layer,
          laydate = layui.laydate;
        //日期
        laydate.render({
          elem: '#date1'
        });
        laydate.render({
          elem: '#date2'
        });
        //方法级渲染
        table.render({
          elem: '#LAY_table_user',
          url: $("#contextPath").val() + "/admin/aboutOrg/getList",
          method: "post",
          where: {
            orgId: $('#conditionform #orgId').attr('org__id'),
          },
          skin: 'nob' //行边框风格
            ,
          even: true //开启隔行背景
            ,
          size: 'lg' //小尺寸的表格
            ,
          cols: [
            [{
              field: 'index',
              title: '序号',
              width: '80',
              templet: '#indexTpl'
            }, {
              field: 'orgName',
              title: '项目名称',
              minWidth: 200
            }, {
              field: 'createTime',
              title: '发布时间',
              minWidth: 200
            }, {
              field: 'title',
              title: '标题',
              minWidth: 200
            }, {
              field: 'content',
              title: '内容',
              minWidth: 200
            },{
              field: 'type',
              title: '类型',
              minWidth: 200,
              templet: function (data) {
								//type 类型(1 服务类型 2资料文件)
								if (data.type == 1) {
									return '服务热线'
								} else if (data.type == 2) {
									return '资料文件'
								}else{
                  return '全部'
                }
							}
            },{
              field: 'hotLineName',
              title: '名称',
              minWidth: 200
            },{
              field: 'hotLine',
              title: '服务热线',
              minWidth: 200
            },{
              field: 'creator',
              title: '创建人',
              width: 120
            },{
                field: 'modifier',
                title: '编辑人',
                width: 120
              }, {
              title: '操作',
              fixed: 'right',
              width: 260,
              align: 'center',
              templet: function (data) {
                var str = '';
                str += '<button class="t-btn t-red-btn t-modify-btn" data-id=' + data.id + '  >修改</button>';
                str += '<button class="t-btn t-red-btn t-detail-btn" data-id=' + data.id + '  >详情</button>';
                str += '<button class="t-btn t-red-btn t-delete-btn" data-id=' + data.id + '  >删除</button>';
                return str;
              }
            }]
          ],
          id: 'testReload',
          page: true,
          response: {
            statusName: 'code' //数据状态的字段名称，默认：code
              ,
            statusCode: 200 //成功的状态码，默认：0
              ,
            countName: "count" //数据总数的字段名称，默认：count
              ,
            dataName: "data" //数据列表的字段名称，默认：data
          },
          request: {
            pageName: 'pageNo' //页码的参数名称，默认：page
              ,
            limitName: 'pageSize' //每页数据量的参数名，默认：limit
          },
          done: function (res, curr, count) {
            // 修改
            $(".t-modify-btn").on("click", function () {
              var id = $(this).data("id");
              window.location.href = $("#contextPath").val() + "/admin/aboutOrg/addOrUpdate?id=" + id;
            })
            // 删除
            $(".t-delete-btn").on("click", function () {
              var id = $(this).data("id");
              _this.ajaxDelTemp(id, function () {
                _this.againRenderTable();
              })
            })
            // 详情
            $(".t-detail-btn").on("click", function () {
              var id = $(this).data("id");
              _this.ajaxDetail(id, function (data) {
                _this.previewPhone(data);
              })
            })
          }
        });
        //查询
        $('.search-btn').on('click', function () {
          var org_Id = $("#conditionform #orgId").attr('org__id');
          if (!org_Id&&userType!=1&&userType!=2) {
            layer.msg('请选择项目')
            return;
          }
          _this.againRenderTable();
        });
      });
    },
    /*重新渲染table*/
    againRenderTable: function () {
      table.reload('testReload', {
        url: $("#contextPath").val() + "/admin/aboutOrg/getList",
        where: {
          title: $("#conditionform .title").val(),
          startTime: $("#date1").val(),
          endTime: $("#date2").val(),
          orgId: $('#conditionform #orgId').attr('org__id'),
          type: $("#conditionform  #type").val()
        },
        page: {
          curr: 1 //重新从第 1 页开始
        }
      });
    },
    /**
     * 删除
     * @param id 模板id
     * @param callback
     */
    ajaxDelTemp: function (id, callback) {
      var str = "确认删除?";
      layer.confirm(str, {
        btn: ['确定', '取消']
      }, function (index, layero) {
        layer.close(index); //如果设定了yes回调，需进行手工关闭
        $.ajax({
          type: "post",
          url: $("#contextPath").val() + "/admin/aboutOrg/deleteAboutOrg",
          data: {
            id: id
          },
          success: function (data) {
            if (data.code == 200) {
              callback();
            } else {
              layer.msg(data.msg)
            }
          },
          error: function () {
            // layer.msg('系统繁忙...')
          }
        });
      }, function (index) {

      });
    },
    /**
     * 预览
     *
     */
    previewPhone: function (data) {
      var wx = {
        title: data.title,
        con: data.content,
        showTip: true
      };
      var wxDetail = {
        type: 'detail',
        title: data.title,
        con: data.content,
        showTip: true,
      }
      //图文微信端
      $("body").append(template.render(tpl.wxTpl)(wx));

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

      var $wx = $(".wx-tpl");
      var $wxDetail = $(".notice-detail-tpl-detail");
      $wxDetail.hide();
      //微信端和APP段banner跳转
      $wx.find(".banner-wp").on("click", function () {
        $wx.hide();
        $wxDetail.show();
      });
      //点击返回
      $wxDetail.find(".back-btn").on("click", function () {
        $wx.show();
        $wxDetail.hide();
      });
      //tab切换
      $wx.find(".tab-right").on("click", function () {
        $wx.hide();
        $wxDetail.hide();
      });
      $wxDetail.find(".tab-right").on("click", function () {
        $wx.hide();
        $wxDetail.hide();
      });
      $(".notice-mask,.notice-close-btn").on("click", function () {
        $(".notice-wrapper").remove();
      })
    },
    /*获取详情*/
    ajaxDetail: function (id, callback) {
      var _this = this;
      $.ajax({
        type: "post",
        url: contextPath + "/admin/aboutOrg/getDetail",
        data: {
          "id": id
        },
        success: function (data) {
          if (data.code == 200) {
            callback(data.data)
          } else {
            layer.msg(data.msg)
          }
        },
        error: function (error) {
          layer.msg('error')
        }
      });
    },
    strlen: function (str) {
      var len = 0;
      for (var i = 0; i < str.length; i++) {
        var c = str.charCodeAt(i);
        //单字节加1
        if ((c >= 0x0001 && c <= 0x007e) || (0xff60 <= c && c <= 0xff9f)) {
          len++;
        } else {
          len += 2;
        }
      }
      return len;
    },
    // 两个数组去重
    array_diff: function (a, b) {
      for (var i = 0; i < b.length; i++) {
        for (var j = 0; j < a.length; j++) {
          if (a[j] == b[i]) {
            a.splice(j, 1);
            j = j - 1;
          }
        }
      }
      return a;
    }
  };
  api.init();
})
