// 设备列表
$(function () {
  var ERROK = 200;
  var contextPath = $("#contextPath").val()
  var table;
  var logo1="";
  var logo2="";
  var logo3="";
  var logo4="";
  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>',
  "imgTpl": '<div class="r-item-img-wp">\
		<div class="r-item-img"></div>\
		<span class="r-item-del-btn"></span>\
	 </div>',
	 "imgTpl1": '<div class="r-item-img-wp1">\
			<div class="r-item-img1"></div>\
			<span class="r-item-del-btn1"></span>\
		 </div>',
		 "imgTpl2": '<div class="r-item-img-wp2">\
				<div class="r-item-img2"></div>\
				<span class="r-item-del-btn2"></span>\
			 </div>',
			 "imgTpl3": '<div class="r-item-img-wp3">\
					<div class="r-item-img3"></div>\
					<span class="r-item-del-btn3"></span>\
				 </div>',
  };
  var api = {
    init: function () {
      this.render();
      this.bindEvent();
    },
    render: function () {
      this.rendertable();
      this.initData();
      this.getFoodCardList();
    },
    bindEvent: function () {
      var _this = this;
      
      $("#sendQueueChannel").on("change", function (value) {
    	  var label_id=($(this).val());
        console.log("点击了切换项目",label_id);
        });
      //重置
      $(".set-btn").on("click", function () {
        if(virAccountInfo){
          var $dom = $("#conditionform #apartId")
          $dom.val("").removeAttr('dep__id')
          _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});
        }
      });
      $("#saveFoodConfig").on("click", function () {
    	  console.log("点击了保存");
    	  _this.saveRenderTable();
//          if(virAccountInfo){
//            var $dom = $("#conditionform #apartId")
//            $dom.val("").removeAttr('dep__id')
//            _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 () {
        var tableData = [{
          name: '',
          orderNum: '',
          shortName: ''
        },{
          name: '',
          orderNum: '',
          shortName: ''
        },{
          name: '',
          orderNum: '',
          shortName: ''
        }]
        $("body").append(template.render(tpl.addTplCopy)({
          isAdmin: $("#isAdmin").val(),
          orgId: $("#conditionform #orgId").attr('org__id'),
          virAccountInfo: virAccountInfo,
          virId: $("#conditionform #companyId").attr("com__id")
        }));
        
        
        //执行渲染
        table.render({
          elem: '#demo'
          ,data:tableData
          ,cols: [[
            {field: 'name', title: '部门名称', width:150,event: 'setSign',edit: 'false'}
            ,{field: 'orderNum', title: '排序（选填）', width:150,event: 'setSign',edit: 'false'}
            ,{field: 'shortName', title: '部门简称（选填）', width:150,event: 'setSign',edit: 'false'}
            ,{
              title: '操作', 
              width:80,
              templet: function(data) {
              var str = '';
              str += '<button class="t-delete-btn" style="border:0;background:#fff;color:red;cursor:pointer" lay-event="del">删除</button>';
              return str;
            }}
          ]]
          ,done : function(res, curr, count){
            // console.log(res.data,111)
          }
        });
        table.on('edit(tableList)', function(obj){
	        var value = obj.value //得到修改后的值
	        var data = obj.data //得到所在行所有键值
	        var field = obj.field; //得到字段
	        layer.msg('[ID: '+ data.id +'] ' + field + ' 字段更改为：'+ value);
	  });
        //监听单元格编辑
        table.on('edit(demo)', function(obj){
          var value = obj.value //得到修改后的值
          ,data = obj.data //得到所在行所有键值
          // console.log(data,'data');
          if(obj.field == "name"){
            if(value.length>50){
              $(this).val(value.substring(0,50))
              data.name = value.substring(0,50)
              layer.msg("部门名称最多50个字符");
            }else{
              data.name = value
            }
            _this.isRepeatByDept(value,function(data){
              obj.value = ''
              data.name = ''
            })
          }
          if(obj.field == "orderNum"){
            if(!((/^[0-9]*$/g).test(value))){
              $(this).val(' ')
              data.orderNum = ''
              layer.msg("请输入数字");
            }else{
              data.orderNum = value
            }
          }
          if(obj.field == "shortName"){
            if(value.length>10){
              $(this).val(value.substring(0,10))
              data.shortName = value.substring(0,10)
              layer.msg("部门简称最多10个字符");
            }else{
              data.shortName = value
            }
          }
          tableData.forEach(function(item,index){
            if(obj.data.LAY_TABLE_INDEX == index){
              tableData[index].name = obj.data.name;
              tableData[index].orderNum = obj.data.orderNum;
              tableData[index].shortName = obj.data.shortName;
            }
          })
          console.log(tableData,'编辑完成')
        });
        $(".addBtn button").on("click",function() {
          console.log(tableData,'添加之前');
          tableData.push({
            name: '',
            orderNum: '',
            shortName: '' 
          })
          table.reload('demo',{
            data : tableData
          });
        });
        table.on('tool(demo)', function (obj) { //注：edit是固定事件名，test是table原始容器的属性 lay-filter="对应的值"       
          if (obj.event === 'del') {        
            // console.log(tableData,'deleteBefore')  
            var dataList = []
            obj.del();
            var arr = []
            tableData.forEach(function(item,index){
              dataList.push(item)
              if(obj.data.name == item.name){
                arr.push(index)
              }
            })
            dataList.splice(arr[0],1);
            tableData = dataList;
            // console.log(tableData,'deleteAfter')
          }else if(obj.event === 'setSign') {
//            if (!$(".dialog-wp #orgId").attr('org__id')) {
//              layer.msg("请选择项目");
//              $("td").data('edit', false)
//              return false;
//            }
//            if (!$(".dialog-wp #companyId").attr('com__id')) {
//              layer.msg("请选择企业名称");
//              $("td").data('edit', false)
//              return false;
//            }
            $("td[data-field='name']").data('edit', 'text')
            $("td[data-field='orderNum']").data('edit', 'number')
            $("td[data-field='shortName']").data('edit', 'text')
          }
        });
        //关闭弹窗
        $(".close-btn,.cancel-add-btn").on("click", function () {
          $(".dialog-wp").remove();
        });
        //确认添加
        $(".sure-add-btn").on("click", function () {
          // console.log(tableData,'表格数据')
          var deptListJson = []
          tableData.forEach(function(item,index){
            if(item.name != ''){
              deptListJson.push(item)
            }
          }) 
          // console.log(deptListJson,'deptListJson')        
          if (!$(".dialog-wp #orgId").attr('org__id')) {
            layer.msg("请选择项目");
            return false;
          }
          if (!$(".dialog-wp #companyId").attr('com__id')) {
            layer.msg("请选择企业名称");
            return false;
          }
          // if (!$(".dialog-wp #apartId").val()) {
          //   layer.msg("请选择部门名称");
          //   return false;
          // }
          _this.submitAdd(JSON.stringify(deptListJson),function () {
            $(".dialog-wp").remove();
            _this.againRenderTable();
          });
        });
      });
      //下载模板
			$("#importTemplate").on("click", function () {
				location.href = $("#contextPath").val() + "/upload/DeptInfo.xlsx";
      });
      //多项目
			$(".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.search_fuzzy()
    },
    getFoodCardList:function () {
    	layui.use(['layer', 'form', 'table', 'layedit', 'laydate', 'jquery'], function () {
    	        var form = layui.form,
    	            laydate = layui.laydate,
    	            layer = layui.layer,
    	            $ = layui.jquery;
    	//页面打开时异步加载数据,查询信道
    	        $(function () {
    	           $.ajax({
    	               type: "POST",
    	               url:  $("#contextPath").val() + "/virtfood/managerList",
    	               data: {
    	            	   page:1,
    	            	   limit:9999,
    	    	          },
    	               success: function (data) {
    	                   $("#sendQueueChannel").html("<option value=''>请选择卡组</option>");
    	                  let comArr = "";
    	               $.each(data.data, function (index, item) {
    	               	 console.log(item, 222222222);
    	                 comArr += "<option value='" + item.id + "'>" + item.food_name + "</option>"
    	               })
    	               $("#sendQueueChannel").append(comArr);
    	               },error: function () {
    	               }
    	           })
    	        });
    	});

    },
    initData:function () {
    	layui.use('table', function(){
    		  var table = layui.table;
    		  //展示已知数据
    		  table.render({
    		    elem: '#tableList',
    		    url: $("#contextPath").val() + "/virtfood/getconfig",
    	          method: "post",
    	          where: {
    	        	food_id:1,
    	          }
    		    ,cols: [[ //标题栏
    		      {field: 'id', title: '序号', width: 80, sort: true,}
    		      ,{field: 'username', title: '用户名', width: 120,edit:'text'}
    		      ,{field: 'email', title: '邮箱', minWidth: 150,edit:'text'}
    		      ,{field: 'sign', title: '签名', minWidth: 160,edit:'text'}
    		    ]]
    		    ,page: true
    		    ,response: {
    		        statusCode: 200 //重新规定成功的状态码为 200，table 组件默认为 0
    		      }
    	          ,parseData: function(res){ //将原始数据解析成 table 组件所规定的数据
    	        	  console.log("res",res)
//    	              return {
//    	                "code": res.status, //解析接口状态
//    	                "msg": res.message, //解析提示文本
//    	                "data": res.rows.item //解析数据列表
//    	              };
    	            }
    		    ,even: true
    		  
    		  });
    		});
    	 
    },
    // 模糊搜索项目
    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:'/virtfood/managerList',
        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#companyId',
        dep_target:'.default-select#apartId',
      });
      var option_2 = $.extend(true,{},default_option,{
        org_target:'.pop-select#orgId',
        com_target:'.pop-select#companyId',
      });
      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 () {
      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() + "/admin/dept/deptList",
          method: "post",
          where: {
            orgId: $("#conditionform #orgId").attr('org__id'),
            virId: $("#conditionform #companyId").attr("com__id")
          },
          skin: 'nob' //行边框风格
            ,
          even: true //开启隔行背景
            ,
          size: 'lg' //小尺寸的表格
            ,
          cols: [
            [{
              field: 'index',
              title: '序号',
              width: '80',
              templet: '#indexTpl'
            }, {
              field: 'orderNum',
              title: '排序',
              width: 120
            }, {
              field: 'orgName',
              title: '项目',
              width: 200
            }, {
              field: 'virName',
              title: '公司名称',
              minWidth: 200
            }, {
              field: 'deptName',
              title: '部门',
              minWidth: 200
            }, {
              field: 'shortName',
              title: '简称',
              width: 120
            }, {
              field: 'creatorName',
              title: '创建人',
              minWidth: 120
            }, {
              field: 'createTime',
              title: '创建时间',
              width: 200
            }, {
              title: '操作',
              fixed: 'right',
              width: 120,
              align: 'center',
              templet: function (data) {
                var str = "<div class='operate'>";
                str += "<span class='op_edit_btn' lay-event='edit' data-id='"+data.deptId+"'><i class='edit'></i><i class='op_hover'>修改</i></span>";
                str += "<span class='op_del_btn' lay-event='del' data-id='"+data.deptId+"'><i class='delete'></i><i class='op_hover'>删除</i></span>";
                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);
                })
              });
            });
          }
        });
        //查询
        $('.search-btn').on('click', function () {
        var cardId=$('#sendQueueChannel').val();
        console.log("cardId",cardId);
          _this.againRenderTable(cardId);
        });
        
      //上传图片第一个
		$(".r-img-file").on("change",function(){
			var $this = $(this);
			var fileName=document.getElementsByClassName("r-img-file")[0].value;  
		    var suffixIndex=fileName.lastIndexOf(".");  
		    var suffix=fileName.substring(suffixIndex+1).toUpperCase();  
		    if(suffix!="BMP"&&suffix!="JPG"&&suffix!="JPEG"&&suffix!="PNG"&&suffix!="GIF"){  
		     layer.alert( "请上传图片（格式BMP、JPG、JPEG、PNG等）!");  
		     return false;
		    }  
			$(".r-item-img-list").append(tpl.imgTpl);
			$(".r-img-file-wp").css('display', 'none');
			_this.selectFileImage($(".r-img-file"),$(".r-item-img-wp").eq($(".r-item-img-wp").length-1).find(".r-item-img"),function(base64){
				$(".r-item-del-btn").on("click",function(){
					$(this).closest(".r-item-img-wp").remove();
					$(".r-img-file-wp").css('display', 'block');
				})
				
				_this.ajaxUploadImg("1",base64,$this.closest(".r-img-file"))
			})
		})
		//第二个
			$(".r-img-file1").on("change",function(){
			var $this = $(this);
			var fileName=document.getElementsByClassName("r-img-file1")[0].value;  
		    var suffixIndex=fileName.lastIndexOf(".");  
		    var suffix=fileName.substring(suffixIndex+1).toUpperCase();  
		    if(suffix!="BMP"&&suffix!="JPG"&&suffix!="JPEG"&&suffix!="PNG"&&suffix!="GIF"){  
		     layer.alert( "请上传图片（格式BMP、JPG、JPEG、PNG等）!");  
		     return false;
		    }  
			$(".r-item-img-list1").append(tpl.imgTpl1);
			$(".r-img-file-wp1").css('display', 'none');
			_this.selectFileImage($(".r-img-file1"),$(".r-item-img-wp1").eq($(".r-item-img-wp1").length-1).find(".r-item-img1"),function(base64){
				$(".r-item-del-btn1").on("click",function(){
					$(this).closest(".r-item-img-wp1").remove();
					$(".r-img-file-wp1").css('display', 'block');
				})
				_this.ajaxUploadImg("2",base64,$this.closest(".r-img-file1"))
			})
		})
		//第三个
			$(".r-img-file2").on("change",function(){
			var $this = $(this);
			var fileName=document.getElementsByClassName("r-img-file2")[0].value;  
		    var suffixIndex=fileName.lastIndexOf(".");  
		    var suffix=fileName.substring(suffixIndex+1).toUpperCase();  
		    if(suffix!="BMP"&&suffix!="JPG"&&suffix!="JPEG"&&suffix!="PNG"&&suffix!="GIF"){  
		     layer.alert( "请上传图片（格式BMP、JPG、JPEG、PNG等）!");  
		     return false;
		    }  
			$(".r-item-img-list2").append(tpl.imgTpl2);
			$(".r-img-file-wp2").css('display', 'none');
			_this.selectFileImage($(".r-img-file2"),$(".r-item-img-wp2").eq($(".r-item-img-wp2").length-1).find(".r-item-img2"),function(base64){
				$(".r-item-del-btn2").on("click",function(){
					$(this).closest(".r-item-img-wp2").remove();
					$(".r-img-file-wp2").css('display', 'block');
				})
				
				_this.ajaxUploadImg("3",base64,$this.closest(".r-img-file2"))
			})
		})
		//第四个
			$(".r-img-file3").on("change",function(){
			var $this = $(this);
			var fileName=document.getElementsByClassName("r-img-file3")[0].value;  
		    var suffixIndex=fileName.lastIndexOf(".");  
		    var suffix=fileName.substring(suffixIndex+1).toUpperCase();  
		    if(suffix!="BMP"&&suffix!="JPG"&&suffix!="JPEG"&&suffix!="PNG"&&suffix!="GIF"){  
		     layer.alert( "请上传图片（格式BMP、JPG、JPEG、PNG等）!");  
		     return false;
		    }  
			$(".r-item-img-list3").append(tpl.imgTpl3);
			$(".r-img-file-wp3").css('display', 'none');
			_this.selectFileImage($(".r-img-file3"),$(".r-item-img-wp3").eq($(".r-item-img-wp3").length-1).find(".r-item-img3"),function(base64){
				$(".r-item-del-btn3").on("click",function(){
					$(this).closest(".r-item-img-wp3").remove();
					$(".r-img-file-wp3").css('display', 'block');
				})
				_this.ajaxUploadImg("4",base64,$this.closest(".r-img-file3"))
			})
		})
		
		      $(".imgdel-btn1").on("click",function(){
		    	  $(".repair-item-img").css('display', 'none');
   		          $(".repair-item").css('display', 'block');
				})
				$(".imgdel-btn2").on("click",function(){
					$(".repair-item-img2").css('display', 'none');
	   		          $(".repair-item2").css('display', 'block');
				})
				$(".imgdel-btn3").on("click",function(){
					$(".repair-item-img3").css('display', 'none');
	   		          $(".repair-item3").css('display', 'block');
				})
				$(".imgdel-btn4").on("click",function(){
					$(".repair-item-img4").css('display', 'none');
	   		          $(".repair-item4").css('display', 'block');
				})
      });
    },
    /**
	 * 上传图片
	 * @param base64
	 * @param $$item
	 */
	ajaxUploadImg: function(type,base64,$item){
		var _this = this;
		 $.ajax({
			   type: "post",
			   url: $("#contextPath").val()+ "/admin/virtual/getAttMagePath", 
			   data: {
				   "serviceIcon": base64
			   },
			   success: function(data){
				   var result = JSON.parse(data);
				   if(result.code == '200'){
					   if(type=='1'){
						   logo1=result.data.preview
					   }else if(type=='2'){
						   logo2=result.data.preview
					   }else if(type=='3'){
						   logo3=result.data.preview
					   }else if(type=='4'){
						   logo4=result.data.preview
					   }
					   console.log("logo1",logo1);
					   $item.find("#business").data("img",result.data.path);
				   	   $item.addClass("no-active");	
//					   $("#conditionform").submit();
				   }   
			   },
			   error: function(){   
			   }
		   });
	},
    /**
	 * 上传图片
	 * @param $dom 上传按钮
	 * @param $imgWp 图片容器
	 * @param $base64Wp 存放base64得input
	 * @param callback 回调
	 */
	selectFileImage:function ($dom,$imgWp,callback) {
		
		var file = $dom[0].files[0];
		var Orientation = null;
		$dom.val("");//上传传按钮
		
		$imgWp.closest(".r-item-img-wp").data("file",file)
		if (file) {
			console.log("正在上传,请稍后...",file);
//			var rFilter = /^(image\/jpeg|image\/png)$/i; // 检查图片格式
//			if (!rFilter.test(file.type)) {
//				layer.msg('图片格式有误，请上传(jpeg,png)');
//				return;
//			}
			EXIF.getData(file, function() {
				EXIF.getAllTags(this);
				Orientation = EXIF.getTag(this, 'Orientation');
			});

			var oReader = new FileReader();
			oReader.onload = function(e) {
				var image = new Image();
				image.src = e.target.result;
				image.onload = function() {
					var expectWidth = this.naturalWidth;
					var expectHeight = this.naturalHeight;

					if (this.naturalWidth > this.naturalHeight
							&& this.naturalWidth > 800) {
						expectWidth = 800;
						expectHeight = expectWidth * this.naturalHeight
								/ this.naturalWidth;
					} else if (this.naturalHeight > this.naturalWidth
							&& this.naturalHeight > 1200) {
						expectHeight = 1200;
						expectWidth = expectHeight * this.naturalWidth
								/ this.naturalHeight;
					}
					var canvas = document.createElement("canvas");
					var ctx = canvas.getContext("2d");
					canvas.width = expectWidth;
					canvas.height = expectHeight;
					ctx.drawImage(this, 0, 0, expectWidth, expectHeight);
					var base64 = null;
					var clearBase64 = null;
					base64 = canvas.toDataURL("image/png", 2);
					if (base64 != null) {
						clearBase64 = base64.substr(base64.indexOf(',') + 1)
					}
					$imgWp.html("<img src='"+base64+"' alt='' />");//图片容器
//					$base64Wp.val(clearBase64);//存放base64得
					callback(base64);
				};
			};
			oReader.readAsDataURL(file);
		}
	},
    
    /**
     * 删除模板
     * @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() + "/admin/dept/delDept",
          data: {
            id: id
          },
          success: function (data) {
            if (data.code == 200) {
              callback();
            } else {
              layer.msg(data.msg)
            }
          },
          error: function () {
            // layer.msg('系统繁忙...')
          }
        });
      }, function (index) {

      });
    },
   // 保存数据
    saveRenderTable:function(){
 	   var _this = this;
 	   if(!$('#sendQueueChannel').val()){
 		  layer.msg('请选择卡组')
	    	 return  
 	   }
 	    if(!$('input[name="merchant_name1"]').val()){
 	    	 layer.msg('请填写完整信息')
 	    	 return
 	    }
 	   if(!$('input[name="merchant_name2"]').val()){
	    	 layer.msg('请填写完整信息')
	    	 return
	    }
 	  if(!$('input[name="merchant_name3"]').val()){
	    	 layer.msg('请填写完整信息')
	    	 return
	    }
 	 if(!$('input[name="merchant_name4"]').val()){
	    	 layer.msg('请填写完整信息')
	    	 return
	    }
 	if(!$('input[name="discount1"]').val()){
    	 layer.msg('请填写完整信息')
    	 return
    }
 	if(!$('input[name="discount2"]').val()){
    	 layer.msg('请填写完整信息')
    	 return
    }
 	if(!$('input[name="discount3"]').val()){
    	 layer.msg('请填写完整信息')
    	 return
    }
 	if(!$('input[name="discount4"]').val()){
    	 layer.msg('请填写完整信息')
    	 return
    }
	      $.ajax({
	        type: "post",
	        url: contextPath + "/virtfood/configsave",
	        data: {
	        	food_id: $('#sendQueueChannel').val(),
	        	merchant_name1:$('input[name="merchant_name1"]').val(),
	        	merchant_name2:$('input[name="merchant_name2"]').val(),
	        	merchant_name3:$('input[name="merchant_name3"]').val(),
	        	merchant_name4:$('input[name="merchant_name4"]').val(),
	        	discount1:$('input[name="discount1"]').val(),
	        	discount2:$('input[name="discount2"]').val(),
	        	discount3:$('input[name="discount3"]').val(),
	        	discount4:$('input[name="discount4"]').val(),
	        	logo1:logo1,
	        	logo2:logo2,
	        	logo3:logo3,
	        	logo4:logo4,
	        	out_url:$('input[name="out_url"]').val(),
	        },
	        success: function (data) {
	          if (data.code == ERROK) {
	        	  let dataList=data.data
	        	  layer.msg('保存成功')
	        	  console.log("dataList",dataList);
	          } else {
	            layer.msg(data.msg)
	          }
	        },
	        error: function (error) {
	          layer.msg('error')
	        }
	      });
    },
    /*重新渲染table*/
    againRenderTable: function (id) {
    	   var _this = this;
    	      $.ajax({
    	        type: "post",
    	        url: contextPath + "/virtfood/getconfig",
    	        data: {
    	        	food_id: id
    	        },
    	        success: function (data) {
    	          if (data.code == ERROK) {
    	        	  let dataList=data.data
    	        	  console.log("dataList",dataList);
    	        	  if(dataList){
    	        		  $("#out_url").val(dataList.out_url)
    	        		   $("#merchant_name1").val(dataList.merchant_name1)
    	        		    $("#merchant_name2").val(dataList.merchant_name2)
    	        		     $("#merchant_name3").val(dataList.merchant_name3)
    	        		      $("#merchant_name4").val(dataList.merchant_name4)
    	        		       $("#discount1").val(dataList.discount1)
    	        		        $("#discount2").val(dataList.discount2)
    	        		         $("#discount3").val(dataList.discount3)
    	        		          $("#discount4").val(dataList.discount4)
    	        		          
    	        		          
    	        		         if(dataList.logo1){
    	        		          $(".repair-item-img").css('display', 'block');
       	        		          $(".repair-item").css('display', 'none');
       	        		          $('#firstImgUrl').attr("src", dataList.logo1)	 
    	        		         }else{
    	        		          $(".repair-item-img").css('display', 'none');
       	        		          $(".repair-item").css('display', 'block');
    	        		          }
		    	        		   if(dataList.logo2){
			        		          $(".repair-item-img2").css('display', 'block');
		   	        		          $(".repair-item2").css('display', 'none');
		   	        		          $('#twoImgUrl').attr("src", dataList.logo2)	 
			        		         }else{
			        		          $(".repair-item-img2").css('display', 'none');
		   	        		          $(".repair-item2").css('display', 'block');
			        		          }
		    	        		  if(dataList.logo3){
			        		          $(".repair-item-img3").css('display', 'block');
		   	        		          $(".repair-item3").css('display', 'none');
		   	        		          $('#threeImgUrl').attr("src", dataList.logo3)	 
			        		         }else{
			        		          $(".repair-item-img3").css('display', 'none');
		   	        		          $(".repair-item3").css('display', 'block');
			        		          }
		    	        		  if(dataList.logo4){
			        		          $(".repair-item-img4").css('display', 'block');
		   	        		          $(".repair-item4").css('display', 'none');
		   	        		          $('#fourImgUrl').attr("src", dataList.logo4)	 
			        		         }else{
			        		          $(".repair-item-img4").css('display', 'none');
		   	        		          $(".repair-item4").css('display', 'block');
						        	}
			    	        	  }else{
			    	        	$("#out_url").val("")
			   	        		   $("#merchant_name1").val("")
			   	        		    $("#merchant_name2").val("")
			   	        		     $("#merchant_name3").val("")
			   	        		      $("#merchant_name4").val("")
			   	        		       $("#discount1").val("")
			   	        		        $("#discount2").val("")
			   	        		         $("#discount3").val("")
			   	        		          $("#discount4").val("")
			   	        		  $(".repair-item-img").css('display', 'none');
     	        		          $(".repair-item").css('display', 'block');
     	        		          $(".repair-item-img2").css('display', 'none');
	   	        		          $(".repair-item2").css('display', 'block');
	   	        		          $(".repair-item-img3").css('display', 'none');
	   	        		          $(".repair-item3").css('display', 'block');
	   	        		          $(".repair-item-img4").css('display', 'none');
	   	        		          $(".repair-item4").css('display', 'block');
			    	        	  }
			    	          } else {
			    	            layer.msg(data.msg)
			    	          }
			    	        },
			    	        error: function (error) {
			    	          layer.msg('error')
			    	        }
			    	      });
                           },
    /**
     * 请求详情
     * @param id
     * @param callback
     */
    ajaxDetail: function (id, callback) {
      var _this = this;
      $.ajax({
        type: "post",
        url: contextPath + "/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();
})