
var permEdit = $("#perm-edit").val();//编辑权限
/*
 * 企业管理
 */
$(function() {
	var tpl = {
		"setPermissionsTpl": '<div class="dialog-wp set-permession">\
		<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><span class="red">*</span>类型名称：</label>\
							<select id ="groupId" class="item-select group-id" >\
								<option value="">请选择类型名称</option>\
								<%for(var i=0;i<names.length;i++){%>\
									<option value="<%=names[i].permId%>" data-company="<%=names[i].virList%>"><%=names[i].permName%></option>\
								<%}%>\
							</select>\
						</li>\
						<li class="li1 hadPeople" style="display:none">\
							<label class="mt15">已有企业：</label>\
							<div class="set-account-num">\
							</div>\
						</li>\
						<li class="li1">\
							<label class="mt15"><span class="red">*</span>设置账号：</label>\
							<div class="set-account-num">\
							<%for(var i=0;i<personList.length;i++){%>\
								<label><input type="checkbox" name="account" value="<%=personList[i].id%>" checked="checked"><span><%=personList[i].virName%></span></label>\
							<%}%>\
							</div>\
							<div style="padding-left:88px">共计：<span class="txt_blue total"><%=personLen%>家</span></div>\
						</li>\
					 </ul>\
					 <div class="dialog-btns" style="border: 0">\
						 <button class="sure-add-btn btn-red" style="margin-top: 25px">确认</button>\
						</div>\
			</div>\
		</div>\
	</div>',
			"itemList": '<option value="">选择校区</option><% for(var i=0;i<list.length;i++){%>\
				<option value="<%=list[i].id%>"><%=list[i].name%></option>\
			<%}%>'	,
			"editTpl": '<div class="dialog-wp">\
				<div class="mask"></div>\
				<div class="dialog dialog-edit-con">\
					<div class="title-wp">\
						<span>编辑企业账号</span>\
						<span class="close-btn"></button>\
					</div>\
					<div class="dialog-edit-wp">\
						<div class="edit-wp-top" style="height:400px>\
							<div class="edit-item">\
								<span class="tips">公司名</span>\
								<input type="text" class="edit-item-input virname-input" placeholder="请输入公司名" value="<%=virname%>" readonly />\
							</div>\
							<div class="edit-item">\
								<span class="tips">账号名称</span>\
								<input type="text" class="edit-item-input account-input" placeholder="请输入账号名称" value="<%=account%>"/>\
								<input type="text" class="hidden" style="display: none">\
							</div>\
							<div class="edit-item">\
								<span class="tips">密码</span>\
								<input type="password" class="hidden" style="display: none">\
								<input type="text" class="edit-item-input password-input" placeholder="请输入密码" value="<%=password%>"/>\
							</div>\
						</div>\
						<div class="edit-wp-btm">\
							<button class="cancel-add-btn btn-white">取消</button>\
							<button class="sure-add-btn btn-red" data-id="<%=id%>">确定</button>\
						</div>\
					</div>   	\
				</div>\
			</div>	',
			"editOtherTpl": '<div class="dialog-wp">\
				<div class="mask"></div>\
				<div class="dialog dialog-edit-con dialog-other-edit-con">\
					<div class="title-wp">\
						<span>编辑其他</span>\
						<span class="close-btn"></button>\
					</div>\
					<div class="dialog-edit-wp">\
						<div class="edit-wp-top">\
							<div class="edit-item">\
								<span class="tips">公司名</span>\
								<input type="text" class="edit-item-input virname-input" placeholder="请输入公司名" value="<%=otherInfo.virname%>" readonly/>\
							</div>\
							<div class="edit-item">\
								<span class="tips">企业结算方式</span>\
								<div class="edit-item-wp">\
									<div class="radio-wp" >\
										<span class="radio-input">\
											<input type="radio" id="indate" data-type="2" class="radio-item" name="type" <%if(otherInfo.settleType==2){%> checked <%}%>/>\
											<span class="radio-inner"></span>\
										</span>		\
										<label class="radio-con" for="indate">月结</label>\
									</div>\
									<div class="radio-wp" >\
										<span class="radio-input">\
											<input type="radio" id="outdate" data-type="1" class="radio-item" name="type" <%if(otherInfo.settleType==1){%> checked <%}%>/>\
											<span class="radio-inner"></span>\
										</span>		\
										<label class="radio-con" for="outdate">现结</label>\
									</div>\
								</div>\
							</div>\
							<div class="edit-item">\
								<span class="tips">月度免费时长</span>\
								<div class="edit-item-wp">\
									<input type="number" class="time-input free-input" value="<%=otherInfo.freeLenTime%>"/>\
								</div>\
							</div>\
							<div class="edit-item">\
								<span class="tips">剩余免费时长</span>\
								<div class="edit-item-wp">\
									<input type="number" class="time-input remain-input" value="<%=otherInfo.remainderTime%>"/>\
								</div>\
							</div>\
							<div class="edit-item account-item required clearfloat">\
								<div class="item-tip tips">企业类型</div>\
								<div class="item-con edit-item-wp">\
									<select class="item-select" id="permType">\
									<option value="">请选择企业类型</option>\
									<%if(funcListStr){%>\
										<%for(var i=0;i<funcListStr.length;i++){%>\
											<option value="<%=funcListStr[i].id%>" <%if(funcListStr[i].id == otherInfo.permId){%> selected <%}%> data-func="<%=funcListStr[i].funcList%>"><%=funcListStr[i].permName%></option>\
										<%}%>\
									<%}%>\
									</select>\
									<div class="funcList" style="display:block">功能权限：<%=otherInfo.funcList %></div>\
								</div>\
							</div>\
						</div>\
						<div class="edit-wp-btm">\
							<button class="cancel-add-btn btn-white">取消</button>\
							<button class="sure-add-btn btn-red" data-id="<%=otherInfo.id%>">确定</button>\
						</div>\
					</div>\
				</div>\
			</div>	',
			"detailTpl": '<div class="dialog-wp">\
			<div class="mask"></div>\
			<div class="dialog dialog-edit-con dialog-other-edit-con">\
				<div class="title-wp">\
					<span>详情</span>\
					<span class="close-btn"></button>\
				</div>\
				<div class="dialog-edit-wp">\
					<div class="edit-wp-top">\
						<div class="edit-item">\
							<span class="tips">校区：</span>\
							<span><%=otherInfo.orgName%></span>\
						</div>\
						<div class="edit-item">\
							<span class="tips">公司名称：</span>\
							<span><%=otherInfo.virName%></span>\
						</div>\
						<div class="edit-item">\
							<span class="tips">企业账号：</span>\
							<span><%=otherInfo.virAccount%></span>\
						</div>\
						<div class="edit-item">\
							<span class="tips">企业结算方式：</span>\
							<span><%if(otherInfo.settleType==2){%> 月结 <%}%></span>\
							<span><%if(otherInfo.settleType==1){%> 现结 <%}%></span>\
						</div>\
						<div class="edit-item">\
							<span class="tips">月度免费时长：</span>\
							<div class="edit-item-wp">\
								<span><%=otherInfo.freeLenTime%></span>\
							</div>\
						</div>\
						<div class="edit-item">\
							<span class="tips">剩余免费时长：</span>\
							<div class="edit-item-wp">\
								<span><%=otherInfo.remainderTime%></span>\
							</div>\
						</div>\
						<div class="edit-item account-item required clearfloat">\
							<div class="item-tip tips">企业类型：</div>\
							<div class="item-con edit-item-wp">\
								<span><%=otherInfo.virPermName%></span>\
								<%if(otherInfo.funcList){%>\
								<div class="funcList" style="display:block">功能权限：<%=otherInfo.funcList %></div>\
								<%}%>\
							</div>\
						</div>\
					</div>\
					<div class="edit-wp-btm">\
						<button class="sure-add-btn btn-red">确定</button>\
					</div>\
				</div>\
			</div>\
		</div>'
	   };
	var layer;
	var table;
	var ERROR_OK = 200;
	var table_data = [];
	var idsArr = [];
	var virList = [];
	layui.use('layer', function(){
		   layer = layui.layer;  
	}); 
	var enterprise = {
		init: function(){
			this.render();
			this.bindEvent();
		},
		render: function(){
			var _this = this;
			
			//渲染校区
			_this.renderItem();
			//渲染table
			-this.renderTable();
			
		},
		bindEvent: function(){
			var _this = this;
			var $checkBtn = $(".check-btn");
			var $editBtn = $(".edit-btn");
			var $addEnterpriseBtn = $(".add-enterprise-btn");
			//查询
			$("#conditionform input[type='text']").on("keydown",function(event){
				if(event.keyCode == 13){
					$("#conditionform .search-btn").click();
				}
			});
			
			//重置
			$(".reset-btn").on("click",function(){
				$("#conditionform").find("select").val("");
				$("#conditionform").find("input").val("");
				//$(".item-select").attr('org__id','')
				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()
//				$("#conditionform .room-select").html($("<option value=''>选择房间号</option>"))
			})
			 // 设置企业类型
			 $("#setPermissions").on("click", function () {
				virList = []
        // var checkStatus = table.checkStatus('testReload');
        var checkStatus = idsArr;
        // if (checkStatus.length == 0) {
        // 	layer.msg("请先选择设置权限人员");
        // 	return false
        // };
				var orgId = $("#conditionform  #orgId").attr('org__id');
				if(!orgId) {
					layer.msg("请先选择校区")
					return false
				}
				var list = checkStatus;
				console.log(list)
        _this.permissionListAjax(orgId, function (data) {
					virList = data
          $("body").append(template.render(tpl.setPermissionsTpl)({
            personLen: list.length,
            personList: list,
            names: data
          }));
          $(".set-permession input:checkbox").on("change", function () {
            $(".set-permession .total").html($('.set-account-num input[name=account]:checkbox:checked').length + "家");
          });
          var persons = [];
          //关闭弹窗
          $(".close-btn").on("click", function () {
            $(".dialog-wp").remove();
          });
          $(".set-permession #groupId").on("change", function () {
            $(".hadPeople .set-account-num").html('');
						var groupId = $("#groupId").val();
						let companyList = [];
						let str = "";
						if(groupId){
							$.each(virList, function (index, item) {
                if(item.permId == groupId){
									companyList = item.virList
								}
							})
              $.each(companyList, function (index, item) {
                str += "<label><input type='checkbox' name='personed' value='" + item.virId + "' checked='checked'><span>" + item.virName + "</span></label>"
							})
							$(".hadPeople").show()
              $(".hadPeople .set-account-num").append(str);
						}else{
							$(".hadPeople").hide()
						}
            if (groupId != '') {
              // _this.ajaxCustomerList($("#groupId").val());
            } else {
              $(".hadPeople").css("display", "none");
            }
          });
          //确认添加
          $(".sure-add-btn").on("click", function () {
            $('.set-account-num input:checkbox:checked').each(function () {
              persons.push($(this).val())
            })
            if (!$(".dialog-wp #groupId").val()) {
              layer.msg("类型名称必填");
              return false;
            }
            // if (persons.length == 0) {
            // 	layer.msg("设置账号必选");
            // 	return false;
            // }
            _this.setUserPerm(persons,$("#groupId").val(), function () {
              $(".dialog-wp").remove();
              layer.msg("设置成功！")
              _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").val(),'/admin/templ/getOrgListByName')
			});
			$('body').on("focus",'#orgId',function(event){
				var _this = $(this)
				cjqt.search_fuzzy.event_focus(_this,'org__id','org__span',$("#contextPath").val(),'/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')
			});
		},
		/**
		 * 渲染table
		 */
		renderTable: function(){
			var _this = this;
			layui.use('table', function(){
				  table = layui.table;
				  
				  //方法级渲染
				  table.render({
				    elem: '#LAY_table_user',
				    method: 'post'
						,skin: 'nob' //行边框风格
						,even: true //开启隔行背景
						,size: 'lg' //小尺寸的表格
				    ,url: $("#contextPath").val()+ "/admin/virtual/getVirTualArchList"
				    ,cols: [[{
							type: 'checkbox',
							fixed: 'left'
						},
					  {
							field:'index', 
							title: '序号', 
							width: '5%',
							templet: '#indexTpl'
					 },{
							field:'orgName', 
							title: '校区', 
							width:'12%'
			     },
			    	 // {
			    	//	  field:'floorNames',
			    		//  title: '楼层',
			    		//  width:200
		    		 // },
						{
						field:'virName', 
						title: '公司名',
						width: '25%'
//	  				  },{
//						  field:'leaseStatus', 
//						  title: '在租状态', 
//						  width:200,
//						  templet: function(data){
//							if(data.leaseStatus==0){
//								return '已迁出';
//							}else{
//								return '在租'
//							}	
//						  }
						},{
						  field:'settleType', 
						  title: '企业结算方式', 
						  width: '8%',
						  templet: function(data){
							if(data.settleType==1){
								return '现结';
							}else if(data.settleType==2){
								return '月结'
							}else{
								return '暂未设置'
							}	
						  }
						},
						{
						  field:'virPermName', 
						  title: '企业类型', 
							width:'10%',
							style:'cursor: pointer;',
							event: 'readType'
					  },
					  {
						  field:'virAccount', 
						  title: '企业账号', 
						  width:'10%'
					  },
					  {
						  field:'isEnable', 
						  title: '企业账号状态', 
						  width:'8%',
						  templet: function(data){
							  var str = '';
							  if(!data.virAccount==""){
								  if(data.isEnable=="1"){
								    	str += '<div data-isEnable='+data.isEnable+'>启用</div>';
								    }else if(data.isEnable=="0"){
								    	str += '<div data-isEnable='+data.isEnable+'>禁用</div>';
								    }
							  }else{
								  str += '<div data-isEnable='+data.isEnable+'>无账号</div>';
							  }
								return str;
						  }
					  },
					  {
							field:'freeLenTime', 
							title: '月度免费时长', 
							width: '10%'
					  },{
							field:'remainderTime', 
							title: '剩余免费时长', 
							width: '10%'
					  },
					  {
						  field: 'manage', 
						  title: '操作', 
						  width: '300px',
						  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-virname='+data.virName+' data-orgId='+data.organizationId+'>编辑企业账号</button>';
						    	if(!data.virAccount==""){
						    		if(data.isEnable=="1"){
								    	str += '&nbsp&nbsp&nbsp<button class="t-btn t-white-btn t-del-btn" data-id='+data.id+' data-isEnable='+data.isEnable+'>禁用</button>';
								    }else if(data.isEnable=="0"){
								    	str += '&nbsp&nbsp&nbsp<button class="t-btn t-white-btn t-del-btn" data-id='+data.id+' data-isEnable='+data.isEnable+' >启用</button>';
								    }
						    	}else{
						    		str += '&nbsp&nbsp&nbsp<button class="t-btn t-white-btn t-del-btn" data-id='+data.id+' data-isEnable='+data.isEnable+' ></button>';
						    	}
									 str += '<button class="t-btn t-red-btn t-edit-other-btn" data-id='+data.id+' data-virname='+data.virName+' data-settletype='+data.settleType+' data-freelentime='+data.freeLenTime+' data-remaindertime='+data.remainderTime+' data-orgid='+data.organizationId+' data-permid='+data.permId+' data-func='+data.funcList+'>编辑其他</button>';
									 str += '<button  class="t-btn t-red-btn t-detail-btn"  lay-event="detail">查看详情</button>';
                }
						    	return str;
						  }
					  }
					  ]]
					    ,id: 'testReload'	
					    ,page: true,
					    where: {
//					    		floorId: $(".floor-select").val(),
//					    		roomId: $(".room-select").val(),
					    		isZuStatus: $(".zu-status-select").val(),
					    		virName: $(".virname-text").val(),
					    		orgId: $("#conditionform  #orgId").attr('org__id')
					    	},
					    response: {
					    	  statusName: 'code' //数据状态的字段名称，默认：code
					    	  ,statusCode: 200 //成功的状态码，默认：0
					    	  ,countName: "count"//数据总数的字段名称，默认：count
					    	  ,dataName: "data" //数据列表的字段名称，默认：data
							},
					    done: function(res, curr, count){
					    	
								  //复现之前选择数据
									table_data = res.data;
									//在缓存中找到id ,然后设置data表格中的选中状态
									//循环所有数据，找出对应关系，设置checkbox选中状态
									for (var i = 0; i < res.data.length; i++) {
										for (var j = 0; j < idsArr.length; j++) {
											//数据id和要勾选的id相同时checkbox选中
											if (res.data[i].id == idsArr[j].id) {
												//这里才是真正的有效勾选
												res.data[i]["LAY_CHECKED"] = 'true';
												//找到对应数据改变勾选样式，呈现出选中效果
												var index = res.data[i]['LAY_TABLE_INDEX'];
												$('.layui-table-fixed-l tr[data-index=' + index + '] input[type="checkbox"]').prop('checked', true);
												$('.layui-table-fixed-l tr[data-index=' + index + '] input[type="checkbox"]').next().addClass('layui-form-checked');
											}
										}
									}
								//设置全选checkbox的选中状态，只有改变LAY_CHECKED的值， table.checkStatus才能抓取到选中的状态
								var checkStatus = table.checkStatus('testReload');
								if (checkStatus.isAll) {
									$(' .layui-table-header th[data-field="0"] input[type="checkbox"]').prop('checked', true);
									$('.layui-table-header th[data-field="0"] input[type="checkbox"]').next().addClass('layui-form-checked');
								}
					      //编辑企业账号
					    	$(".t-edit-btn").on("click",function(){
					    		var virname = $(this).data("virname");
					    		var id = $(this).data("id");
					    		var orgId =$(".item-select").attr('org__id');
					    		//显示编辑企业账号弹窗
					    		_this.showEditDialog(virname,id,orgId)
					    	});
					    	//删除
					    	$(".t-del-btn").on("click",function(){
					    		var id = $(this).data("id");
					    		var isEnable=$(this).data("isenable");
					    		_this.ajaxDelTemp(id,isEnable,function(){
					    			Index = 0;
					    			 table.reload('testReload', {
										  where: { //设定异步数据接口的额外参数，任意设
											  virId: id
										  }
										  ,page: {
										    curr: 1 //重新从第 1 页开始
										  }
									}); 
					    		})
					    	});
					    	//编辑其他
					    	$(".t-edit-other-btn").on("click",function(){
					    		var otherInfo = {
					    				id: $(this).data("id"),
					    				virname: $(this).data("virname"),
					    				settleType: $(this).data("settletype"),
					    				freeLenTime: $(this).data("freelentime"),
											remainderTime: $(this).data("remaindertime"),
											orgId: $(this).data("orgid"),
											permId: $(this).data("permid"),
											funcList: $(this).data("func")
									};
									//显示编辑其他弹窗
									_this.showEditOtherDialog(otherInfo)				    	
					    	});
					      }
					});
					table.on('tool(user)', function (obj) {
						console.log(obj.event); //点击事件
						console.log(obj.data, 'ddd');
						if (obj.event === 'detail') {
							$("body").append(template.render(tpl.detailTpl)({
								otherInfo:obj.data
							}));
							//关闭
							$(".close-btn ,.dialog-edit-con .cancel-add-btn").on("click",function(){
								$(this).closest(".dialog-wp").remove();
							});
							//确定
							$(".sure-add-btn").on("click",function(){
								$(this).closest(".dialog-wp").remove();
							})
						} else if(obj.event == 'readType') {
							layer.msg('功能权限：'+obj.data.funcList, {
								time: 20000, //20s后自动关闭
							});
						}
          });
					//复选框选中监听,将选中的id 设置到缓存数组,或者删除缓存数组
					table.on('checkbox(user)', function (obj) {
						if (obj.checked == true) {
							if (obj.type == 'one') {
								idsArr.push(obj.data);
							} else {
								for (var i = 0; i < table_data.length; i++) {
									idsArr.push(table_data[i]);
								}
							}
						} else {
							if (obj.type == 'one') {
								for (var i = 0; i < idsArr.length; i++) {
									if (idsArr[i].id == obj.data.id) {
										idsArr.remove(i);
									}
								}
							} else {
								for (var i = 0; i < idsArr.length; i++) {
									for (var j = 0; j < table_data.length; j++) {
										if (idsArr[i].id == table_data[j].id) {
											idsArr.remove(i);
										}
									}
								}
							}
						};
						var newIdsArr = [];
						for (var i = 0; i < idsArr.length; i++) {
							var flag = true;
							for (var j = 0; j < newIdsArr.length; j++) {
								if (idsArr[i].id == newIdsArr[j].id) {
									flag = false;
								};
							};
							if (flag) {
								newIdsArr.push(idsArr[i]);
							};
						};
						//					console.log('newIdsArr',newIdsArr);
						//					console.log('idsArr',idsArr);
						idsArr = newIdsArr;
					});
				  //查询
				  $('#conditionform  .search-btn').on('click', function(){
						idsArr = []; //清空之前选择的数据
					  table.reload('testReload', {
						  where: { //设定异步数据接口的额外参数，任意设
//							  floorId: $(".floor-select").val(),
//					    		roomId: $(".room-select").val(),
					    		isZuStatus: $(".zu-status-select").val(),
					    		virName: $(".virname-text").val(),
					    		orgId: $(".item-select").attr('org__id')
						  }
						  ,page: {
						    curr: 1 //重新从第 1 页开始
						  }
					}); 
				  });
				});
		},
		
		/**
		 * 删除模板
		 * @param id 模板id
		 * @param callback
		 */
		ajaxDelTemp: function(id,isEnable,callback){
			var str="";
			if(isEnable=="1"){
				str="确认禁用?";
			}else{
				str="确认启用?";
			}
			layer.confirm(str, {
				  btn: ['确定', '取消'] 
				}, function(index, layero){
					 layer.close(index); //如果设定了yes回调，需进行手工关闭
					 $.ajax({
						   type: "post",
						   url: $("#contextPath").val()+ "/admin/virtual/deleteAccount", 
						   data: {
							   "virId": id,
							   "isEnable":isEnable
						   },
						   success: function(data){
							   if(data.code == 200){
								   callback();
							   }   
						   },
						   error: function(){   
						   }
				   });
				}, function(index){
					
				});	
		},
		
		/*重新渲染table*/
		againRenderTable: function(){
			console.log('test',$("#conditionform  #orgId").attr('org__id'))
			idsArr = []; //清空之前选择的数据
			table.reload('testReload', {
				where: {
					isZuStatus: $(".zu-status-select").val(),
		    		virName: $(".virname-text").val(),
		    		orgId: $("#conditionform  #orgId").attr('org__id') ? $("#conditionform  #orgId").attr('org__id'): ''
				} ,
				  page: {
				    curr: 1 //重新从第 1 页开始
				  }
			}); 
		},
		/**
		 * 渲染校区列表
		 * @param 
		 */
		renderItem: function(){
			var _this = this;
			 $.ajax({
				   type: "post",
				   url: $("#contextPath").val()+ "/admin/templ/getOrgList", 
				   success: function(data){
					   if(data.code == ERROR_OK){
						   console.log(data.data);
						  // itemList
						   // $(".item-select").html(template.render(tpl.itemList)({list:data.data}))
					   }else{
						   layer.alert(data.msg);
					   }   
				   },
				   error: function(){   
				   }
			   });
		},
		/**
		 * 显示编辑企业弹窗
		 * @param virname 企业名称
		 * @param id 企业id
		 */
		showEditDialog: function(virname,id,orgId){
			var _this = this;
			//获取企业账号和密码
			_this.ajaxVirInfo(id,function(data){
				var virInfo = {
					id: id,
					virname: virname,
					account: data.account,
					password: data.password,
					orgId:orgId
				}
				$("body").append(template.render(tpl.editTpl)(virInfo));
				//关闭
				$(".close-btn ,.dialog-edit-con .cancel-add-btn").on("click",function(){
					$(this).closest(".dialog-wp").remove();
				});
				//确定
				$(".sure-add-btn").on("click",function(){
					var $this = $(this);
					_this.ajaxUpdateVirname(id,orgId,function(){
						$this.closest(".dialog-wp").remove();
					})
				})
			})
		},
		/**
		 * 获取企业账号和密码
		 * @param id 企业id
		 * @param callback
		 */
		ajaxVirInfo: function(id,callback){
			var _this = this;
			$.ajax({
				   type: "post",
				   url: $("#contextPath").val()+ "/admin/virtual/getAccount", 
				   data: {
					   id: id,
					   type: 1 //1获取账号及密码2获取密码
				   },
				   success: function(data){
					   
					   if(data.code == ERROR_OK){
						  callback(data.data)
					   }else{
						   layer.alert(data.msg);
					   }   
				   },
				   error: function(){   
				   }
			   });
		},
		/**
		 *  新增或修改企业账号
		 * @param id
		 * @param callback
		 */
		ajaxUpdateVirname: function(id,orgId,callback){
			var _this = this;
			
//			if(!orgId){
//				layer.msg("请选择校区");
//				return  false;
//			};
			//账号
			var account = $(".account-input").val();
			if(!account){
				layer.msg("请输入账号");
				return  false;
			};
			//密码
			var password = $(".password-input").val();
			if(!password){
				layer.msg("请输入密码");
				return  false;
			};
			$.ajax({
				   type: "post",
				   url: $("#contextPath").val()+ "/admin/virtual/saveAccount", 
				   data: {
					   id: id,
					   account: account ,//账号
					   password: password, //密码
					   orgId:orgId
				   },
				   success: function(data){
					   
					   if(data.code == ERROR_OK){
						  layer.msg("修改成功！") ;
                           _this.againRenderTable();
						  callback()
					   }else{
						   layer.alert(data.msg);
					   }   
				   },
				   error: function(){   
				   }
			   });
		},
		/**
		 * 显示编辑其他弹窗
		 * @param otherInfo 企业信息（结算方式(1现结2月结)、月度免费时长、剩余免费时长）
		 */
		showEditOtherDialog: function(otherInfo){
			var _this = this;
			_this.getPermList(otherInfo.orgId,function(data){
				console.log(otherInfo)
				console.log(data)
				$("body").append(template.render(tpl.editOtherTpl)({
					otherInfo:otherInfo,
					funcListStr: data
				}));
				//关闭
				$(".close-btn ,.dialog-edit-con .cancel-add-btn").on("click",function(){
					$(this).closest(".dialog-wp").remove();
				});
				//确定
				$(".sure-add-btn").on("click",function(){
					var $this = $(this);
					_this.ajaxUpdateOther(otherInfo.id,function(){
						$this.closest(".dialog-wp").remove();
					})
				})
				// 企业类型选择
				$("#permType").on("change",function() {
					console.log($(this).val())
					virPermId = $(this).val()
					if($(this).val()){
						let str = ''
						let funcList = $("#permType").find("option:selected").attr('data-func')
						$(".funcList").show()
						str = "功能权限：" + funcList
						$(".funcList").html(str)
					}else{
						$(".funcList").hide()
					}
				})
			})
		},
		/**
		 *  修改免费时长
		 *  @param id
		 *  @param callback
		 */
		ajaxUpdateOther: function(id,callback){
			var _this = this;
			//结算类型
			var settleType = $('.dialog input[name="type"]:checked ').data("type");
			if(!settleType){
				layer.msg("请选择结算类型");
				return  false;
			};
			//月度免费时长
			var freeLenTime = $(".free-input").val();
			if(!isNaN(freeLenTime) && Number(freeLenTime)<0 ){
				layer.msg("请输入正确的月度免费时长");
				return  false;
			};
			//剩余免费时长
			var remainderTime= $(".remain-input").val();
			if(!isNaN(remainderTime) && Number(remainderTime)<0){
				layer.msg("请输入正确的剩余免费时长");
				return  false;
			};
			// 企业类型ID
			var virPermId= $("#permType").val();
			$.ajax({
				   type: "post",
				   url: $("#contextPath").val()+ "/admin/virtual/updateVirFreeTime", 
				   data: {
					   id: id,
					   settleType: settleType ,//账号
					   remainderTime: remainderTime, //密码
						 freeLenTime: freeLenTime,
						 virPermId: virPermId
				   },
				   success: function(data){
					   
					   if(data.code == ERROR_OK){
						  layer.msg("修改成功！") ;
						  _this.againRenderTable();
						  callback()
					   }else{
						   layer.alert(data.msg);
					   }   
				   },
				   error: function(){   
				   }
			   });
		},
		//请求对应校区的企业类型列表
		permissionListAjax: function (orgId, callback) {
			$.ajax({
				type: "post",
				url:  $("#contextPath").val() + "/admin/virPerm/getOrgRelationVirPermList",
				data: {
					orgId: orgId
				},
				success: function (data) {
					if (data.code == ERROR_OK) {
						callback(data.data)
					} else {
						layer.msg(data.msg)
					}
				},
				error: function (error) {
					layer.msg('error')
				}
			});
		},
		//请求对应校区的企业类型列表
		getPermList: function (orgId, callback) {
			$.ajax({
				type: "post",
				url:  $("#contextPath").val() + "/admin/virPerm/virPermList",
				data: {
					orgId: orgId,
					permType: '0',
					pageSize: 100000,
					pageNo: 1
				},
				success: function (data) {
					if (data.code == ERROR_OK) {
						callback(data.data)
					} else {
						layer.msg(data.msg)
					}
				},
				error: function (error) {
					layer.msg('error')
				}
			});
		},
		//请求对应校区的企业类型列表
		setUserPerm: function (virIds,virPermId, callback) {
			let virId = virIds.join(";");
			$.ajax({
				type: "post",
				url:  $("#contextPath").val() + "/admin/virPerm/batchSetVirPerm",
				data: {
					virIds: virId,
					virPermId: virPermId
				},
				success: function (data) {
					if (data.code == ERROR_OK) {
						callback(data.data)
					} else {
						layer.msg(data.msg)
					}
				},
				error: function (error) {
					layer.msg('error')
				}
			});
		}
	}
	enterprise.init();
});
