/**
 * 企业信息资料管理
 * 
 */
var layer;
var table;
	layui.use('layer', function(){
		   layer = layui.layer;  
	});  
var ERROR_OK = 200;
var contextPath = $("#contextPath").val();
var updateAct = $("#updateAct").val();
var deleteAct = $("#deleteAct").val();
var funcid = $("#funcid").val();

var permDelete = $("#perm-delete").val();//删除权限
var permEdit = $("#perm-edit").val();//编辑权限
var virAccountInfo = $("#virAccountInfo").val()

var tpl ={
    "exportTpl": '<div class="dialog-wp">\
				<div class="mask"></div>\
				<div class="dialog dialog-export-con">\
					<div class="title-wp">\
						<span>导入</span>\
						<span class="close-btn"></span>\
					</div>\
					<div class="dialog-export-wp">\
						<div class="choose-floor-wp">\
							<span class="tip">楼宇：</span>\
							<select class="default-select" id="buildId">\
								<option value="">选择楼宇</option>\
								<% for(var i=0;i<data.length;i++){%>\
									<option value="<%=data[i].id%>"><%=data[i].name%></option>\
								<%}%>\
							</select>\
						</div>\
						<div class="export-file-wrapper">\
							<input type="file" id="excelFile" name="excelFile" />\
							<button class="btn-big-red export-sure-btn">导入</button>\
						</div>\
					</div>	\
				</div>\
			</div>'
};
$(function(){
	
	var elementgroupList = {
			init: function(){
				this.render();
				this.bindEvent();
				
			},
			render: function(){
				this.rendertable();
				
			},
			bindEvent: function(){
				var _this = this;
				
				//重置
				$(".set-btn").on("click",function(){
          if(virAccountInfo){
            var $dom = $("#conditionform .keyWord,#conditionform #date1,#conditionform #date2")
            $dom.val("")
            _this.againRenderTable({type:1});
          }else{
					 var $orgId = $("#conditionform  .single-orgid");
					 var $dom = $("#conditionform input,#conditionform select")
					 if($orgId.length){
						 $dom.val("").removeAttr('com__id dep__id')
					 }else{
						 $dom.val("").removeAttr('org__id com__id dep__id')
					 }
           _this.againRenderTable({type:1});
          }
         });
       
				//新增
				$(".add-ele-btn").on("click",function(){
					addVirtualArchitecture('', 0)
//					window.location.href= contextPath + '/admin/users/jumpUserInfo?funcid='+funcid;
				});
//				$("#btn-search").click(function(){
//					$("#conditionform").submit();
//				});
				
				//下载模板
				$(".download-btn").on("click",function(){
					location.href=$("#contextPath").val()+"/upload/VirtualArch.xlsx";
				});
				
				//导入 buildList等于1
				$("#excelFile").on("change",function(){
					exportFile();
				});
				
				// //导入 buildList大于1
				$(".export-btn-enter").on("click",function(){
					//显示弹窗
					showExportDialog()
					//
				});
				// 模糊搜索
				_this.search_fuzzy()
			},
			// 模糊搜索事件
			search_fuzzy: function(){
				var default_option = {
					org_attrName:'org__id',
					com_attrName:'com__id',
					dep_attrName:'dep__id',
					org_spanName:'org__span',
					com_spanName:'com__span',
					dep_spanName:'dep__span',
					org_path:'/admin/templ/getOrgListByName',
					com_path:'/admin/templ/getVirList',
					dep_path:'/admin/templ/getDept',
					contextPath:$("#contextPath").val()
				}
				var option_1 = $.extend(true,{},default_option,{
					org_target:'.default-select#organizationId',
					com_target:'.default-select#virtualId'
				});

				function eve(option_,otherOption){
					var obj = $.extend(true, {}, option_, otherOption);
					var type = obj.type
					var _path, _target, _attrName, _spanName
					if(type == 1){
						_path = obj.org_path
						_target = obj.org_target
						_attrName = obj.org_attrName
						_spanName = obj.org_spanName
					}else if(type == 2){
						_path = obj.com_path
						_target = obj.com_target
						_attrName = obj.com_attrName
						_spanName = obj.com_spanName
					}else if(type == 3){
						_path = obj.dep_path
						_target = obj.dep_target
						_attrName = obj.dep_attrName
						_spanName = obj.dep_spanName
					}
					$('body').on("input",_target,function(event){
						var _this = $(this)
						var obj_input = $.extend(true,{}, obj,{"_this":_this});
						cjqt.search_fuzzy.event_input(_this,_attrName,_spanName,contextPath,_path,obj_input)
					});
					$('body').on("focus",_target,function(event){
						var _this = $(this)
						var obj_focus = $.extend(true,{},obj,{"_this":_this});
						cjqt.search_fuzzy.event_focus(_this,_attrName,_spanName,contextPath,_path,obj_focus)
					});
					$('body').on('blur',_target,function(event) {
						var _this = $(this)
						var obj_blur = $.extend(true,{},obj,{"_this":_this});
						cjqt.search_fuzzy.event_blur(_this,_attrName,obj_blur)
					});
					$('body').on('click',_target+'~.select_wrap>.'+_spanName, function(event) {
						event.preventDefault();
						event.stopPropagation();
						/* Act on the event */
						var _this = $(this)
						var obj_click = $.extend(true,{},obj,{"_this":_this});
						cjqt.search_fuzzy.event_click(_this,_attrName,_target,obj_click)
					});

				}
				// 搜索联动
				eve(option_1,{type:1})
				eve(option_1,{type:2})
			},
			
			rendertable: function(){
				var _this = this;
				layui.use(['table','laydate'], function(){
					  table = layui.table;
						var layer = layui.layer,
						laydate = layui.laydate;
						//日期
						laydate.render({
							elem: '#date1'
						});
						laydate.render({
							elem: '#date2'
						});
					  //方法级渲染
					  table.render({
					    elem: '#LAY_table_user'
					    ,url: contextPath + "/admin/virtualArch/virList"
					    ,skin: 'nob' //行边框风格
				    		  ,even: true //开启隔行背景
				    		  ,size: 'lg' //小尺寸的表格
					    ,cols: [[    
			             {
				    		   title: '序号',
				    		   templet: '#indexTpl',
//				    		   width: '80'
				    	  },{
				    		  field:'name',
				    		  title: '企业名称',
//				    		  minWidth: '200',
			    		  },{
				    		  field:'contExpireTime',
				    		  title: '合同到期时间',
//				    		  minWidth: '200',
			    		  },{
							  field:'agent_name',
							  title: '代理企业',
//				    		  minWidth: '200',
						  },{
							  field:'agent_name',
							  title: '级别',
//				    		  minWidth: '200',
							  templet: function(data){
								  var str = '';
								  if(data.level==1){
									  return '普通'
								  }else if(data.level==2){
									  return '代理'
								  }
								  return str;
							  }
						  },{
			    			  field:'codeNumber', 
			    			  title: '企业编码', 
//			    			  minWidth: '200',
		    			  },{
			    			  field:'phone', 
			    			  title: '联系电话', 
//			    			  minWidth: '200',
		    			  },{
			    			  field:'buildName', 
			    			  title: '楼宇', 
//			    			  minWidth: '280',
		    			  },{
			    			  field:'floorNames', 
			    			  title: '楼层', 
//			    			  minWidth: '200',
		    			  },{
			    			  field:'roomNames', 
			    			  title: '房间号', 
//			    			  minWidth: '200',
		    			  },{
			    			  field:'leaseStatus', 
			    			  title: '企业状态', 
//			    			  minWidth: '200',
			    			  templet: function(data){
	    						  var str = '';
	    						  if(data.leaseStatus==1){
	    							  return '在租'
	    						  }else if(data.leaseStatus==0){
	    							  return '已迁出'
	    						  }else if(data.leaseStatus==5){
	    							  return '合同即将到期'
	    						  }else if(data.leaseStatus==6){
	    							  return '合同已到期'
	    						  }
	    						  return str;
	    					  }
		    			  },{
			    			  field:'address', 
			    			  title: '地址', 
//			    			  minWidth: '200',
		    			  },{
	    					 
	    					  title: '操作', 
	    					  minWidth: '180',
	    					  fixed: 'right', 
	    					  templet: function(data){
	    						  var str = '';
	    						  if(permEdit == 1){
	    							  str += '<button class="t-btn t-red-btn t-edit-btn" data-id="'+data.id + '" data-level="'+data.level + '" >修改</button>';
	    						  }
	    						  if(permDelete == 1){
	    							  str += '<button class="t-btn t-white-btn t-del-btn" data-id="'+data.id+'" >删除</button>';
	    						  }
	    						  return str;
	    					  }
	  					  }
						  ]]
						    ,id: 'testReload'
						    ,page: true,
						    method: 'post',
						    request: {
						        pageName: 'pageNo' //页码的参数名称，默认：page
						        ,limitName: 'pageSize' //每页数据量的参数名，默认：limit
                  },
                  where: {
                    virtualId: $("#conditionform #virtualId").attr('com__id')
                  },
						    response: {
						    	  statusName: 'code' //数据状态的字段名称，默认：code
						    	  ,statusCode: 200 //成功的状态码，默认：0
						    	  ,countName: "count"//数据总数的字段名称，默认：count
						    	  ,dataName: "data" //数据列表的字段名称，默认：data
						    	}   ,
						    done: function(res, curr, count){
//						        //如果是异步请求数据方式，res即为你接口返回的信息。
						    	//删除
						    	$(".t-del-btn").on("click",function(){
						    		var id = $(this).data("id");
						    		_this.delEles(id)
						    		
						    	});
						    	//修改
						    	$(".t-edit-btn").on("click",function(){
						    		var id = $(this).data("id");
						    		var funcid = $("#funcid").val();
						    		addVirtualArchitecture(id, $(this).data("level"));
//						    		window.location.href= contextPath + '/admin/users/jumpUserInfo?userid='+id+'&funcid='+funcid;
						    	})
						    }	
					  });
					  //查询
					  $('#conditionform  .search-btn').on('click', function(){
						  	_this.againRenderTable();
					  });
					});
			},
			/*重新渲染table*/
			againRenderTable: function(option){
				var obj = $.extend(true, {}, option);
				var type =  obj.type || ''
				var $orgId = $(".single-orgid");
				var orgId = $("#organizationId").attr('org__id')
				if(type == 1){
          if(virAccountInfo){
            table.reload('testReload', {
              where: {
                virtualId: $("#conditionform #virtualId").attr('com__id'),
							  keyWord: '',
							  orgId: $orgId.length?orgId:'',
							  beginTime: '',
							  endTime: '',
				              agentName:$("#agentName").val()
              },
              page: {
                curr: 1 //重新从第 1 页开始
              }
            });
          }else{
					table.reload('testReload', {
						where: {
							virtualId: '',
							keyWord: '',
							orgId: $orgId.length?orgId:'',
							beginTime: '',
							endTime: '',
							agentName:$("#agentName").val()
						} ,
						  page: {
						    curr: 1 //重新从第 1 页开始
						  }
          }); 
        }
				}else{
					table.reload('testReload', {
						where: {
							virtualId: $("#virtualId").attr('com__id'),
							keyWord: $(".keyWord").val(),
							orgId: orgId,
							beginTime: $("#date1").val(),
							endTime: $("#date2").val(),
							agentName:$("#agentName").val()
						} ,
						  page: {
						    curr: 1 //重新从第 1 页开始
						  }
					}); 
				}
			},
			/**
			 * 删除
			 * @param id 元素id
			 */
			delEles: function(id){
				var _this = this;
				layer.confirm('确定删除?', {
				  btn: ['确定', '取消'] 
				}, function(index, layero){
					 layer.close(index); //如果设定了yes回调，需进行手工关闭
//					 "delete/"+id+"&"+$("#funcid").val();
					 window.location.href= contextPath + "/admin/virtualArch/delete/"+id+"&"+funcid;
				}, function(index){
					
				});	
			}
	
	};
	elementgroupList.init();
	
});
//显示导入弹窗
 function showExportDialog(){
 	//获取楼宇
     $.ajax({
         url :$("#contextPath").val()+"/admin/floor/getBuildByOrg",
         type : "POST",
		 data: {
             orgId: $("#organizationId").attr('org__id')
		 },
         success : function(data) {
            if(data.code==200){
                $("body").append(template.render(tpl.exportTpl)(data));
                //关闭弹窗
                $(".dialog-export-con .close-btn").on("click",function(){
                	$(this).closest(".dialog-wp").remove()
				});
                //导入
                $("#excelFile").on("change",function(){
                    exportFile();
                });
			}else{
            	alert(data.msg)
			}
         },
         error : function(data) {
         }
     });

 }
