// 设备列表
$(function() {
  var ERROK = 200;
  var contextPath = $("#contextPath").val()
  var table;
  var orgList = [];
  var deviceList = [];
  var departList = [];
  var companyList = [];
  var fkj_orgId //访客机orgId
  var fkj_machineId //访客机machineId
  template.config("escape", false);
  var orgId = "";
  var tpl = {
    "addTpl": '<div class="dialog-wp addTpl">\
					<div class="mask"></div>\
					<div class="dialog dialog-account-con add-power">\
						<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 staff addPower" data-type="1">\
                \
                </div>\
                <div class="titleT">员工</div>\
                <div class="account-item required clearfloat visitor addPower" data-type="2">\
                \
                </div>\
                <div class="titleT">访客</div>\
						</div>\
					</div>\
				</div>	',
    "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"><span class="red">*</span>名称：</div>\
            <div class="item-con">\
              <input  type="text" class="item-input new-power-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="AFFFFDDDFF101">\
            </div>\
          </div>\
         <div class="dialog-btns">\
          <button class="sure-add-btn btn-red">确定</button>\
        </div>\
      </div>\
    </div>\
  </div>	',
    "addPowerTpl": '<div class="dialog-wp detailOne">\
    <div class="mask"></div>\
    <div class="dialog dialog-account-con">\
      <div class="title-wp">\
        <span>新增<%=title %>通行权限</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><span class="red">*</span>名称：</label>	<input  type="text" class="item-input power-name setName" placeholder="请输入名称"></li>\
            <li class="li1 clearfloat">\
            <label class="mt15"><span class="red">*</span>通行设备：</label>\
            <div class="set-account-num">\
            \
            </div>\
          </li>\
    		<%if(groupType !=1){%>\
	    		<li class="li1 clearfloat">\
	    			<label class="mt15">可用日期：</label>\
			    	<div class="port-con" style="float: left;padding-top:15px;">\
						<div class="checkbox-wp">\
							<span class="checkbox-input">\
								<input type="checkbox" id="isWorkday" class="check-item"  name="isWorkday" checked/>\
								<span class="checkbox-inner"></span>\
							</span>\
							<label class="checkbox-con" for="isWorkday">工作日</label>\
						</div>\
						<div class="checkbox-wp">\
							<span class="checkbox-input">\
								<input type="checkbox" id="isWeek" class="check-item"  name="isWeek" checked/>\
								<span class="checkbox-inner"></span>\
							</span>\
							<label class="checkbox-con" for="isWeek">休息日</label>\
						</div>\
						<div class="checkbox-wp">\
							<span class="checkbox-input">\
								<input type="checkbox" id="isHoliday" class="check-item"  name="isHoliday" checked/>\
								<span class="checkbox-inner"></span>\
							</span>\
							<label class="checkbox-con" for="isHoliday">节假日</label>\
						</div> \
					</div>\
	    		</li>\
			    	<li class="li1 clearfloat">\
					<label class="mt15">可用时段限制：</label>\
			    	<div class="port-con" style="float: left;padding-top:15px;">\
						<div class="checkbox-wp">\
							<span class="checkbox-input">\
								<input type="checkbox" id="isUseLimit" class="check-item"  name="isUseLimit" />\
								<span class="checkbox-inner"></span>\
							</span>\
							<label class="checkbox-con" for="isUseLimit">启用</label>\
						</div>\
				    	<div class="layui-inline limit-time">\
					        \
					        <div class="layui-input-inline">\
					          <input type="text" class="layui-input" id="beginTime" placeholder="起始时间">\
					        </div> ~ \
					    	<div class="layui-input-inline">\
						        <input type="text" class="layui-input" id="endTime" placeholder="结束时间">\
						      </div>\
				      	</div>\
					</div>\
				</li>\
    		<%}%>	\
            <li class="li1 spans clearfloat">\
            <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>	',
    "editPowerTpl": '<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 clearfloat"><label><span class="red">*</span>名称：</label><input  type="text" class="item-input power-name groupName" value="<%=detail.groupName%>" disabled></li>\
          <li class="li1 clearfloat" style="margin-top:15px;"><label><span class="red">*</span>类型：</label>\
            <% if(detail.groupType == "1"){ %>\
              <input  type="text" class="item-input power-name groupType" data-type="<%=detail.groupType%>" value="员工" disabled>\
            <%}else if(detail.groupType == "2"){%>\
              <input  type="text" class="item-input power-name groupType" data-type="<%=detail.groupType%>" value="访客" disabled>\
            <%}%>\
          </li>\
          <li class="li1 clearfloat">\
            <label class="mt15"><span class="red">*</span>通行设备：</label>\
            <div class="set-account-num">\
            <%for(var i=0;i<data.length;i++){%>\
              <label><input type="checkbox" name="account" value="<%=data[i].id%>" <% if(data[i].isChecked){ %>checked="checked"<%}%>><span><%=data[i].deviceName%></span></label>\
            <%}%>\
            </div>\
          </li>\
    	<%if(detail.groupType !=1){%>\
		<li class="li1 clearfloat">\
			<label class="mt15">可用日期：</label>\
	    	<div class="port-con" style="float: left;padding-top:15px;">\
				<div class="checkbox-wp">\
					<span class="checkbox-input">\
						<input type="checkbox" id="isWorkday" class="check-item"  name="isWorkday" <%if(detail.isWorkday==1){%>checked <%}%>  />\
						<span class="checkbox-inner"></span>\
					</span>\
					<label class="checkbox-con" for="isWorkday">工作日</label>\
				</div>\
				<div class="checkbox-wp">\
					<span class="checkbox-input">\
						<input type="checkbox" id="isWeek" class="check-item"  name="isWeek" <%if(detail.isWeek==1){%>checked <%}%> />\
						<span class="checkbox-inner"></span>\
					</span>\
					<label class="checkbox-con" for="isWeek">休息日</label>\
				</div>\
				<div class="checkbox-wp">\
					<span class="checkbox-input">\
						<input type="checkbox" id="isHoliday" class="check-item"  name="isHoliday" <%if(detail.isHoliday==1){%>checked <%}%> />\
						<span class="checkbox-inner"></span>\
					</span>\
					<label class="checkbox-con" for="isHoliday">节假日</label>\
				</div> \
			</div>\
		</li>\
	    	<li class="li1 clearfloat">\
			<label class="mt15">可用时段限制：</label>\
	    	<div class="port-con" style="float: left;padding-top:15px;">\
				<div class="checkbox-wp">\
					<span class="checkbox-input">\
						<input type="checkbox" id="isUseLimit" class="check-item"  name="isUseLimit" <%if(detail.isUseLimit==1){%>checked <%}%>/>\
						<span class="checkbox-inner"></span>\
					</span>\
					<label class="checkbox-con" for="isUseLimit">启用</label>\
				</div>\
		    	<div class="layui-inline limit-time" <%if(detail.isUseLimit==1){%> style="display:none;" <%}%>>\
			        \
			        <div class="layui-input-inline">\
			          <input type="text" class="layui-input" id="beginTime" placeholder="起始时间" value="<%=detail.beginTime%>">\
			        </div> ~ \
			    	<div class="layui-input-inline">\
				        <input type="text" class="layui-input" id="endTime" placeholder="结束时间" value="<%=detail.endTime%>">\
				      </div>\
		      	</div>\
			</div>\
		</li>\
	<%}%>	\
          <li class="li1 spans clearfloat">\
          <label>备注：</label>\
          <div class="remark">\
            <textarea class="device-remark" placeholder="请填写备注"><%=detail.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>	',
    "detailTpl": '<div class="dialog-wp detailTpl">\
					<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><%=groupName%></span></li>\
									<li class="li1">\
										<label>类型：</label>\
										<% if(groupType == "1"){ %>\
											<span>员工</span>\
										<%}%>\
										<% if(groupType == "2"){ %>\
											<span>访客</span>\
										<%}%>\
									</li>\
                  <% if(modifyTime){ %><li class="li1"><label>更新时间：</label><span><%=modifyTime%></span></li>	<%}%>\
                  <li class="li1"><label>通行设备：</label><span><%=deviceNames%></span></li>\
    			 <%if(groupType==2){%> \
    			 	<li class="li1">\
    					<label>可用日期：</label>\
    					<span><%if(isWorkday==1){%>工作日&nbsp;  <%}%><%if(isWeek==1){%>休息日 &nbsp;<%}%><%if(isHoliday==1){%>节假日 <%}%></span>\
    				</li>\
			    	<li class="li1">\
						<label>可用时段限制：</label>\
						<span><%if(isUseLimit==1){%>启用   &nbsp; &nbsp;  <%=beginTime%> ~ <%= endTime%> <%}else{%> 不启用 <%}%></span>\
					</li>\
    			 <%}%>\
                  <li class="li1"><label>备注：</label><span><%=remark%></span></li>\
								 </ul>\
						</div>\
					</div>\
				</div>	',
        fkjNewModeTpl: '<div class="part_ part_state clearfloat">\
                    <div class="part_title float-left">访客机SN</div>\
                    <div class="part_content float-left">\
                      <div class="radio-wp">\
                         <li class="goal_li clearfloat"><input type="text" class="SN-input" value="<%=res.deviceCode%>"/></li>\
                      </div>\
                    </div>\
                    <div class="part_title float-left">访客机JSON</div>\
                    <div class="part_content float-left">\
                      <div class="radio-wp">\
                         <li class="goal_li clearfloat"><textarea class="JSON-input" cols="60" style="max-width: 400px; max-height: 500px;" rows="3"><%=res.machineJson%></textarea></li>\
                      </div>\
                    </div>\
                  </div>',
        fkjOldModeTpl:' <div class="part_ part_state clearfloat">\
                    <div class="part_title float-left">上传身份证头像</div>\
                    <div class="part_content float-left">\
                      <div class="radio-wp">\
                         <span class="radio-input">\
                          <% if(res.isUploadIdenphoto){ %>\
                            <input type="radio" id="status11" class="radio-item status1" data-status="1" name="status1" checked/>\
                          <%}else{%>\
                            <input type="radio" id="status11" class="radio-item status1" data-status="1" name="status1"/>\
                          <%}%>\
                          <span class="radio-inner"></span>\
                         </span>\
                         <label class="radio-con" for="status11">是</label>\
                      </div>\
                      <div class="radio-wp">\
                         <span class="radio-input">\
                          <% if(res.isUploadIdenphoto){ %>\
                            <input type="radio" id="status12" class="radio-item status1" data-status="0" name="status1" />\
                          <%}else{%>\
                            <input type="radio" id="status12" class="radio-item status1" data-status="0" name="status1" checked/>\
                          <%}%>\
                          <span class="radio-inner"></span>\
                         </span>\
                         <label class="radio-con" for="status12">否</label>\
                      </div>\
                    </div>\
                  </div>\
                  <div class="part_ part_state clearfloat">\
                    <div class="part_title float-left">身份证是否必填</div>\
                    <div class="part_content float-left">\
                      <div class="radio-wp">\
                         <span class="radio-input">\
                         <% if(res.isRequiredIdenNumber){ %>\
                            <input type="radio" id="status21" class="radio-item status2" data-status="1" name="status2" checked/>\
                          <%}else{%>\
                            <input type="radio" id="status21" class="radio-item status2" data-status="1" name="status2"/>\
                          <%}%>\
                          <span class="radio-inner"></span>\
                         </span>\
                         <label class="radio-con" for="status21">是</label>\
                      </div>\
                      <div class="radio-wp">\
                         <span class="radio-input">\
                         <% if(res.isRequiredIdenNumber){ %>\
                          <input type="radio" id="status22" class="radio-item status2" data-status="0" name="status2" />\
                        <%}else{%>\
                          <input type="radio" id="status22" class="radio-item status2" data-status="0" name="status2" checked/>\
                        <%}%>\
                          <span class="radio-inner"></span>\
                         </span>\
                         <label class="radio-con" for="status22">否</label>\
                      </div>\
                    </div>\
                  </div>\
                  <div class="part_ part_state clearfloat">\
                    <div class="part_title float-left">是否抓拍图片</div>\
                    <div class="part_content float-left">\
                      <div class="radio-wp">\
                         <span class="radio-input">\
                         <% if(res.isTakePhoto){ %>\
                          <input type="radio" id="status31" class="radio-item status3" data-status="1" name="status3" checked/>\
                        <%}else{%>\
                          <input type="radio" id="status31" class="radio-item status3" data-status="1" name="status3"/>\
                        <%}%>\
                        <span class="radio-inner"></span>\
                         </span>\
                         <label class="radio-con" for="status31">是</label>\
                      </div>\
                      <div class="radio-wp">\
                         <span class="radio-input">\
                         <% if(res.isTakePhoto){ %>\
                          <input type="radio" id="status32" class="radio-item status3" data-status="0" name="status3" />\
                        <%}else{%>\
                           <input type="radio" id="status32" class="radio-item status3" data-status="0" name="status3" checked/>\
                        <%}%>\
                          <span class="radio-inner"></span>\
                         </span>\
                         <label class="radio-con" for="status32">否</label>\
                      </div>\
                    </div>\
                  </div>\
                  <div class="part_ part_state clearfloat">\
                    <div class="part_title float-left">到访目的</div>\
                    <div class="part_content float-left">\
                      <div class="goal_wrap">\
                        <ul class="goal_ul">\
                        <%for(var i=0;i<visitReason.length;i++){%>\
                          <% if(i=="0"){ %>\
                            <li class="goal_li clearfloat"><input type="text" class="goal_input_" value="<%=visitReason[i]%>"/></li>\
                          <%}else{%>\
                            <li class="goal_li clearfloat"><input type="text" class="goal_input_" value="<%=visitReason[i]%>"/><span class="goal_delete">删除</span></li>\
                          <%}%>\
                        <%}%>\
                        </ul>\
                        <div class="add_div"><span class="add_li">继续添加</span></div>\
                      </div>\
                    </div>\
                  </div>',
        fkjModTpl: '<div class="mask">\
              <div class="pop_wrap">\
                <div class="pop_title">访客机设置-调试<span class="pop_close"></span></div>\
                <div class="pop_content">\
                  <div class="part_ part_state clearfloat">\
                    <div class="part_title float-left">是否新设备</div>\
                    <div class="part_content float-left">\
                      <div class="radio-wp">\
                         <span class="radio-input">\
                          <% if(res.isNewVersion){ %>\
                            <input type="radio" id="status51" class="radio-item status5" data-status="1" name="status5" checked/>\
                          <%}else{%>\
                            <input type="radio" id="status51" class="radio-item status5" data-status="1" name="status5"/>\
                          <%}%>\
                          <span class="radio-inner"></span>\
                         </span>\
                         <label class="radio-con" for="status51">是</label>\
                      </div>\
                      <div class="radio-wp">\
                         <span class="radio-input">\
                          <% if(res.isNewVersion){ %>\
                            <input type="radio" id="status52" class="radio-item status5" data-status="0" name="status5" />\
                          <%}else{%>\
                            <input type="radio" id="status52" class="radio-item status5" data-status="0" name="status5" checked/>\
                          <%}%>\
                          <span class="radio-inner"></span>\
                         </span>\
                         <label class="radio-con" for="status52">否</label>\
                      </div>\
                    </div>\
                  </div>\
                  <div class="addModeView"></div>\
                  <div class="part_ part_btn clearfloat">\
                    <span class="btn-red pop_sure_btn">确定</span>\
                  </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.addTpl));
        //关闭弹窗
        $(".close-btn").on("click", function() {
          $(".dialog-wp").remove();
        });
        $(".addPower").on("click", function() {
          $(".dialog-wp").remove();
          var groupType = $(this).data("type");
          var title = "员工";
          if (groupType == 1) {
            title = "员工";
          } else {
            title = "访客";
          }
          $("body").append(template.render(tpl.addPowerTpl)({
            orgList: orgList,
            title: title,
            groupType: groupType
          }));
          //可用时间段联动
          $("#isUseLimit").on("click",function(){
        	  if($(this).prop("checked")){
        		  $(".limit-time").show();
        	  }else{
        		  $(".limit-time").hide();
        	  }
          })
          //时间范围
          layui.use('laydate', function () {
				var laydate = layui.laydate;
				var end,start;
				 start= laydate.render({
		            elem: '#beginTime'
	            	,type: 'time'
	            	 ,format: 'HH:mm',
	            	 done: function(value,date){
	            		 end.config.min = _this._doneTime(date)
	            	 }
		          });
				 end = laydate.render({
		            elem: '#endTime'
	            	,type: 'time'
	            	 ,format: 'HH:mm',
	            	  done: function(value,date){
	            		  start.config.max = _this._doneTime(date)
	            	 }
		          });
			});

          if ($(".dialog-wp #orgId").attr('org__id')) {
            _this.getDeviceList($(".dialog-wp #orgId").attr('org__id'), 1);
          }
          $(".item-select").on("change", function() {
            setTimeout(function() {
              _this.getDeviceList($(".dialog-wp #orgId").attr('org__id'), 1);
            }, 200)
          })
          //关闭弹窗
          $(".close-btn").on("click", function() {
            $(".dialog-wp").remove();
          });
          //确认添加
          var list = [];
          $(".sure-add-btn").on("click", function() {
            $('.set-account-num input:checkbox:checked').each(function() {
              list.push($(this).val())
            })
            if (!$(".dialog-wp #orgId").attr('org__id')) {
              layer.msg("项目必选");
              return false;
            }
            if (!$(".dialog-wp .power-name").val()) {
              layer.msg("名称必填");
              return false;
            }
            if (list.length == 0) {
              layer.msg("通行设备必选");
              return false;
            };

            _this.ajaxAdd(function() {
              $(".dialog-wp").remove();
              _this.againRenderTable();
            }, list, groupType, 0, $(".dialog-wp #orgId").attr('org__id'));
          });
          // 访客机
        })
      });
      // 关闭公共弹层
      $('body').on('click', '.pop_close', function(event) {
        event.preventDefault();
        /* Act on the event */
        $('.mask').remove()
      });
      // 访客机
      $('.fkj_btn').on('click', function(event) {
        event.preventDefault();
        var orgId = $("#orgId").attr('org__id')
        if(!orgId){
          layer.msg('请选择项目')
          return
        }
        $.ajax({
          type: "post",
          url: $("#contextPath").val() + "/lingling/visitorMachineInfo",
          data: {
            orgId: orgId,
          },
          success: function(data) {
            res = data.data
            if(res){ //修改
              $("body").append(template.render(tpl.fkjModTpl)({
                res: res
              }));
              if (res.isNewVersion) {
                $(".addModeView").append(template.render(tpl.fkjNewModeTpl)({
                  res: res
                }));
              } else {
                $(".addModeView").append(template.render(tpl.fkjOldModeTpl)({
                  res: res,
                  visitReason: res.visitReasonStr.split(';')
                }));
              }
              fkj_orgId = res.orgId
              fkj_machineId = res.machineId
            }else{ //新增
              res = {
                deviceCode: '',
                isNewVersion: 1,
                isRequiredIdenNumber: 0,
                isTakePhoto: 0,
                isUploadIdenphoto: 0,
                machineId: '',
                machineJson: '',
                orgId: orgId,
                visitReasonStr: ''
              }
              $("body").append(template.render(tpl.fkjModTpl)({
                res: res
              }));
              $(".addModeView").append(template.render(tpl.fkjNewModeTpl)({
                res: res
              }));
            }
          },
          error: function(error) {
            layer.msg('error')
          }
        });
      });
      $("body").bind('input', '.status5',function(event){
        event.preventDefault();
        var isNewVersion = $(".radio-item.status5:checked").data("status")
        if (res.isNewVersion != isNewVersion) {
          res.isNewVersion = isNewVersion
          if (res.isNewVersion) {
            $(".addModeView").replaceWith("<div class=\"addModeView\">"+template.render(tpl.fkjNewModeTpl)({
              res: res
            })+"</div>");
          } else {
            $(".addModeView").replaceWith("<div class=\"addModeView\">"+template.render(tpl.fkjOldModeTpl)({
              res: res,
              visitReason: res.visitReasonStr.split(';')
            })+"</div>");
          }
        }
      });
      // 访客机添加到访目的
      $('body').on('click', '.add_li', function(event) {
        event.preventDefault();
        /* Act on the event */
         $('.goal_ul').append('<li class="goal_li clearfloat"><input type="text" class="goal_input_" /><span class="goal_delete">删除</span></li>')
      });
      // 访客机删除到访目的
      $('body').on('click', '.goal_delete', function(event) {
        event.preventDefault();
        /* Act on the event */
        $(this).parent().remove()
      });
      // 访客机设置确定
      $('body').on('click', '.pop_sure_btn', function(event) {
        event.preventDefault();
        /* Act on the event */
        var formdata = res;
        formdata['isNewVersion'] = $(".radio-item.status5:checked").data("status")
        if (formdata['isNewVersion']) {
          formdata['deviceCode'] = $(".SN-input").val()
          formdata['machineJson'] = $(".JSON-input").val()

          if (formdata['deviceCode'] == null||formdata['deviceCode'] == ''||formdata['deviceCode'] == undefined) {
            layer.msg('请填写访客机SN')
            return
          }
          if (formdata['machineJson'] == null||formdata['machineJson'] == ''||formdata['machineJson'] == undefined) {
            layer.msg('请填写访客机JSON')
            return
          }
        } else {
          formdata['deviceCode'] = String(formdata['deviceCode'])
          formdata['machineJson'] = String(formdata['machineJson'])

          formdata['isUploadIdenphoto'] = $(".radio-item.status1:checked").data("status")
          formdata['isRequiredIdenNumber'] = $(".radio-item.status2:checked").data("status")
          formdata['isTakePhoto'] = $(".radio-item.status3:checked").data("status")

          var strVisitReason = ''
          var dom_input = $('.goal_input_')
          var flag = false //看是否全部为空字符
          $.each(dom_input,function(idnex,item){
            var val = $(item).val()
            if(val){
              flag = true
              if(strVisitReason == '') {
                strVisitReason = val
              } else {
                strVisitReason = strVisitReason + ';' + val
              }
            }
          })
          if(!flag){
            layer.msg('请填写到访目的')
            return
          } else {
            formdata['visitReasonStr'] = strVisitReason
          }
        }

        console.log('formdata == ', formdata)

        $.ajax({
          type: "post",
          url: $("#contextPath").val() + "/lingling/addUpdateVisitorMachine",
          data: formdata,
          success: function(data) {
            if(data.code == 200){
              layer.msg('设置成功')
              $('.mask').remove()
            }else {
              layer.msg(data.msg)
            }
          },
          error: function(error) {
            layer.msg('error')
          }
        });
      });
      // 模糊搜索
      _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/getDeviceGroupList",
          method: "post",
          where: {
            orgId: $("#orgId").attr('org__id')
          },
          skin: 'nob' //行边框风格
            ,
          even: true //开启隔行背景
            ,
          size: 'lg' //小尺寸的表格
            ,
          cols: [
            [{
              field: 'index',
              title: 'ID',
              minWidth: '30',
              templet: '#indexTpl'
            }, {
              field: 'groupName',
              title: '权限名称',
              minWidth: 200
            }, {
              field: 'deviceNames',
              title: '通行设备',
              minWidth: 200
            }, {
              field: 'createTime',
              title: '添加时间',
              minWidth: 200
            }, {
              field: 'remark',
              title: '备注',
              minWidth: 200
            }, {
              title: '操作',
              fixed: 'right',
              minWidth: 200,
              align: 'center',
              templet: function(data) {
                var str = '';
                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-edit-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-delete-btn").on("click", function() {
              var id = $(this).data("id");
              _this.ajaxDelTemp(id, function() {
                _this.againRenderTable();
              })
            });
            //修改
            $(".t-edit-btn").on("click", function() {
              var id = $(this).data("id");
              _this.ajaxDetail(id, function(dict) {
                var detail = dict;
                _this.getDeviceList(detail.orgId, 2, id, function(data) {
                  let listArr = [];
                  var list = [];
                  data.forEach(itme => {
                    if(itme.isChecked) {
                      listArr.push(itme.id.toString())
                    }
                  })
                  $("body").append(template.render(tpl.editPowerTpl)({
                    data: data,
                    orgList: orgList,
                    detail: detail
                  }));
                  //可用时间段联动
                  if(detail.isUseLimit==1){
                	  $(".limit-time").show();
                  }
                  $("#isUseLimit").on("click",function(){
                	  if($(this).prop("checked")){
                		  $(".limit-time").show();
                	  }else{
                		  $(".limit-time").hide();
                	  }
                  })
                //时间范围
                  var start,end;
                  layui.use('laydate', function () {
        				var laydate = layui.laydate;
        				var end,start;
        				 start= laydate.render({
        		            elem: '#beginTime'
        	            	,type: 'time'
        	            	 ,format: 'HH:mm',

        	            	 done: function(value,date){
        	            		 end.config.min = _this._doneTime(date)
        	            	 }


        		          });
        				 end = laydate.render({
        		            elem: '#endTime'
        	            	,type: 'time'
        	            	 ,format: 'HH:mm',
        	            	  done: function(value,date){
        	            		  start.config.max = _this._doneTime(date)
        	            	 }
        		          });
        			});
                  //关闭弹窗
                  $(".close-btn").on("click", function() {
                    $(".dialog-wp").remove();
                  });
                  //确认添加
                  $(".sure-add-btn").on("click", function() {
                    $('.set-account-num input:checkbox:checked').each(function() {
                      list.push($(this).val())
                    })
                    var isChange = 0;
                    if (list.length == 0) {
                      layer.msg("通行设备必选");
                      return false;
                    } else {
                      if (list.length == listArr.length) {
                        isChange = 1;
                        listArr.forEach(itme => {
                          isChange = _this.backIsChange(list, itme)
                        })
                      }
                      else {
                        isChange = 1;
                      }
                    }
                    _this.ajaxAdd(function() {
                      $(".dialog-wp").remove();
                      _this.againRenderTable();
                    }, list, detail.groupType, isChange, detail.orgId, id);
                  });
                })
              });
            });
            //详情
            $(".t-detail-btn").on("click", function() {
              var id = $(this).data("id");
              _this.ajaxDetail(id, function(data) {
                $("body").append(template.render(tpl.detailTpl)(data));
                //关闭弹窗
                $(".close-btn").on("click", function() {
                  $(".dialog-wp").remove();
                });
              })
            });
          }
        });
        //查询
        $('#conditionform  .search-btn').on('click', function() {
          _this.againRenderTable();
        });
      });
    },
    /**
     * 数组中是否存在指定元素
     * @param data 数组数据
     * @param id 元素
     */
    backIsChange: function(data,id) {
      var indexRow = 1;
      data.every(itme => {
        if(itme == id) {
          indexRow = 0
          return false
        } else {
          return true
        }
      })
      return indexRow
    },
    /**
     * 删除
     * @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() + "/lingling/delDeviceGroup",
          data: {
            id: id
          },
          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: {
          groupName: $("#conditionform .groupName").val(),
          groupType: $("#conditionform .groupType").val(),
          deviceId: $("#conditionform .deviceId").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')
        }
      });
    },
    //获取设备列表
    getDeviceList: function(orgId, type, groupId, callback) {
      $.ajax({
        type: "post",
        url: contextPath + "/lingling/getDeviceTree",
        data: {
          groupId: groupId,
          orgId: orgId
        },
        dataType: "json",
        success: function(data) {
          if (data.code == ERROK) {
            if (type == 1) {
              var list = data.data;
              var str = "";
              $(".dialog-wp .set-account-num").html("");
              $.each(list, function(index, item) {
                if (item.isChecked) {
                  str += "<label><input type='checkbox' name='account' value='" + item.id + "' checked='checked'><span>" + item.deviceName + "</span></label>"
                } else {
                  str += "<label><input type='checkbox' name='account' value='" + item.id + "'><span>" + item.deviceName + "</span></label>"
                }
              })
              $(".dialog-wp .set-account-num").append(str);
            } else {
              callback(data.data)
            }

          } else {
            layer.msg(data.msg)
          }
        },
        error: function(error) {
          layer.msg('error')
        }
      });
    },
    /**
     * 请求详情
     * @param id
     * @param callback
     */
    ajaxDetail: function(id, callback) {
      var _this = this;
      $.ajax({
        type: "post",
        url: contextPath + "/lingling/getDeviceGroupInfo",
        data: {
          id: id
        },
        success: function(data) {
          if (data.code == ERROK) {
            callback(data.data)
          } else {
            layer.msg(data.msg)
          }
        },
        error: function(error) {
          layer.msg('error')
        }
      });
    },
    /**
     * 新增权限列表
     * @param data
     * @param callbck
     */
    ajaxAdd: function(callback, list, type, isChange, orgId, id) {
      var _this = this;
      var deviceIds = "";
      deviceIds = list.join(";");
      var result = {
			  groupName: $(".power-name").val(),
	          groupType: type,
              isChange: isChange,
	          remark: $(".device-remark").val(),
	          deviceIds: deviceIds,
	          orgId: orgId,
	          id: id
      	}
      if(type!=1){
      	//可用日期
      	//工作日
      	var isWorkday = $("#isWorkday").prop("checked") ? 1: 0;
      	//休息日
      	var isWeek = $("#isWeek").prop("checked") ? 1: 0;
      	//节假日
      	var isHoliday = $("#isHoliday").prop("checked") ? 1: 0;
      	if(!isWorkday && !isWeek && !isHoliday){
      		layer.msg("请选择可用日期");
              return false;
      	};
      	result["isWorkday"] = isWorkday;
      	result["isWeek"] = isWeek;
      	result["isHoliday"] = isHoliday;
      	//可用时间段限制
      	var isUseLimit = $("#isUseLimit").prop("checked") ? 1: 0;
      	result["isUseLimit"] = isUseLimit;

      	if(isUseLimit){
      		var beginTime = $("#beginTime").val();
      		var endTime = $("#endTime").val();
      		if(!(endTime && beginTime)){
      			layer.msg("请设置可用时段");
                  return false;
      		};
      		result["beginTime"] = beginTime;
          	result["endTime"] = endTime;
      	}
      };

      $.ajax({
        type: "post",
        url: $("#contextPath").val() + "/lingling/addUpdateDeviceGroup",
        data: result,
        dataType: "json",
        success: function(data) {
          if (data.code == 200) {
            callback();
          } else {
            layer.msg(data.msg)
          }
        },
        error: function() {
          // layer.msg('系统繁忙.....')
        }
      });
    },
    /**
     * 更新设备
     * @param data
     * @param callbck
     */
    addDevice: function(callback, deviceId) {
      $.ajax({
        type: "post",
        url: $("#contextPath").val() + "/lingling/updateLocalDevice",
        data: {
          deviceType: $(".dialog-wp .device-type").val(),
          address: $(".dialog-wp .device-address").val(),
          remark: $(".device-remark").val(),
          deviceId: deviceId,
          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('系统繁忙.....')
        }
      });
    },
    _doneTime: function(date){
    	return {
			  hours: date.hours,
			  minutes: date.minutes,
			  seconds: date.seconds,
			  year: date.year,
	          month: date.month - 1,
	          date: date.date
	 		};
    }
  };
  api.init();
})
