// 设备列表
$(function () {
  var ERROK = 200;
  var contextPath = $("#contextPath").val()
  var table;
  var allProjectList;
  var foodid;
  var tableData = [{
      name: '',
      orderNum: '',
      shortName: ''
    },{
      name: '',
      orderNum: '',
      shortName: ''
    },{
      name: '',
      orderNum: '',
      shortName: ''
    }]
  template.config("escape", false);
  var orgId = $("#orgId").attr('org__id');
  var virAccountInfo = $("#virAccountInfo").val()
  var tpl = {
    "addTplCopy": '<div class="dialog-wp addTplCopy">\
    <div class="mask"></div>\
    <div class="dialog dialog-account-con" style="width: 900px">\
      <div class="title-wp">\
        <span>新增部门</span>\
        <span class="close-btn"></button>\
      </div>\
      <div class="dialog-account-wp ">\
         <div class="account-list">\
          <%if(isAdmin == "true"){%>\
            <div class="account-item required clearfloat">\
              <div class="item-tip"><span class="red">*</span>校区：</div>\
              <div class="item-con">\
                <div class="layui-input-inline">\
                <input class="pop-select orgId layui-input" name="orgId" id="orgId" autocomplete="off" placeholder="请选择校区" />\
                <span class="select_wrap _hide"></span>\
              </div>\
            </div>\
            </div>\
          <%}%>\
          <%if(isAdmin  == "false"){%>\
            <input class="pop-select orgId layui-input" name="orgId" id="orgId" autocomplete="off" type="hidden" value="<%=orgId%>" org__id="<%=orgId%>"/>\
          <%}%>\
          <%if(virAccountInfo){%>\
            <input class="pop-select company-id layui-input" name="companyId" type="hidden" com__id="<%=virId%>" value="<%=virId%>" id="companyId" autocomplete="off" placeholder="请选择企业" />\
          <%}%>\
    	  <%if(!virAccountInfo){%>\
            <div class="account-item required clearfloat">\
              <div class="item-tip"><span class="red">*</span>企业名称：</div>\
              <div class="item-con">\
                <div class="layui-input-inline">\
                  <input class="pop-select company-id layui-input" name="companyId" id="companyId" autocomplete="off" placeholder="请选择企业" />\
                  <span class="select_wrap _hide"></span>\
                </div>\
              </div>\
            </div>\
           <%}%>\
          <div class="account-item required clearfloat" style="width: 800px;">\
            <div class="item-tip"><span class="red">*</span>新增部门：</div>\
            <div class="item-con" style="width:660px">\
              <div class="tables" style="width:100%">\
                <table class="layui-hide" id="demo" lay-filter="demo"></table>\
                <div class="addBtn">\
                  <button>+ 继续添加</button>\
                </div>\
              </div>\
            </div>\
          </div>\
          <div class="dialog-btns" style="border:0;width: 800px;">\
            <button class="sure-add-btn btn-red" style="margin-top: 10px;">确定</button>\
          </div>\
         </div>\
      </div>\
    </div>\
  </div>	',
    "addTpl": '<div class="dialog-wp">\
    <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(isAdmin == "true"){%>\
            <div class="account-item required clearfloat">\
              <div class="item-tip"><span class="red">*</span>校区：</div>\
              <div class="item-con">\
                <div class="layui-input-inline">\
                <input class="pop-select orgId layui-input" name="orgId" id="orgId" autocomplete="off" placeholder="请选择校区" />\
                <span class="select_wrap _hide"></span>\
              </div>\
            </div>\
            </div>\
          <%}%>\
          <%if(isAdmin  == "false"){%>\
            <input class="pop-select orgId layui-input" name="orgId" id="orgId" autocomplete="off" type="hidden" value="<%=orgId%>" org__id="<%=orgId%>"/>\
          <%}%>\
          <div class="account-item required clearfloat">\
            <div class="item-tip"><span class="red">*</span>企业名称：</div>\
            <div class="item-con">\
              <div class="layui-input-inline">\
                <input class="pop-select company-id layui-input" name="companyId" id="companyId" autocomplete="off" placeholder="请选择企业" />\
                <span class="select_wrap _hide"></span>\
              </div>\
            </div>\
          </div>\
          <div class="account-item required clearfloat">\
            <div class="item-tip"><span class="red">*</span>部门名称：</div>\
            <div class="item-con">\
              <div class="layui-input-inline">\
                <input class="pop-select apart-id layui-input" name="apartId" id="apartId" autocomplete="off" placeholder="请输入部门" />\
                <span class="select_wrap _hide"></span>\
              </div>\
            </div>\
          </div>\
          <div class="account-item required clearfloat">\
            <div class="item-tip">排序：</div>\
            <div class="item-con">\
              <input  type="text" class="item-input sort" placeholder="请输入排序">\
            </div>\
          </div>\
          <div class="account-item required clearfloat">\
            <div class="item-tip">简称：</div>\
            <div class="item-con">\
              <input  type="text" class="item-input abbrev" placeholder="请输入简称">\
            </div>\
            </div>\
          </div>\
          <div class="dialog-btns">\
            <button class="sure-add-btn btn-red">确定</button>\
          </div>\
         </div>\
      </div>\
    </div>\
  </div>	',
    "modifyTpl": '<div class="dialog-wp">\
    <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">\
              <div class="layui-input-inline">\
                <input class="pop-select orgId layui-input disabled" name="orgId" id="orgId" autocomplete="off" org__id="<%=orgId%>" value="<%=orgName%>" disabled/>\
              </div>\
            </div>\
          </div>\
          <div class="account-item required clearfloat">\
            <div class="item-tip"><span class="red">*</span>企业名称：</div>\
            <div class="item-con">\
              <div class="layui-input-inline">\
                <input class="pop-select apart-id layui-input disabled" name="companyId" id="companyId" autocomplete="off" com__id="<%=virId%>" value="<%=virName%>" disabled/>\
              </div>\
            </div>\
          </div>\
          <div class="account-item required clearfloat">\
            <div class="item-tip"><span class="red">*</span>部门名称：</div>\
            <div class="item-con">\
              <div class="layui-input-inline">\
                <input class="pop-select apart-id layui-input" name="apartId" id="apartId" autocomplete="off" dep__id="<%=deptName%>" value="<%=deptName%>"/>\
                <span class="select_wrap _hide"></span>\
              </div>\
            </div>\
          </div>\
          <div class="account-item required clearfloat">\
            <div class="item-tip">排序：</div>\
            <div class="item-con">\
              <input  type="text" class="item-input sort" placeholder="请输入排序" value="<%=orderNum%>">\
            </div>\
          </div>\
          <div class="account-item required clearfloat">\
            <div class="item-tip">简称：</div>\
            <div class="item-con">\
              <input  type="text" class="item-input abbrev" placeholder="请输入简称" value="<%=shortName%>">\
            </div>\
            </div>\
          </div>\
          <div class="dialog-btns">\
            <button class="sure-add-btn btn-red">确定</button>\
          </div>\
         </div>\
      </div>\
    </div>\
  </div>',
  "exportTplNo": '<div class="dialog-wp">\
  <div class="mask"></div>\
  <div class="dialog export-or-download-con">\
    <div class="title-wp">\
      <span>导入账号</span>\
      <span class="close-btn"></button>\
    </div>\
    <div class="export-or-download-wp">\
      <input type="hidden" class="default-select d-orgid" name="orgId" id="orgId" org__id="<%=orgId %>"/>\
      <div class="choose-item-wp">\
        <span class="tip">企业</span>\
        <input class="default-select d-companyid"  autocomplete="off" placeholder="请输入企业名称"/>\
                <span class="select_wrap _hide"></span>\
      </div>\
      <div class="export-or-download-btns">\
         <button class="sure-operate-btn sure-operate-btn-single btn-red-width90" type="button">导入<input class="excelFile" type="file" id="excelFile" name="excelFile" /></button> \
      </div>\
    </div>\
  </div>\
  </div>',
  "exportTpl": '<div class="dialog-wp">\
  <div class="mask"></div>\
  <div class="dialog export-or-download-con">\
    <div class="title-wp">\
      <span>导入账号</span>\
      <span class="close-btn"></button>\
    </div>\
    <div class="export-or-download-wp">\
      <div class="choose-item-wp">\
        <span class="tip">校区</span>\
        <input class="default-select d-orgid" name="orgId" id="orgId"  autocomplete="off" placeholder="请输入校区名称"/>\
                <span class="select_wrap _hide"></span>\
      </div>\
      <div class="choose-item-wp">\
        <span class="tip">企业</span>\
        <input class="default-select d-companyid"  autocomplete="off" placeholder="请输入企业名称"/>\
                <span class="select_wrap _hide"></span>\
      </div>\
      <div class="export-or-download-btns">\
        <button class="sure-operate-btn sure-operate-btn-mult btn-red-width90" type="button">导入<input class="excelFile" type="file" id="excelFile" name="excelFile" /></button> \
      </div>\
    </div>\
  </div>\
  </div>',
  };
  var api = {
    init: function () {
      this.render();
      this.bindEvent();
    },
    render: function () {
      this.rendertable("","");
    },
    bindEvent: function () {
      var _this = this;
      _this.getProjectList();
      //重置
      $(".set-btn").on("click", function () {
    	 var $dom = $("#conditionform #orgId,#conditionform input")
         $dom.val("").removeAttr('org__id')
    	 _this.againRenderTable({type:1});

      });
      $('.saveDialogBtn').click(function () {
    	  $('.alert3').css('display', 'none');
    	  })
    	  
    	  //取消Edit
          $('.cancelEditBtn').click(function () {
              $('.projectotherId').val('')
              $('#organizationId').val('')
              $('#virtualId').val('')
              var projectArr=$('.part-wp-project-edit')
              for(var j=projectArr.length-1;j>=0;j--){
              	if(j>0){
              		projectArr.eq(j).remove()	
              	}
              }
      	    $('.alert3').css('display', 'none');
      	    layui.form.render();
      	   _this.againRenderTable({type:1});
            })
      // 取消
      $('.cancelBtn').click(function () {
        $('input[name="username"]').val('');
        $('input[name="mobile"]').val('');
        $('input[name="carNumber"]').val('');
       
        $('.form_alert   input:radio[name="price_type"]').eq(0).attr("checked",'checked');
	    $('.form_alert   input:radio[name="price_type"]').eq(0).attr("checked",true);
	    
	    $("input[name=price_type][value=0]").prop("checked","true");
        $("input[name=price_type][value=1]").prop("checked","false");

        $('.projectotherId').val('')
        $('#organizationId').val('')
        $('#virtualId').val('')
        var projectArr=$('.part-wp-project')
        for(var j=projectArr.length-1;j>=0;j--){
        	if(j>0){
        		projectArr.eq(j).remove()	
        	}
        }
	    $("#virtualId").parent().parent().hide();
	    $('.alert').css('display', 'none');
	    layui.form.render();
      })
       // 保存
      $('.saveBtn').click(function () {
    	  let id = '';
    	  let serialNumber = null;
    	  var orgIdotherStr = '';
    	  var orgIdotherArrObj = $("input[name='orgIdother']");
    	  console.log("allProjectList",allProjectList[0]);
    	  for(var t=0;t<orgIdotherArrObj.length;t++){
    		  console.log(orgIdotherArrObj.eq(t).val())
    		  for(var j=0;j<allProjectList.length;j++){
    			  if(orgIdotherArrObj.eq(t).val()==allProjectList[j].name){
    				  orgIdotherStr+=allProjectList[j].id+",";
    			  }
    		  }
    	  }
    	  	//console.log(orgIdotherStr);
    	  var foodType=$("input[type='radio']:checked").val();
    	  console.log("饭卡类型",foodType);
    	  if(foodType=='0'){
    		  foodType="2" 
    	  }else{
    		  foodType="1"  
    	  }
    	  let data = {
    			  id: id,
    			  food_name: $('input[name="username"]').val(),
    			  account_number: $('input[name="mobile"]').val(),
    			  account_password: $('input[name="carNumber"]').val(),
    			  orgId: $('#organizationId').attr('org__id'),
    			  food_type:foodType,
    			  virt_id:$("#virtualId").attr('com__id'),
    			  org_ids:orgIdotherStr,
    	  			}
    	  	console.log('保存的data',data)
    	  	 if(!data.food_name){
    	    	 layer.msg('请输入饭卡组名称')	
        		 return
    	    }
    	    if(!data.account_number){
    	    	 layer.msg('请输入手机号')	
        		 return
    	    }
    	    if(!data.account_password){
    	    	 layer.msg('请输入密码')	
        		 return
    	    }
           if(data.food_type=='2'){
        	if(!data.virt_id){
        		 layer.msg('请选择企业')	
        		 return
        	   }
             }
           $(".saveBtn").attr('disabled',true);  
           $('.saveBtn').css("background","grey");
    	  _this.saveCardInfo(data);
         
       })
       
		
	    $('#addProject').click(function () {
	    //	console.log("点击了新增校区");
	    	var project_arr = $('.part-wp-project');
	    	var last_obj = project_arr.eq(0).parent();
//	    	last_obj.after(last_obj.html())
//	    	return false;
	    	
	    	$(this).parent().before(last_obj.html())
	    });
      
      $('#addEditProject').click(function () {
  	    //	console.log("点击了新增校区");
  	    	var project_arr = $('.part-wp-project-edit');
  	    	var last_obj = project_arr.eq(0).parent();
//  	    	last_obj.after(last_obj.html())
//  	    	return false;
  	    	$(this).parent().before(last_obj.html())
  	    	
  	    });
	    
	    $('body').on('click','.delete_Project',function () {
	    	  if($('input[name="orgIdother"]').length>1){
	    		  $(this).parent().parent().remove();
	    	  }  	  
	      });
	    $('body').on('click','.delete_editProject',function () {
	    	var delProjectName=$(this).parent().find("input[name='orgIdEditother']").eq(0).val()
	    	console.log($(this).parent().find("input[name='orgIdEditother']").eq(0).val());
	    	let delectId;
	    	for(var j=0;j<allProjectList.length;j++){
  			  if(delProjectName==allProjectList[j].name){
  				delectId=allProjectList[j].id
  			  }
  		    }
	    	if($('input[name="orgIdEditother"]').length>1){
	    		_this.orgedit(delectId,'del');
	    		$(this).parent().parent().remove();
	    	}
	      });
	    //保存
	    $('body').on('click','.save_editProject',function () {
	    	var delProjectName=$(this).parent().find("input[name='orgIdEditother']").eq(0).val()
	    	console.log($(this).parent().find("input[name='orgIdEditother']").eq(0).val());
	    	let delectId;
	    	for(var j=0;j<allProjectList.length;j++){
  			  if(delProjectName==allProjectList[j].name){
  				delectId=allProjectList[j].id
  			  }
  		    }
	    	_this.orgedit(delectId,'add');
	      });
	    
      //新增
      $(".add-ele-btn").on("click", function () {
    	  	$('.alert').css('display', 'block');
    	    $('.alert .alert_con>h2').text('新增卡组');
    	    $('.form_alert   input:radio[name="price_type"]').eq(1).attr("checked",'checked');
    	    $('.form_alert   input:radio[name="price_type"]').eq(1).attr("checked",true);
    	    
    	    $("input[name=price_type][value=0]").prop("checked","true");
            $("input[name=price_type][value=1]").prop("checked","false");
    	    $("#virtualId").parent().parent().hide();
    	    layui.form.render();
    	  //通用
    	    $(".form_alert .layui-form-radio").eq(0).on("click",function (){
    	    	$("#virtualId").parent().parent().hide();
    	    	$(".part-wp-project").show();
    	    	$("#addProject").show();
    	    	
    	    });
    	    //企业
    	    $(".form_alert .layui-form-radio").eq(1).on("click",function (){
    	    	$("#virtualId").parent().parent().show();
    	    	$(".part-wp-project").hide();
    	    	$("#addProject").hide();
    	    	
    	    });
      });
      $('.selector').change(function () {
	    	 console.log("点击选校区", 222222222);	  
	      });
      //多校区
			$(".export-btn").on("click", function () {
				_this.exportFile();
      })
      //单校区
			$(".export-wp-no").on("click", function () {
        var $orgId = $("#conditionform  .single-orgid");
				_this.exportFile($orgId.length);
      })
      // 模版事件
			$("body").on("click",'.close-btn', function () {
				$(".dialog-wp").remove();
			});
			// (单)
			$("body").on("change", ".sure-operate-btn-single input", function () {
				var virId = $(".d-companyid").attr('com__id');
				if (!virId) {
					layer.msg("请选择企业");
					$(this).val('');
					return false;
				};
				_this.exportFileAjax($("#conditionform  .single-orgid").attr('org__id'), virId, function () {
					$(".dialog-wp").remove();
				})
			});
			// (多)
			$("body").on("change", ".sure-operate-btn-mult input", function () {
				var orgId = $(".d-orgid").attr('org__id');
				var virId = $(".d-companyid").attr('com__id');
				if (!orgId) {
					layer.msg("请选择校区");
					$(this).val('');
					return false;
				};
				if (!virId) {
					layer.msg("请选择企业");
					$(this).val('');
					return false;
				};
				_this.exportFileAjax(orgId, virId, function () {
					$(".dialog-wp").remove();
				})
			});
	   _this.getAllProject();
      // 模糊搜索
      _this.search_fuzzy();
      _this.search_main();
      _this.search_otherproject();
      _this.search_editproject();
      
    },
    orgedit:function(orgid,type){
    	  $.ajax({
    	        type: "post",
    	        url: $("#contextPath").val() + "/virtfood/orgedit",
    	        data: {
    	        	orgid:orgid,
    	        	foodid:foodid,
    	        	type:type
    	        },
    	        success: function (data) {
    	          var data = data;
    	          if (data.code == '200') {
    	        	  layer.msg("操作成功！");
    	          } else {
    	            layer.msg(data.msg)
    	          }
    	        },
    	        error: function (error) {
    	          layer.msg('error')
    	        }
    	      });
    },
    //获取所有的校区数组
    getAllProject:function(){
  	  $.ajax({
  	        type: "post",
  	        url: $("#contextPath").val() + "/admin/templ/getOrgListByName",
  	        data: {
  	      
  	        },
  	        success: function (data) {
  	          var data = data;
  	          if (data.code == '200') {
  	        	allProjectList=data.data
  	          } else {
  	            layer.msg(data.msg)
  	          }
  	        },
  	        error: function (error) {
  	          layer.msg('error')
  	        }
  	      });
    },
    search_editproject: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.EditOtherprojectEdit',
                com_target:'.default-select#virtualId',
                dep_target:'.default-select#apartId',
              });
              var option_2 = $.extend(true,{},default_option,{
                org_target:'.pop-select.EditOtherprojectEdit',
                com_target:'.pop-select#virtualId',
              });
              var option_3 = $.extend(true,{},default_option,{
        				org_target:'.d-orgid',
        				com_target:'.d-companyid'
        			});

              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})
              eve(option_1,{type:3})
              // 新增、修改联动
              eve(option_2,{type:1})
              eve(option_2,{type:2,
                click_callback:function(){
                  $("td[data-field='name']").data('edit', 'text')
                  $("td[data-field='orderNum']").data('edit', 'number')
                  $("td[data-field='shortName']").data('edit', 'text')
                  // $("td").data('edit', 'text')
              }})
              //导入联动
        			eve(option_3,{type:1})
        			eve(option_3,{type:2})
    },
    search_otherproject: 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.projectotherId',
          com_target:'.default-select#virtualId',
          dep_target:'.default-select#apartId',
        });
        var option_2 = $.extend(true,{},default_option,{
          org_target:'.pop-select.projectotherId',
          com_target:'.pop-select#virtualId',
        });
        var option_3 = $.extend(true,{},default_option,{
  				org_target:'.d-orgid',
  				com_target:'.d-companyid'
  			});

        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})
        eve(option_1,{type:3})
        // 新增、修改联动
        eve(option_2,{type:1})
        eve(option_2,{type:2,
          click_callback:function(){
            $("td[data-field='name']").data('edit', 'text')
            $("td[data-field='orderNum']").data('edit', 'number')
            $("td[data-field='shortName']").data('edit', 'text')
            // $("td").data('edit', 'text')
        }})
        //导入联动
  			eve(option_3,{type:1})
  			eve(option_3,{type:2})
      },
    // 模糊搜索校区
    search_main: 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#orgId',
        com_target:'.default-select#virtualId',
        dep_target:'.default-select#apartId',
      });
      var option_2 = $.extend(true,{},default_option,{
        org_target:'.pop-select#orgId',
        com_target:'.pop-select#virtualId',
      });
      var option_3 = $.extend(true,{},default_option,{
				org_target:'.d-orgid',
				com_target:'.d-companyid'
			});

      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})
      eve(option_1,{type:3})
      // 新增、修改联动
      eve(option_2,{type:1})
      eve(option_2,{type:2,
        click_callback:function(){
          $("td[data-field='name']").data('edit', 'text')
          $("td[data-field='orderNum']").data('edit', 'number')
          $("td[data-field='shortName']").data('edit', 'text')
          // $("td").data('edit', 'text')
      }})
      //导入联动
			eve(option_3,{type:1})
			eve(option_3,{type:2})
    },
    // 模糊搜索校区
    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',
        dep_target:'.default-select#apartId',
      });
      var option_2 = $.extend(true,{},default_option,{
        org_target:'.pop-select#orgId',
        com_target:'.pop-select#virtualId',
      });
      var option_3 = $.extend(true,{},default_option,{
				org_target:'.d-orgid',
				com_target:'.d-companyid'
			});

      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})
      eve(option_1,{type:3})
      // 新增、修改联动
      eve(option_2,{type:1})
      eve(option_2,{type:2,
        click_callback:function(){
          $("td[data-field='name']").data('edit', 'text')
          $("td[data-field='orderNum']").data('edit', 'number')
          $("td[data-field='shortName']").data('edit', 'text')
          // $("td").data('edit', 'text')
      }})
      //导入联动
			eve(option_3,{type:1})
			eve(option_3,{type:2})
    },

    rendertable: function (orgId, userName) {
      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() + "/virtfood/managerList",
          method: "post",
          where: {
        	orgId: orgId,
          	food_name: userName
          },
          skin: 'nob', //行边框风格
          even: true, //开启隔行背景
          size: 'lg', //小尺寸的表格
          limit: 10,
          cols: [
            [{
              field: 'index',
              title: '序号',
              width: '96',
              templet: '#indexTpl'
            }, {
              field: 'food_name',
              title: '卡组名称',
              width: 150
            },{
          	  field: 'org_name',
    		  title: '校区主体',
    		  minWidth: 200,
    		  templet: function(data){
    			  var str = "<div class='operate'>";
    			  str += "<button class='t-btn t-red-btn t-del-btn' lay-event='showproject' >"+data.org_name+"</button>";
                  str += "</div>";
                  return str;
			  }  
		  }, {
              field: 'food_type',
              title: '类型',
              minWidth: 150,
              templet: function(data){
				  var str = '';
				  if(data.food_type==1){
					  return '通用类型'
				  }else if(data.food_type==2){
					  return '企业类型'
				  }
				  return str;
			  }
            }, {
              field: 'account_number',
              title: '账号',
              minWidth: 150
            }, {
              field: 'account_password',
              title: '密码',
              width: 150
            }, {
              field: 'card_no',
              title: '饭卡ID',
              minWidth: 120
            }, {
  			  field:'approval_status', 
			  title: '审核结果', 
			  minWidth: 120,
			  templet: function(data){
				  var str = '';
				  if(data.approval_status==1){
					  return '待审核'
				  }else if(data.approval_status==2){
					  return '审核通过'
				  }else if(data.approval_statuss==3){
					  return '审核不通过' 
				  }else{
					  return '待审核' 
				  }
				  return str;
			  }
		     }, {
   			  field:'enabled', 
			  title: '状态', 
			  minWidth: '120',
			  templet: function(data){
				  var str = '';
				  if(data.enabled==1){
					  return '启用'
				  }else if(data.enabled==2){
					  return '禁用'
				  }
				  return str;
			  }
		     },{
              title: '操作',
              fixed: 'right',
              width: 150,
              align: 'center',
              templet: function (data) {
            	  var str = "<div class='operate'>";
                  if(data.enabled == 1){
					  str += "<button class='t-btn t-white-btn t-del-btn' lay-event='disable' >禁用</button>";
				  }else {
					  str += "<button class='t-btn t-red-btn t-edit-btn' lay-event='able' >启用</button>";
				  }
                  str += "<button class='t-btn t-red-btn t-edit-btn' lay-event='deleteHandle' >删除</button>";
                  str += "</div>";
                  return str;
              }
            }]
          ],
          id: 'testReload',
          page: true,
          response: {
            statusName: 'code' //数据状态的字段名称，默认：code
              ,
            statusCode: 200 //成功的状态码，默认：0
              ,
            countName: "count" //数据总数的字段名称，默认：count
              ,
            dataName: "data" //数据列表的字段名称，默认：data
          },
          request: {
            pageName: 'page' //页码的参数名称，默认：page
              ,
            limitName: 'limit' //每页数据量的参数名，默认：limit
          },
          done: function (res, curr, count) {
            $(".edit,.delete").mouseover(function(){
              $(this).next().show();
            })
            $(".edit,.delete").mouseout(function(){
              $(this).next().hide();
            })
            //如果是异步请求数据方式，res即为你接口返回的信息。
            //删除
            $(".op_del_btn").on("click", function () {
              var id = $(this).data("id");
              _this.ajaxDelTemp(id, function () {
                _this.againRenderTable();
              })
            });
            //修改
            $(".op_edit_btn").on("click", function () {
              var id = $(this).data("id");
              _this.ajaxDetail(id, 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 () {
                  var name = $('.pop-select#apartId').val()
                  _this.submitMod(name,function () {
                    $(".dialog-wp").remove();
                    layer.msg("修改成功！");
                    _this.againRenderTable();
                  }, id);
                })
              });
            });
          }
        });
        table.on('tool(user)',function(obj){
//        	console.log("obj",obj.event);
        	if (obj.event === 'disable') {//禁用
        		//console.log('禁用',obj.data.approval_status);
        		if(obj.data.approval_status=='9'||obj.data.approval_status=='1'){
        			 layer.msg('当前饭卡信息未审核');
        			 return ;
        		}
                layer.confirm('确定禁用吗？', function (index) {
                	_this.get_user_del(obj.data.id,'2');
                  layer.close(index);
                });
              }else if(obj.event === 'able'){//开启
            	if(obj.data.approval_status=='9'||obj.data.approval_status=='1'){
           			 layer.msg('当前饭卡信息未审核');
           			 return ;
           		 }
           		  
            	  layer.confirm('确定启用吗？', function (index) {
            		  _this.get_user_del(obj.data.id,'1');  
                	  layer.close(index);
                   });
              }else if (obj.event === 'showproject') {
            	  $('.alert3').css('display', 'block');
            	  $('.alert3 .alert_con>h2').text('主体校区');
//            	  console.log("111111",obj.data);
            	  foodid=obj.data.id
                  $('#foodName').val(obj.data.org_name);
                  if(obj.data.food_type=="1"){
                	  $('.lookCompanyName').css('display', 'none');
                	  $(".part-wp-project-edit").show();
          	    	  $("#addEditProject").show();
                  }else if(obj.data.food_type=="2"){
                	  $('.lookCompanyName').css('display', 'block');
                	  $(".part-wp-project-edit").hide();
          	    	  $("#addEditProject").hide();
                	  
                  }
                  $('#companyName').val(obj.data.virt_name);
                  //显示多个校区
                  if(obj.data.iorg_name){
                	  var projectOtherLists=obj.data.iorg_name.split(',')
//                	  console.log('projectOtherLists',projectOtherLists);
                	  for(let r=0;r<projectOtherLists.length-1;r++){
                		  var project_arr = $('.part-wp-project-edit');
      					  var last_obj = project_arr.eq(0).parent();
      					  last_obj.after(last_obj.html())
                	  }
                	  var orgIdotherArrObj = $("input[name='orgIdEditother']");
//                	  console.log("orgIdotherArrObj",orgIdotherArrObj)
                	   for(let k=0;k<projectOtherLists.length;k++){
                		   for(let j=0;j<orgIdotherArrObj.length;j++){
                			   if(k==j){
                				   orgIdotherArrObj.eq(j).val(projectOtherLists[k])
                			   }
                		   }
                	  }
//                	  for(let k=0;k<projectOtherLists.length;k++){
//                		  $("input[name='orgIdEditother']").val(projectOtherLists[k])
////                		  $('.EditOtherprojectEdit').val(projectOtherLists[k]) 
//                	  }
                  }
              }else if(obj.event === 'deleteHandle'){
            	   var id =obj.data.id;
                   _this.ajaxDelTemp(id, function () {
                     _this.againRenderTable();
                   })
              }
        	
        });
        //查询
        $('.search-btn').on('click', function () {
          _this.againRenderTable();
        });
      });
    },
    //新增信息保存
    saveCardInfo:function(params){
    	var _this=this
    	  $.ajax({
    	        type: "post",
    	        url: $("#contextPath").val() + "/virtfood/save",
    	        data: {
    	          id: params.id,
    	          food_name: params.food_name,
    	          account_number: params.account_number,
    	          account_password: params.account_password,
    	          org_id: params.orgId,
    	          food_type:params.food_type,
    	          virt_id:params.virt_id,
    	          org_ids:params.org_ids,
    	        },
    	        success: function (data) {
    	          var data = data;
    	          setTimeout(function(){
    	               $(".saveBtn").removeAttr("disabled");
    	               $('.saveBtn').css("background","#158DF6");
    	           },2000);
    	          if (data.code == '200') {
    	        	  console.log("新增返回",data);
    	            layer.msg(data.msg);
    	            $('input[name="username"]').val('');
    	            $('input[name="mobile"]').val('');
    	            $('input[name="carNumber"]').val('');
    	            $('.form_alert   input:radio[name="price_type"]').eq(0).attr("checked",'checked');
    	    	    $('.form_alert   input:radio[name="price_type"]').eq(0).attr("checked",true);
    	    	    $("input[name=price_type][value=0]").prop("checked","true");
    	            $("input[name=price_type][value=1]").prop("checked","false");

    	            $('.projectotherId').val('')
    	            $('#organizationId').val('')
    	            $('#virtualId').val('')
    	            var projectArr=$('.part-wp-project')
    	            for(var j=projectArr.length-1;j>=0;j--){
    	            	if(j>0){
    	            		projectArr.eq(j).remove()	
    	            	}
    	            }
    	    	    $("#virtualId").parent().parent().hide();
    	    	    $('.alert').css('display', 'none');
    	    	    layui.form.render();
    	            
    	            _this.rendertable("","");
    	            param = {};
    	          } else {
    	             layer.msg(data.msg)
    	            _this.rendertable("","");
    	          }
    	        },
    	        error: function (error) {
    	          layer.msg('error')
    	        }
    	      });
    },
    //启用  禁用
    get_user_del:function(cardId,status){
    	 var _this = this;
    	$.ajax({
            type: "post",
            url: $("#contextPath").val() + "/virtfood/openorclose",
            data: {
            	id: cardId,
            	status:status,
            },
            success: function (data) {
              console.log(data, 222222222);
              if (data.code == '200') {
                layer.msg(data.msg)
                _this.rendertable();
              } else {
                layer.msg(data.msg)
              }
            },
            error: function (error) {
              layer.msg('error')
            }
          });
    	
    },
    /**
     * 删除模板
     * @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() + "/virtfood/delete",
          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 (option) {
      var obj = $.extend(true, {}, option);
      var type =  obj.type || ''
      var $orgId = $("#conditionform  .single-orgid");
      var orgId = $('#orgId').attr('org__id')
        if(type == 1){
            table.reload('testReload', {
              where: {
                orgId: '',
                food_name: '',
              },
              page: {
                curr: 1 //重新从第 1 页开始
              }
            });
          
        }else{
          table.reload('testReload', {
            where: {
              orgId:orgId,
              food_name:  $('input[name="user"]').val(),
            },
            page: {
              curr: 1 //重新从第 1 页开始
            }
          });
        }
    
    },
    getProjectList: function (id, callback) {
        var _this = this;
        $.ajax({
          type: "post",
          url: contextPath + "/admin/templ/getOrgListByName",
          success: function (data) {
              $("#mainProject").html("<option value=''>请选择校区</option>");
              let comArr = "";
           $.each(data.data, function (index, item) {
             comArr += "<option value='" + item.id + "'>" + item.name + "</option>"
           })
           $("#mainProject").append(comArr);
          // _this.getCompanyList()
          },
          error: function (error) {
            layer.msg('error')
          }
        });
      },
    /**
     * 请求详情
     * @param id
     * @param callback
     */
    ajaxDetail: function (id, callback) {
      var _this = this;
      $.ajax({
        type: "post",
        url: contextPath + "/admin/dept/deptInfo",
        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 callback
     * @param id
     */
    submitAdd: function (deptListJson,callback, id) {
      var _this = this;
      var formData = new FormData();
      if(id){
        formData.append("id", id);
      }
      formData.append("deptListJson", deptListJson);
      formData.append("virId", $(".dialog-wp #companyId").attr('com__id'));
      formData.append("orgId", $(".dialog-wp #orgId").attr('org__id'));
      $.ajax({
        type: "post",
        url: $("#contextPath").val() + "/admin/dept/saveUpdateDept",
        data: formData,
        cache: false, // 不缓存
				processData: false, // 告诉jQuery不要去处理发送的数据
				contentType: false, // 告诉jQuery不要去设置Content-Type请求头
        success: function (data) {
          if (data.code == 200) {
            callback();
          } else {
            layer.msg(data.msg)
          }
        },
        error: function () {
          // layer.msg('系统繁忙.....')
        }
      });
    },   
    /**
     * 修改
     * @param callback
     * @param id
     */
    submitMod: function (name,callback, id) {
      var _this = this;
      var formData = new FormData();
      if(id){
        formData.append("id", id);
      }
      formData.append("name", name);
      formData.append("orderNum", $('.item-input.sort').val());
      formData.append("shortName", $('.item-input.abbrev').val());
      formData.append("virId", $(".dialog-wp #companyId").attr('com__id'));
      formData.append("orgId", $(".dialog-wp #orgId").attr('org__id'));
      $.ajax({
        type: "post",
        url: $("#contextPath").val() + "/admin/dept/saveUpdateDept",
        data: formData,
        cache: false, // 不缓存
        processData: false, // 告诉jQuery不要去处理发送的数据
        contentType: false, // 告诉jQuery不要去设置Content-Type请求头
        success: function (data) {
          if (data.code == 200) {
            callback();
          } else {
            layer.msg(data.msg)
          }
        },
        error: function () {
          // layer.msg('系统繁忙.....')
        }
      });
    },  
    /**
     * 部门名称是否重复
     * @param id
     * @param callback
     */
    isRepeatByDept: function (name, callback) {
      var _this = this;
      $.ajax({
        type: "post",
        url: contextPath + "/admin/dept/isRepeatByDept",
        data: {
          orgId: $(".dialog-wp #orgId").attr('org__id'),
          virId: $(".dialog-wp #companyId").attr('com__id'),
          name: name,
          id: ''
        },
        success: function (data) {
          if (data.code == ERROK) {
            
          } else {
            layer.msg(data.msg)
            callback()
          }
        },
        error: function (error) {
          layer.msg('error')
        }
      });
    },
    /**
		 * 导入弹框
		 * @param length 判断是单校区还是多校区 ，为0多校区 不为0单校区 
		 */
		exportFile: function (length) {
			var _this = this;
			if (!!length) {
				$("body").append(template.render(tpl.exportTplNo)({
					orgId:$("#conditionform  .single-orgid").attr('org__id'),
				}));
			} else {
				$("body").append(template.render(tpl.exportTpl));
			}
    },
    /**
		 * 导入数据
		 * @param orgId 校区id
		 * @param callback
		 */
		exportFileAjax: function (orgId, virId, callback) {
			var _this = this;
			var fileName = $("#excelFile").val();
			var extension = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length);
			var formData = new FormData();
			if (extension == "xlsx") {
				if (fileName == null || fileName == "") {
					layer.alert("数据导入为空,请按照模板填写资料后再导入!");
					return;
				};
				formData.append("orgId", orgId);
				formData.append("virId", virId);
				formData.append("excelFile", $("#excelFile")[0].files[0]);
				$.ajax({
					type: "post",
					url: $("#contextPath").val() + "/admin/dept/importDept",
					data: formData,
					cache: false, // 不缓存
					processData: false, // 告诉jQuery不要去处理发送的数据
					contentType: false, // 告诉jQuery不要去设置Content-Type请求头			 
					success: function (data) {
						if (data.code == '200') {
							callback && callback();
							_this.againRenderTable();
						} else {
							layer.msg(data.msg);
							$(".dialog-wp").remove();
						}
					},
					error: function () {

						layer.msg('error')
					}
				});
			} else {
				layer.alert("请上传xlsx格式的文件");
			}
		},
  };
  api.init();
})