//导入企业
function exportFile(){
	var _this = this;
	var fileName=$("#excelFile").val();
	var buildId=$("#buildId").val();
	if(!buildId){
        layer.alert("请选择楼宇!");
        return;
	}
	var extension=fileName.substring(fileName.lastIndexOf(".")+1,fileName.length);
	if(extension=="xlsx"){
		if(fileName == null || fileName == ""){
			layer.alert("数据导入为空,请按照模板填写资料后再导入!");
			return;
		}
		//2018-08-28  lmz  首先判断该校区下楼宇有多少个，如果是单个的，就传单个的id,如果是多个，就弹窗让用户选择楼宇，选完了之后再弹出让其选择导入的文件
		 $.ajaxFileUpload
         (
             {
                 url: $("#contextPath").val()+ "/admin/virtual/importVirtualInfo?buildId="+buildId, //用于文件上传的服务器端请求地址
                 secureuri: false, //是否需要安全协议，一般设置为false
                 fileElementId: 'excelFile', //文件上传域的ID
                 dataType: 'json', //返回值类型 一般设置为json
//                 data:{
//                	 buildId:buildId
//                 },
                 success: function (data) //服务器成功响应处理函数
                 {
                	 var data=data;
                	$("#excelFile").on("change",function(){
         				_this.exportFile();
         			});
                     if (data.code == '200') {
                    	 $("#conditionform").submit();
                     } else {
                    	 layer.alert(data.msg);
                     }
                 }
             }
         )		
	}
	else{
		alert("请上传xlsx格式的文件");
	}
}
	
