// 设备列表
$(function () {
  var ERROK = 200;
  var contextPath = $("#contextPath").val()
  var table;
  var orgList = [];
  var addressList = [];
  var departList = [];
  var companyList = [];
  template.config("escape", false);
  var orgId = "";
  var tpl = {
    "addSecondTpl": '<div class="dialog-wp detailOne">\
    <div class="mask"></div>\
    <div class="dialog dialog-account-con">\
      <div class="title-wp">\
        <span>新增设备</span>\
        <span class="close-btn"></button>\
      </div>\
      <div class="dialog-account-wp ">\
         <div class="account-list">\
         \
         <% if(orgList!=null&&orgList.length>1){ %>\
           <div class="account-item required clearfloat">\
            <div class="item-tip"><span class="red">*</span>项目：</div>\
            <div class="item-con">\
            <input class="item-select organ-id" name="orgId" id="orgId" autocomplete="off"/>\
            <span class="select_wrap _hide"></span>\
             </div>\
          </div>\
        <%}else if(orgList!=null&&orgList.length==1){%>\
           <div class="account-item required clearfloat" style="display: none">\
            <div class="item-tip"><span class="red">*</span>项目：</div>\
            <div class="item-con">\
              <input type="hidden" id="orgId" value="<%=orgList[0].id %>" org__id="<%=orgList[0].id %>"/>\
             </div>\
          </div>\
        <%}%>\
        \
           <ul class="list1">\
            <li class="li1"><label>名称：</label><span><%=data.deviceName%></span></li>\
            <li class="li1"><label>SN码：</label><span><%=data.deviceCode%></span></li>\
            <li class="li1"><label>设备ID：</label><span class="deviceId"><%=data.deviceId%></span></li>\
            <li class="li1">\
              <label><span class="red">*</span>类型：</label>\
              <select class="item-select device-type">\
              <option value="">请选择设备类型</option>\
              <option value="1">闸机</option>\
              <option value="2">梯控</option>\
              <option value="3">门禁</option>\
            </select>\
            </li>\
            <li class="li1 spans">\
              <label><span class="red">*</span>地址：</label>\
              <div class="address">\
                <textarea class="device-address" placeholder="请输入地址"></textarea>\
              </div>\
            </li>\
            <li class="li1 spans">\
            <label>备注：</label>\
            <div class="remark">\
              <textarea class="device-remark" placeholder="请填写备注"></textarea>\
            </div>\
          </li>\
           </ul>\
           <div class="dialog-btns">\
             <button class="sure-add-btn btn-red" style="margin-top: 25px">确定</button>\
            </div>\
      </div>\
    </div>\
  </div>	',
    "detailOne": '<div class="dialog-wp detailOne">\
					<div class="mask"></div>\
					<div class="dialog dialog-account-con">\
						<div class="title-wp">\
							<span>账号详情</span>\
							<span class="close-btn"></button>\
						</div>\
						<div class="dialog-account-wp ">\
							 <div class="account-list">\
								 <ul class="list1">\
									<li class="li1"><label>手机号码：</label><span><%=mobile%></span></li>\
									<li class="li1"><label>姓&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;名：</label><span><%=userName%></span></li>\
									<li class="li1"><label>积分余额：</label><span><%=integrale%></span></li>\
									<li class="li1"><label>部&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;门：</label>\
									<%for (var i=0;i<departList.length;i++){ %>\
										<% if(departList[i].id == dept){ %>\
											<span><%=departList[i].itemname%></span>\
										<%}%>\
									<%}%>\
									</li>\
									<li class="li1"><label>送餐地址：</label>\
										<%for (var i=0;i<addressList.length;i++){ %>\
											<% if(addressList[i].id == address){ %>\
												<span><%=addressList[i].itemname%></span>\
											<%}%>\
										<%}%>\
									</li>\
									<li class="li1">\
										<label>账号类型：</label>\
										<% if(roleType == "1"){ %>\
											<span>管理员</span>\
										<%}%>\
										<% if(roleType == "2"){ %>\
											<span>个人账户</span>\
										<%}%>\
										<% if(roleType == "3"){ %>\
											<span>可被代订</span>\
										<%}%>\
									</li>\
									<li class="li1 spans"><label>积分明细：</label>\
										<div class="integral">\
										<% if(recodeList != null){ %>\
											<%for (var i=0;i<recodeList.length;i++){ %>\
												<div class="integral-list">\
													<div><span class="left" style="color: #333333; font-size:15px"><%=recodeList[i].opTypeStr%></span>\
													<% if(recodeList[i].exchangeIntegral.indexOf("-") != -1){ %><span class="right greenC"><%=recodeList[i].exchangeIntegral%></span><%}%>\
													<% if(recodeList[i].exchangeIntegral.indexOf("-") == -1){ %><span class="right yellowC">+<%=recodeList[i].exchangeIntegral%></span><%}%>\
													</div>\
													<div style="font-size:13px"><span class="left"><%=recodeList[i].createTime%></span><span class="right">余额:<%=recodeList[i].newIntgrale%></span></div>\
												</div>\
											<%}%>\
										<%}%>\
										</div>\
									</li>\
								 </ul>\
								 <div class="dialog-btns">\
								 	<button class="sure-detail-btn btn-red">确定</button>\
							 	 </div>\
						</div>\
					</div>\
				</div>	',

  };
  var api = {
    init: function () {
      this.render();
      this.bindEvent();
    },
    render: function () {
      this.rendertable();
    },
    bindEvent: function () {
      var _this = this;
     
     
      // 模糊搜索
      _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')
      });
    },
    rendertable: function () {
      var _this = this;
      var datetime = new Date();
      var year = datetime.getFullYear();
      var month = datetime.getMonth() + 1 < 10 ? "0" + (datetime.getMonth() + 1) : datetime.getMonth() + 1;
      var date = datetime.getDate() < 10 ? "0" + datetime.getDate() : datetime.getDate();
      
      layui.use(['table', 'laydate', 'form'], function () {
        table = layui.table;
        var form = layui.form,
          layer = layui.layer,
          laydate = layui.laydate;
        //日期
        laydate.render({
          elem: '#date1',
          value:year+'-'+month+'-'+date
        });
        laydate.render({
          elem: '#date2',
          value:year+'-'+month+'-'+date
        });
        //方法级渲染
        table.render({
          elem: '#LAY_table_user',
          url: $("#contextPath").val() + "/lingling/getPassHistory",
          method: "post",
          where: {
            orgId: $("#orgId").attr('org__id'),
            startTime:year+'-'+month+'-'+date,
            endTime:year+'-'+month+'-'+date
          },
          skin: 'nob' //行边框风格
            ,
          even: true //开启隔行背景
            ,
          size: 'lg' //小尺寸的表格
            ,
          cols: [
            [{
              field: 'index',
              title: 'ID',
              width: '80',
              templet: '#indexTpl'
            }, {
              field: 'orgName',
              title: '项目',
              width: 120
            }, {
              field: '',
              title: '通行人（姓名、手机号）',
              width: 200,
              lineHeight: 20,
              templet: function (data) {
            	  var personStr =''
            	  if(data.userName){
            		  personStr = data.userName +"</br>"
            	  }
            	  if(data.mobile){
            		  personStr =personStr + data.mobile+"</br>"
            	  }
            	  return personStr
              }
            }, {
              field: 'deviceType',
              title: '通行设备（类型、ID、名称）',
              width: 200,
              lineHeight: 20,
              templet: function (data) {
                var list = ''
                if (data.deviceType == 1) {
                  list = '闸机'
                } else if (data.deviceType == 2) {
                  list = '梯控'
                } else if (data.deviceType == 3) {
                  list = '门禁'
                }
                if(data.deviceId){
                	list = list +"</br>"+data.deviceId
                }
                if(data.deviceName){
                	list = list +"</br>"+data.deviceName
                }
                return list
              }
            }, {
              field: 'openTime',
              title: '通行时间',
              minWidth: 200
            }, {
              field: 'passType',
              title: '通行方式',
              minWidth: 200,
              templet: function (data) {
                var str = '';
                if (data.passType && data.passType == 2) {
                  str += '令令开门'+'</br>';
                }
                if (data.passType && data.passType == 3) {
                  str += '访客登记（无闸机）'+'</br>';
                }
                if (data.passType && data.passType == 4){
                  str += '考拉';
                }
                return str
              }
            }, {
              field: 'type',
              title: '用户类型',
              width: 120,
              templet: function (data) {
                if (data.type == "1"||data.type == "3") {
                  return '员工'
                } else {
                  return '访客'
                }
              }
            }, {
              field: 'cardUid',
              title: '卡号',
              minWidth: 200
            }]
          ],
          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) {

          }
        });
        //查询
        $('.search-btn').on('click', function () {
        	var startTime=$('#date1').val()
        	var endTime=$('#date2').val()
        	var dayNumber=_this.dateDiff(endTime,startTime)
        	console.log("dayNumber",dayNumber)
        	if(dayNumber<0){//开始日期大于结束时间
        		layer.msg("请选择开始日期小于结束日期")
        		return false;
        	}else{
        		 _this.againRenderTable();
        	}
         
        });
        //重置
        $(".set-btn").on("click", function () {
         $("#conditionform input:not('#orgId'),#conditionform select").val("");
      	  var datetime = new Date();
            var year = datetime.getFullYear();
            var month = datetime.getMonth() + 1 < 10 ? "0" + (datetime.getMonth() + 1) : datetime.getMonth() + 1;
            var date = datetime.getDate() < 10 ? "0" + datetime.getDate() : datetime.getDate();
            $('#date1').val(year+'-'+month+'-'+date);
            $('#date2').val(year+'-'+month+'-'+date);
          _this.againRenderTable();
        });
        //导出报表
    	$(".export-excel-histtory").on("click", function () {
    		var startTime=$('#date1').val()
        	var endTime=$('#date2').val()
        	var dayNumber=_this.dateDiff(endTime,startTime)
        	console.log("dayNumber",dayNumber)
        	if(dayNumber<0){//开始日期大于结束时间
        		layer.msg("请选择开始日期小于结束日期")
        		return false;
        	}else if(dayNumber>365){//大于1年时间有问题
        		layer.msg("请选择开始日期结束日期间隔小于1年")
        		return false;
        	}else{
        		var str = "确定导出报表数据吗?";
    			layer.confirm(str, {
    				btn: ['确定', '取消']
    			}, function (index, layero) {
    				layer.close(index); //如果设定了yes回调，需进行手工关闭
    				_this.exportAjax();
    			}, function (index) {});
        	}
		})
      });
    },
    /*格式化时间*/
    
  //调用该方法(主方法)
     dateDiff:function(date1, date2){
    	 var _this = this;
        var type1 = typeof date1, type2 = typeof date2;
        if(type1 == 'string'){
        	 date1 = _this.stringToTime(date1);
        } else {
        	 date1 = date1.getTime();
        }
       
        if(type2 == 'string'){
        	date2 = _this.stringToTime(date2);
        } else {
        	date2 = date2.getTime();
        }
      
        return (date1 - date2) / 1000/3600/24;//结果是秒
    },

    //字符串转成Time(dateDiff)所需方法
     stringToTime:function(string){
        var f = string.split(' ', 2);
        var d = (f[0] ? f[0] : '').split('-', 3);
        var t = (f[1] ? f[1] : '').split(':', 3);
        return (new Date(parseInt(d[0], 10) || null,  (parseInt(d[1], 10) || 1)-1,  parseInt(d[2], 10) || null,
        parseInt(t[0], 10) || null,  parseInt(t[1], 10) || null, parseInt(t[2], 10) || null )).getTime();
    },
    /*重新渲染table*/
    againRenderTable: function () {
      table.reload('testReload', {
        where: {
          passPersonInfo: $("#conditionform .passPersonInfo").val(),
          passEqInfo: $("#conditionform .passEqInfo").val(),
          cardCode: $("#conditionform .cardCode").val(),
          startTime: $("#date1").val(),
          endTime: $("#date2").val(),
          passType: $("#conditionform .passType").val(),
          userType: $("#conditionform .userType").val(),
          orgId: $("#conditionform  #orgId").attr('org__id')
        },
        page: {
          curr: 1 //重新从第 1 页开始
        }
      });
    },
	//导出
	exportAjax: function () {
		var _this = this;
		let pageNo = $(".layui-laypage-em").next().html();
		let pageSize = $(".layui-laypage-limits").find("option:selected").val();
		$.ajax({
			type: "post",
			url: contextPath + "/lingling/exportPassHistory",
			data: {
				pageNo: pageNo,
				pageSize: pageSize,
				passPersonInfo: $("#conditionform .passPersonInfo").val(),
		          passEqInfo: $("#conditionform .passEqInfo").val(),
		          cardCode: $("#conditionform .cardCode").val(),
		          startTime: $("#date1").val(),
		          endTime: $("#date2").val(),
		          passType: $("#conditionform .passType").val(),
		          userType: $("#conditionform .userType").val(),
		          orgId: $("#conditionform  #orgId").attr('org__id')
			},
			success: function (data) {

				if (data.code == ERROK) {
					// location.href = data.data;
					location.href = $("#contextPath").val() + "/upload/PassHistoryExcel.xls";
				} 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();
})
