// 设备列表
$(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 = {
    "updateTpl": '<div class="dialog-wp addTpl">\
    <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">\
            <div class="account-item required clearfloat">\
							<div class="item-tip">设备ID：</div>\
							<div class="item-con">\
								<label><%=deviceId%></label>\
							</div>\
						</div>\
            <div class="account-item required clearfloat">\
            <div class="item-tip"><span class="red">*</span>名称：</div>\
            <div class="item-con">\
              <input  type="text" class="item-input new-device-name" placeholder="请输入名称">\
            </div>\
          </div>\
           <div class="account-item required clearfloat">\
            <div class="item-tip"><span class="red">*</span>SN码：</div>\
            <div class="item-con">\
              <input  type="text" class="item-input new-device-code" placeholder="请输入设备上的serial number" value="">\
            </div>\
          </div>\
         <div class="dialog-btns">\
          <button class="sure-add-btn btn-red">确定</button>\
        </div>\
      </div>\
    </div>\
  </div>	',
    "modifyTpl": '<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"> \
              <div class="dialog-account-wp ">\
                <div class="account-item required clearfloat">\
                  <div class="item-tip"><span class="red">*</span>名称：</div>\
                  <div class="item-con">\
                    <input  type="text" class="item-input device-name" placeholder="请输入名称"  value="<%=deviceName%>">\
                  </div>\
                </div>\
              </div>\
            </li>\
            <li class="li1">\
              <label><span class="red">*</span>类型：</label>\
              <select class="item-select device-type">\
                <option value="">请选择设备类型</option>\
                <option value="1"  <%if(deviceType==1){%> selected <%}%> >闸机</option>\
                <option value="2" <%if(deviceType==2){%> selected <%}%> >梯控</option>\
                <option value="3" <%if(deviceType==3){%> selected <%}%> >门禁</option>\
              </select>\
            </li>\
            <li class="li1 spans">\
              <label><span class="red">*</span>地址：</label>\
              <div class="address">\
                <textarea class="device-address" placeholder="请输入地址"><%=address%></textarea>\
              </div>\
            </li>\
            <li class="li1 spans">\
            <label>备注：</label>\
            <div class="remark">\
              <textarea class="device-remark" placeholder="请填写备注"><%=remark%></textarea>\
            </div>\
          </li>\
           </ul>\
           <div class="dialog-btns">\
             <button class="sure-add-btn btn-red" style="margin-top: 25px">确定</button>\
            </div>\
        </div>\
      </div>\
    </div>',
    "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"> \
              <div class="dialog-account-wp ">\
                <div class="account-item required clearfloat">\
                  <div class="item-tip"><span class="red">*</span>名称：</div>\
                  <div class="item-con">\
                    <input  type="text" class="item-input device-name" placeholder="请输入名称">\
                  </div>\
                </div>\
                <div class="account-item required clearfloat">\
                  <div class="item-tip"><span class="red">*</span>SN码：</div>\
                  <div class="item-con">\
                    <input  type="text" class="item-input device-code" placeholder="请输入设备上的serial number" value="">\
                  </div>\
                </div>\
              </div>\
            </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();
      this.itemAjax();
    },
    bindEvent: function () {
      var _this = this;
      //重置
      $(".set-btn").on("click", function () {
        $("#conditionform input:not('#orgId'),#conditionform select").val("");
        _this.againRenderTable();
      });
      //新增
      $(".add-ele-btn").on("click", function () {
        $("body").append(template.render(tpl.addSecondTpl)({
          orgList: orgList
        }));
        //关闭弹窗
        $(".close-btn,.cancel-add-btn").on("click", function () {
          $(".dialog-wp").remove();
        });
        //确认添加
        $(".sure-add-btn").on("click", function () {
          if (!$(".dialog-wp #orgId").attr('org__id')) {
            layer.msg("请选择项目");
            return false;
          }
          if (!$(".dialog-wp .device-name").val()) {
            layer.msg("名称必填");
            return false;
          }
          if (!$(".dialog-wp .device-code").val()) {
            layer.msg("SN码必填");
            return false;
          }
          if (!$(".dialog-wp .device-type").val()) {
            layer.msg("类型为必选项");
            return false;
          }
          if (!$(".dialog-wp .device-address").val()) {
            layer.msg("地址为必填项");
            return false;
          }
          _this.submitAdd(function () {
            $(".dialog-wp").remove();
            _this.againRenderTable();
          });
        });
      });
      // 模糊搜索
      _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;
      layui.use(['table', 'laydate', 'form'], function () {
        table = layui.table;
        var form = layui.form,
          layer = layui.layer,
          laydate = layui.laydate;
        //日期
        laydate.render({
          elem: '#date1'
        });
        //方法级渲染
        table.render({
          elem: '#LAY_table_user',
          url: $("#contextPath").val() + "/lingling/getDeviceList",
          method: "post",
          where: {
            orgId: $("#orgId").attr('org__id')
          },
          skin: 'nob' //行边框风格
            ,
          even: true //开启隔行背景
            ,
          size: 'lg' //小尺寸的表格
            ,
          cols: [
            [{
              field: 'index',
              title: 'ID',
              width: '80',
              templet: '#indexTpl'
            }, {
              field: 'roleType',
              title: '类型',
              width: 120,
              templet: function (data) {
                if (data.deviceType == 1) {
                  return '闸机'
                } else if (data.deviceType == 2) {
                  return '梯控'
                } else if (data.deviceType == 3) {
                  return '门禁'
                }
              }
            }, {
              field: 'deviceId',
              title: '设备ID',
              minWidth: 200
            }, {
              field: 'deviceName',
              title: '名称',
              minWidth: 200
            }, {
              field: 'deviceCode',
              title: 'SN码',
              minWidth: 200
            }, {
              field: 'deviceStatus',
              title: '状态',
              width: 120,
              templet: function (data) {
                if (data.deviceStatus == true) {
                  return '<span>在线</span>'
                } else {
                  return '<span style="color:red">离线</span>'
                }
              }
            }, {
              field: 'address',
              title: '地址',
              minWidth: 200
            }, {
              field: 'createTime',
              title: '添加时间',
              minWidth: 200
            }, {
              field: 'remark',
              title: '备注',
              minWidth: 200
            }, {
              title: '操作',
              fixed: 'right',
              width: 260,
              align: 'center',
              templet: function (data) {
                var str = '';
                str += '<button class="t-btn t-red-btn t-modify-btn" data-deviceId=' + data.deviceId + ' data-orgId=' + data.orgId + '  >修改</button>';
                if (data.deviceStatus == true) {
                  str += '<button class="t-btn t-red-btn t-delete-btn" data-deviceId=' + data.deviceId + ' data-orgId=' + data.orgId + ' >禁用</button>';
                  str += '<button class="t-btn t-red-btn t-edit-btn" data-deviceId=' + data.deviceId + ' data-orgId=' + data.orgId + ' >更换</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) {
            //如果是异步请求数据方式，res即为你接口返回的信息。
            //删除
            $(".t-delete-btn").on("click", function () {
              var deviceId = $(this).data("deviceid");
              var orgId = $(this).data("orgid");
              _this.ajaxDelTemp(deviceId,orgId, function () {
                _this.againRenderTable();
              })
            });
            //更新
            $(".t-edit-btn").on("click", function () {
              var deviceId = $(this).data("deviceid");
              var orgId = $(this).data("orgid");
              _this.ajaxDetail(deviceId,orgId, function (data) {
                $("body").append(template.render(tpl.updateTpl)(data));
                //关闭弹窗
                $(".close-btn,.cancel-add-btn").on("click", function () {
                  $(".dialog-wp").remove();
                });
                //确认添加
                $(".sure-add-btn").on("click", function () {
                  _this.submitAdd(function () {
                    $(".dialog-wp").remove();
                    layer.msg("更新成功！");
                    _this.againRenderTable();
                  }, data.deviceId,data.orgId);
                })
              });
            });
            //修改
            $(".t-modify-btn").on("click", function () {
              var deviceId = $(this).data("deviceid");
              var orgId = $(this).data("orgid");
              _this.ajaxDetail(deviceId,orgId, function (data) {
                $("body").append(template.render(tpl.modifyTpl)(data));
                //关闭弹窗
                $(".close-btn,.cancel-add-btn").on("click", function () {
                  $(".dialog-wp").remove();
                });
                //确认添加
                $(".sure-add-btn").on("click", function () {
                  _this.submitAdd(function () {
                    $(".dialog-wp").remove();
                    layer.msg("更新成功！");
                    _this.againRenderTable();
                  }, data.deviceId,data.orgId);
                })
              });
            });
            //详情
            $(".t-publish-btn").on("click", function () {
              var id = $(this).data("id");
              var orgId = $(this).data("orgid");
              _this.ajaxDetail(id,orgId, function (data) {
                console.log(data);
                $("body").append(template.render(tpl.detailOne)(data));
                //关闭弹窗
                $(".close-btn,.sure-detail-btn").on("click", function () {
                  $(".dialog-wp").remove();
                });
              })
            });
          }
        });
        //查询
        $('.search-btn').on('click', function () {
          _this.againRenderTable();
        });
      });
    },
    /**
     * 删除模板
     * @param id 模板id
     * @param callback
     */
    ajaxDelTemp: function (deviceId,orgId, callback) {
      var str = "确认下线?";
      layer.confirm(str, {
        btn: ['确定', '取消']
      }, function (index, layero) {
        layer.close(index); //如果设定了yes回调，需进行手工关闭
        $.ajax({
          type: "post",
          url: $("#contextPath").val() + "/lingling/delDevice",
          data: {
            deviceId: deviceId,
            orgId:orgId
          },
          success: function (data) {
            if (data.code == 200) {
              callback();
            } else {
              layer.msg(data.msg)
            }
          },
          error: function () {
            // layer.msg('系统繁忙...')
          }
        });
      }, function (index) {

      });
    },

    /*重新渲染table*/
    againRenderTable: function () {
      table.reload('testReload', {
        where: {
          deviceType: $("#conditionform .deviceType").val(),
          deviceStatus: $("#conditionform .deviceStatus").val(),
          deviceId: $("#conditionform .deviceId").val(),
          deviceCode: $("#conditionform .deviceCode").val(),
          createTime: $("#date1").val(),
          orgId: $("#conditionform  #orgId").attr('org__id')
        },
        page: {
          curr: 1 //重新从第 1 页开始
        }
      });
    },
    //请求项目列表
    itemAjax: function () {
      $.ajax({
        type: "post",
        url: contextPath + "/admin/templ/getOrgList",
        success: function (data) {
          if (data.code == ERROK) {
            orgList = data.data;
          } else {
            layer.msg(data.msg)
          }
        },
        error: function (error) {
          layer.msg('error')
        }
      });
    },
    /**
     * 请求详情
     * @param id
     * @param callback
     */
    ajaxDetail: function (deviceId,orgId, callback) {
      var _this = this;
      $.ajax({
        type: "post",
        url: contextPath + "/lingling/getDeviceInfo",
        data: {
          deviceId: deviceId,
          orgId,orgId
        },
        success: function (data) {
          if (data.code == ERROK) {
            callback(data.data)
          } else {
            layer.msg(data.msg)
          }
        },
        error: function (error) {
          layer.msg('error')
        }
      });
    },
    /**
     * 新增或修改账号
     * @param callback
     * @param id
     */

    submitAdd: function (callback, deviceId,orgId) {
      var _this = this;
      if (!deviceId) {
        _this.ajaxAdd(function () {
          callback();
        })
      } else {
        _this.ajaxUpdate(deviceId,orgId, function () {
          callback();
        })
      }
    },

    /**
     * 新增
     * @param data
     * @param callbck
     */
    ajaxAdd: function (callback) {
      $.ajax({
        type: "post",
        url: $("#contextPath").val() + "/lingling/addDevice",
        data: {
          deviceName: $(".device-name").val(),
          deviceCode: $(".device-code").val(),
          deviceType: $(".dialog-wp .device-type").val(),
          address: $(".dialog-wp .device-address").val(),
          remark: $(".device-remark").val(),
          orgId: $(".dialog-wp #orgId").attr('org__id')
        },
        dataType: "json",
        success: function (data) {
          if (data.code == 200) {
            callback();
          } else {
            layer.msg(data.msg)
          }
        },
        error: function () {
          // layer.msg('系统繁忙.....')
        }
      });
    },
    /**
     * 替换设备
     * @param data
     * @param callbck
     */
    ajaxUpdate: function (deviceId, callback) {
      $.ajax({
        type: "post",
        url: $("#contextPath").val() + "/lingling/updateDevice",
        data: {
          deviceId: deviceId,
          newDeviceName: $(".new-device-name").val(),
          newDeviceCode: $(".new-device-code").val()
        },
        dataType: "json",
        success: function (data) {
          if (data.code == 200) {
            callback();
          } else {
            layer.msg(data.msg)
          }
        },
        error: function () {
          // layer.msg('系统繁忙.....')
        }
      });
    },
    /**
     * 修改设备信息
     * @param data
     * @param callbck
     */
    ajaxUpdate: function (deviceId,orgId, callback) {
      $.ajax({
        type: "post",
        url: $("#contextPath").val() + "/lingling/updateLocalDevice",
        data: {
          deviceName: $(".device-name").val(),
          deviceType: $(".dialog-wp .device-type").val(),
          address: $(".dialog-wp .device-address").val(),
          remark: $(".device-remark").val(),
          deviceId: deviceId,
          orgId:orgId
        },
        dataType: "json",
        success: function (data) {
          if (data.code == 200) {
            callback();
          } else {
            layer.msg(data.msg)
          }
        },
        error: function () {
          // layer.msg('系统繁忙.....')
        }
      });
    },
    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();
})