//翻页
function goPage(pageNo){
	if(pageNo=="gopage"){
		$("#pageNo").val($("#gopage").val());
	}else{
		$("#pageNo").val(pageNo);
	}
		$("#conditionform").submit();
}


function addVirtualArchitecture(virtualId, level){
	var url="",
		vir = $("#virtualId"),
		virId = vir.attr("com__id");
	if(virtualId!=""&&virtualId!=null){
		url=contextPath+"/admin/virtualArch/virtualArchForm?virtualId="+virtualId;
	}
	else{
		url=contextPath+"/admin/virtualArch/virtualArchForm";

		if(virId && vir.attr("level") == 2) { //isAdmin=false level=2的用户在添加时，默认添加的为level=1的记录，且代理企业为当前用户企业
			url += "?virId=" + virId + "&virName=" + encodeURI(vir.val());
		}
	}

	//非管理员界面使用。编辑普通或新增
	if(virId && (level == 1 || level == 0)) {
		var rangeId = vir.attr("range_id");
		url += (url.indexOf("?") != -1 ? "&" : "?") + "rangeId=" + rangeId;
	}
	var iHeight=600;
	var iWidth=600;
    var iTop = (window.screen.availHeight-30-iHeight)/2;
	var iLeft = (window.screen.availWidth-10-iWidth)/2;
	var params='width='+iWidth+',height='+iHeight+',top='+iTop+',left='+iLeft+',channelmode=no'+',directories=yes'
		 +',location=no'+',menubar=no'+',resizable=no'+',scrollbars=yes'+',status=yes'+',titlebar=yes'+',toolbar=no';
	var winObj= window.open(url,"",params); 
	var loop = setInterval(function() {     
	    if(winObj!=null&&winObj.closed) {
	        clearInterval(loop);    
	        $("#conditionform").submit();
	    }    
	}, 1000);
}

function dele(id){
	if(confirm("确定删除？")){
		window.location.href="delete/"+id+"&"+$("#funcid").val();
	}	
}
