<template>  
  <div class="mcTable">
      <div class="tableCon"></div>
      <div class="noDataModal" v-show="noData">
        <div><span><img src="../../assets/img/nodata.png"><br>{{tips}}</span></div>
      </div>
      <div class="loadingCon" v-show="isLoading">
        <div><span><i class="mc-icon-loading"></i><br>正在加载中，请稍后...</span></div>
      </div>
      <ul class="filterList" v-show="isShowFilter">
        <li v-for="(item,index) in filterListData" v-bind:class="{ active: index == filterLisActive}" v-on:click="changeFilter(index)">
        {{ item.label }}
        </li>
      </ul>
  </div> 
</template>


<script>    
  import handsontable from "handsontable"; 
  import PopperMixin from '../../assets/js/PopperMixin_table';

  export default {
    mixins: [PopperMixin],
    name:'mcTable',
    props: {
      tableData: {
        type: Array,
        default: function(){
          return [];
        }
      },
      columns: {
        type: Array,
        default: function(){
          return [];
        }
      },
      mergeCells: {
        type: Array,
        default: function(){
          return [];
        }
      },
      colWidths:{
        type: Array,
        default: function(){
          return [];
        }
      },
      stripe: {
        type: Boolean,
        default: false
      },
      renderAllRows: {
        type: Boolean,
        default: false
      },
      fixedRowsTop: {
        type: Number,
        default: 0
      },
      fixedColumnsLeft: {
        type: Number,
        default: 0
      },
      theadRow: {
        type: Number,
        default: 1
      },
      stretchH: {
        type: String,
        default: "all"
      },
      tips: {
        type: String,
        default: "暂无数据"
      },
      usePopper:{
        type: Boolean,
        default: false
      },
      manualColumnResize:{
        type: Boolean,
        default: false
      },
      contextMenu:{
        default: false
      },
      tableId:{
        type: String,
        default: ""
      }
    },
    watch: {
      tableData: function(){
        this.mountedFn();  
      }
    },
    mounted: function() {
      var vueObj = this;
      vueObj.$nextTick(function(){
        vueObj.mountedFn();   
      });
    },
    data() {
      return {
        grid: "",
        noData: false,
        isLoading: false,
        tableColumns: '',
        tableColWidths: [],
        tableRemouldData: [],   //格式处理后的数据
        viewList: [],           //用来显示的数据
        collapseID: {},         //折叠的ID
        hideID: {},             //隐藏的ID
        checkedID: {},          //选中的ID
        indeterminateID:{},     //不确定的ID 
        sortCol: {},            //排序的列 
        filterCol: {},          //筛选的列  
        isShowFilter: false,    //是否显示筛选列表
        filterListData: [],     //筛选列表数据
        filterLisActive: 0,     //筛选列表选中下标
        sortE: {},              //排序点击对象e
        filterE: {},            //筛选点击对象e
        filterListState: {},    //筛选列表的状态（是否显示）
        sortData: [],           //排序后的数据
        filterData: [],         //筛选后的数据
        manualColumnResizerTimer: '',  //手动改变列宽定时器
        manualColumnResizerStart: '',  //手动改变列宽开始位置
        tdMinWidth: 24,         //td最小宽度
        isShowSelect: false,    //是否显示下拉
      };
    },
    methods: {
      mountedFn: function(){
        var vueObj = this;
        vueObj.tableRemouldData = vueObj.remouldNodes(vueObj.tableData);  //处理数据
        vueObj.viewList = vueObj.objDeepCopy(vueObj.tableRemouldData);
        vueObj.tableColumns = vueObj.objDeepCopy(vueObj.columns);
        vueObj.tableColWidths = vueObj.getColWidths();
        vueObj.buildTable();
        vueObj.setStripe();
        vueObj.bindScroll();
        vueObj.bindDocumentClick(); 
        vueObj.checkManualColResize();
        vueObj.stopHeadContextMenu();    //阻止头部右键事件

        var el = vueObj.$el.getElementsByClassName("ht_master")[0].getElementsByClassName("wtHolder")[0];
        el.onscroll = function(){
          var selectOptionsLen = document.getElementsByClassName("selectOptions").length;
          if(selectOptionsLen > 0){
            document.getElementsByClassName("selectOptions")[0].style.display = 'none';
          } 
        }
        vueObj.listenScroll();    //监听scroll
      },
      buildTable: function(){
        var vueObj = this;
        if(vueObj.grid){
          console.log("destroy");
          vueObj.grid.destroy();
        }
        // vueObj.createAssistDom();   //创建协助Dom
        console.log("buildTable");
        var tableObj = vueObj.$el.getElementsByClassName("tableCon")[0];
        vueObj.grid = new handsontable(tableObj, {
          data: vueObj.viewList,
          columns: vueObj.tableColumns,
          mergeCells: vueObj.mergeCells,
          colWidths: vueObj.colWidths || vueObj.tableColWidths,
          rowHeaders: true,
          rowHeaderWidth: ((!!window.ActiveXObject || "ActiveXObject" in window)&&vueObj.fixedColLeft>0) ? 3 : 0,
          colHeaders: false,
          fixedRowsTop: vueObj.fixedRowsTop,
          fixedColumnsLeft: vueObj.fixedColumnsLeft,
          renderAllRows: vueObj.renderAllRows,
          stretchH: vueObj.stretchH,
          currentRowClassName: 'currentRow',
          manualColumnResize: vueObj.manualColumnResize,
          manualRowResize:false,
          outsideClickDeselects: false,
          fillHandle: false,    
          cells: vueObj.getProp,
          viewportColumnRenderingOffset: 500,
          afterGetRowHeader: vueObj.setTrColor,
          contextMenu: vueObj.contextMenu,
          rowHeights: 35, 
          // autoRowSize: true,
          // renderAllRows: true
          
        });

        //判断是否有数据
        var dataLen = vueObj.tableData.length;
        if(dataLen <= vueObj.theadRow ){
          vueObj.noData = true;
          if(dataLen == vueObj.theadRow){
            var tableW = vueObj.$el.offsetWidth;
            var headObj = vueObj.$el.getElementsByClassName("ht_clone_top")[0].getElementsByClassName("wtHider")[0];
            var headW = headObj.offsetWidth;
            var headH = headObj.offsetHeight;
            var top = headH;
            var bottom = 0;
            if(headW > tableW){
              bottom = 12;
            }
            var modalObj = vueObj.$el.getElementsByClassName("noDataModal")[0];
            modalObj.style.top = top + "px";
            modalObj.style.bottom = bottom + "px";
          }  
        }else{
          vueObj.noData = false;
        }

        vueObj.grid.addHook('afterRender', function(){
          console.log("afterRender");
          vueObj.setStripe();
        });

        vueObj.grid.addHook('afterChange', function(changes, source){
          if(changes){
            changes.forEach(function(change){
              if(change[2]!==change[3] && change[2]){               
                vueObj.$emit('after-change', changes);
                var row = change[0];
                var prop = change[1];
                var changeID = vueObj.viewList[row].id;
                vueObj.updateTableRemouldData(changeID, prop, change[3]);    //当显示数据发生改变时，对原始数据也进行改变
              }              
            });                  
          };
        });

        vueObj.grid.addHook('afterSelectionEnd', function(r, c, r2, c2){ 
          var top=Math.min(r, r2);       
          if(top < vueObj.theadRow){              
            //清除选中单元格
            vueObj.grid.deselectCell();
          }            
        });

        // 添加表格中的事件代理
        // vueObj.addEvent();
      },
      setStripe: function(){   //设置斑马条纹
        var vueObj = this;
        var isShowStripe = vueObj.stripe;
        if(isShowStripe){
          var masterObj = vueObj.$el.getElementsByClassName("ht_master")[0];
          var cloneLeftObj = vueObj.$el.getElementsByClassName("ht_clone_left")[0];
          var trArr1 = masterObj.getElementsByTagName("tbody")[0].getElementsByTagName("tr");
          var trArr2 = cloneLeftObj.getElementsByTagName("tbody")[0].getElementsByTagName("tr");
          var trArr2Len= trArr2.length;
          var num = vueObj.theadRow % 2 == 0 ? 0 : 1;
          for(var i=0; i< trArr1.length; i++){
            if(i%2 != num){
              trArr1[i].setAttribute("class", "trStripe");
              if(trArr2Len > 0){
                trArr2[i].setAttribute("class", "trStripe");
              }
            }
          }
        }
      },
      getProp: function (row, col, prop){
        var cellProperties = {};
        if(row < this.theadRow){       
          cellProperties.readOnly = true;
          cellProperties.className = 'htCenter htMiddle theadBg';
        }else{
          cellProperties.readOnly = this.tableColumns[col] ? this.tableColumns[col].readOnly || false : false;
          cellProperties.className = this.tableColumns[col] ? this.tableColumns[col].align || "" : "";
        }

        //匹配渲染器
        if(this.tableColumns[col]){
          var rendererName = this.tableColumns[col].rendererName || '';
          var isCustomRender = this.tableColumns[col].isCustomRender || false;
          if(rendererName){
            if(row >= this.theadRow){
              if(isCustomRender){  
                cellProperties.renderer = this.customRender;
                // cellProperties.renderer = this.$emit(rendererName);
              }else if(rendererName === "aLink"){
                cellProperties.renderer = this.aLinkRenderer;
                cellProperties.readOnly = true;
              }else if(rendererName === "aBtn"){
                cellProperties.renderer = this.aBtnRenderer;
                cellProperties.readOnly = true;
              }else if(rendererName === "switchBtn"){
                cellProperties.renderer = this.switchBtnRenderer;
                cellProperties.readOnly = true;
              }else if(rendererName === "popperBtn"){
                cellProperties.renderer = this.popperBtnRenderer;
                cellProperties.readOnly = true;
              }else if(rendererName === "colTree"){
                cellProperties.renderer = this.colTreeRenderer;
                cellProperties.readOnly = true;
                cellProperties.className = 'htLeft htMiddle';
              }else if(rendererName === "checkboxBtn"){
                cellProperties.renderer = this.checkboxRenderer;
                cellProperties.readOnly = true;
              }else if(rendererName === "select"){
                cellProperties.renderer = this.selectRenderer;
                cellProperties.readOnly = true;
              }else if(rendererName === "cornerMark"){
                cellProperties.renderer = this.cornerMarkRenderer;
              }
            }
          }
          //thead排序渲染
          var isSort = this.tableColumns[col].isSort || '';
          var isFilter = this.tableColumns[col].isFilter || '';
          if(isSort || isFilter){
            if(row < this.theadRow && row == this.tableColumns[col].sortRow){  //只设置表头
              cellProperties.renderer = this.headRenderer;
              cellProperties.readOnly = true;
            }
          }
        }
        return cellProperties;
      },
      setFontSize: function(size){   //设置字体大小
        var vueObj = this;
        var className = vueObj.$el.getAttribute("class");  
        var index = className.indexOf("font");
        var newClassName;
        if(index >= 0){
          newClassName = className.substring(0, index) + "font" + size;
        }else{
          newClassName = className + " font" + size;
        }
        vueObj.$el.setAttribute("class", newClassName);
        vueObj.grid.render();
      },
      setCol: function(col){
        var vueObj = this;
        vueObj.tableColumns = col;
        vueObj.tableColWidths = vueObj.getColWidths();
        vueObj.grid.updateSettings({"columns": vueObj.tableColumns,"colWidths": vueObj.tableColWidths});
        vueObj.grid.render();
      },
      aLinkRenderer: function(instance, td, row, col, prop, value, cellProperties){
        handsontable.renderers.TextRenderer.apply(this, arguments);
        var eventName = this.tableColumns[col].eventName;
        var html = '<a class="aLink" func="'+ eventName +'" row="'+ row +'" col="'+ col +'" prop="'+ prop +'">'+ value +'</a>';
        td.innerHTML = html;
        this.addEvent(td,"a","click", this.eventManager);
        return td;
      },
      aBtnRenderer: function(instance, td, row, col, prop, value, cellProperties){
          handsontable.renderers.TextRenderer.apply(this, arguments);
          var eventName = this.tableColumns[col].eventName;
          var html = '<a class="aBtn" func="'+ eventName +'" row="'+ row +'" col="'+ col +'" prop="'+ prop +'">'+ value +'</a>';
          td.innerHTML = html;
          this.addEvent(td,"a","click", this.eventManager);
          return td;
      },
      switchBtnRenderer: function(instance, td, row, col, prop, value, cellProperties){
          handsontable.renderers.TextRenderer.apply(this, arguments);
          var eventName = this.tableColumns[col].eventName;
          var iconClassName;
          if(value == "off"){
            iconClassName = "mc-icon-turn-off";
          }else{
            iconClassName = "mc-icon-turn-on";
          }
          var html = '<a class="switchBtn '+ iconClassName +'" func="'+ eventName +'" row="'+ row +'" col="'+ col +'" prop="'+ prop +'"></a>';
          td.innerHTML = html;
          this.addEvent(td,"a","click", this.eventManager);
          return td;
      },
      popperBtnRenderer: function(instance, td, row, col, prop, value, cellProperties){
          handsontable.renderers.TextRenderer.apply(this, arguments);
          var eventName = this.tableColumns[col].eventName;
          var html = '<a class="aPopper clickBtn" func="'+ eventName +'" row="'+ row +'" col="'+ col +'" prop="'+ prop +'">'+ value +'</a>';
          td.innerHTML = html;
          this.addEvent(td,"a","click", this.eventManager);
          return td;
      },
      checkboxRenderer: function(instance, td, row, col, prop, value, cellProperties){
          handsontable.renderers.TextRenderer.apply(this, arguments);
          var eventName = 'changeCheckbox';
          var checkedHtml = "";
          if(value){
            checkedHtml = 'checked = true';
          }
          var html = '<input type="checkbox" class="checkboxRender" func="'+ eventName +'" row="'+ row +'" col="'+ col +'" prop="'+ prop +'"'+ checkedHtml +'>';
          td.innerHTML = html;
          this.addEvent(td,"input","click", this.eventManager, {'myselfFn':true});
          return td;
      },
      colTreeRenderer: function(instance, td, row, col, prop, value, cellProperties){
          handsontable.renderers.TextRenderer.apply(this, arguments);
          var eventName = 'foldTr';
          var record = this.viewList[row];
          var enableCheckbox = this.tableColumns[col].enableCheckbox;
          var className;

          if(record.childCount && record.childCount > 0){
            className = (this.collapseID[record.id] ? 'mc-icon-triangle-right ' : 'mc-icon-triangle-down ') + ' levelIcon level' + record.level;
          }else{
            className = ' levelIcon level' + record.level;
          }
          
          value = value || ' ';
          var checkboxHtml = "";
          if(enableCheckbox){
            var checkedHtml = this.checkedID[record.id] ? 'checked="checked"' : '';
            checkboxHtml = '<input type="checkbox" class="colTreeCheckbox colTreeCheckbox_'+ record.id +'" '+ checkedHtml +' row="'+ record.rowNo +'">';
          }
          var html = '<i class="'+ className +'" func="'+ eventName +'" row="'+ record.rowNo +'" col="'+ col +'" prop="'+ prop +'"></i>'+ checkboxHtml + value;
          td.innerHTML = html;
          this.addEvent(td,"i","click", this.eventManager, {'myselfFn':true});
          if(enableCheckbox){
            if(this.indeterminateID[record.id]){
              td.getElementsByTagName("input")[0].indeterminate = true;
              td.getElementsByTagName("input")[0].setAttribute('isindeterminate','true');
            }
            this.addEvent(td,"input","change", this.checkIndeterminate);
          }
          return td;
      },
      headRenderer: function(instance, td, row, col, prop, value, cellProperties){   //表头排序渲染器
          handsontable.renderers.TextRenderer.apply(this, arguments);
          var isSort = this.tableColumns[col].isSort || '';
          var isFilter = this.tableColumns[col].isFilter || '';
          var btnHtml = '';
          var eventName = 'tableHeadClick';
          var sortType = '';
          var filterRule = '';
          if(isSort){   //排序
            var srotState = this.sortCol[col] || "";
            var iconHtml = '<i class="mc-icon-triangle-up" func="'+ eventName +'"></i><i class="mc-icon-triangle-down" func="'+ eventName +'"></i>';
            if(srotState == "up"){
              iconHtml = '<i class="mc-icon-triangle-up active" func="'+ eventName +'"></i><i class="mc-icon-triangle-down" func="'+ eventName +'"></i>';
            }else if(srotState == "down"){
              iconHtml = '<i class="mc-icon-triangle-up" func="'+ eventName +'"></i><i class="mc-icon-triangle-down active" func="'+ eventName +'"></i>';
            }
            btnHtml = '<span class="tableSort" row="'+ row +'" col="'+ col +'" prop="'+ prop +'">'
                        + iconHtml
                      +'</span>';
            sortType = this.tableColumns[col].sortType;
          }
          if(isFilter){   //筛选
            var filterState = this.filterCol[col] || "";
            var activeHtml = "";
            if(filterState){
              activeHtml = " active"
            }
            var iconHtml = '<span class="tableFilter"><i class="mc-icon-filtrate'+ activeHtml +'" func="'+ eventName +'"></i></span>';
            btnHtml = btnHtml + iconHtml;
            filterRule = this.tableColumns[col].filterRule;
          }
          var html =  '<span class="tableHeadTd">' + value + '</span>' + btnHtml;
          td.innerHTML = html; 
          this.addEvent(td,"i","click", this.eventManager, {'myselfFn':true, 'row':row, 'col':col, 'prop':prop, 'sortType':sortType, 'filterRule':filterRule});
          return td;
      },
      selectRenderer: function(instance, td, row, col, prop, value, cellProperties){   //下拉渲染
        var options = this.tableColumns[col].options;
        var isMultiple = this.tableColumns[col].isMultiple || '';
        var isEdit = this.tableColumns[col].isEdit || '';
        var eventName = 'showOptions';
        var htmlStr;
        htmlStr = '<div class="htAutocomplete current highlight" row="'+ row +'" col="'+ col +'" prop="'+ prop +'" value="'+ value +'">'+ value +'<i class="mc-icon-arrow-down" func="'+ eventName +'" row="'+ row +'" col="'+ col +'" prop="'+ prop +'"></i></div>';
        td.innerHTML = htmlStr; 
        this.addEvent(td,"i","click", this.eventManager, {'myselfFn':true, 'options':options, isMultiple});
        return td;
      },
      cornerMarkRenderer: function(instance, td, row, col, prop, value, cellProperties){   //角标渲染
        var eventName = this.tableColumns[col].eventName;
        var html = value + '<i func="'+ eventName +'" row="'+ row +'" col="'+ col +'" prop="'+ prop +'" class="triangle_topright">';
        td.innerHTML = html;
        td.style.position = 'relative';
        this.addEvent(td,"i","click", this.eventManager);
        return td;
      },
      customRender: function(instance, td, row, col, prop, value, cellProperties){   //自定义渲染器
      var rendererName = this.tableColumns[col].rendererName || '';
        this.$emit(rendererName, instance, td, row, col, prop, value, cellProperties);
      },
      addEvent: function(el, targetNode, eventType, fn, opts){    // 添加表格中的事件代理
        //el 绑定事件的对象
        //targetNode 触发事件的对象
        //eventType 要添加的事件类型如：'click'等
        //fn 要添加的事件，function
        //opts 要传入的参数
        el['event' + eventType + fn] = el['event' + eventType + fn] || null;
        if(!el['event' + eventType + fn]){
          el['event' + eventType + fn] = function(e){
            var e = e || window.event;
            e.datas = opts || {};
            e.datas.el = el;
            e.datas.targetNode = targetNode;
            fn.call(el, e);
          }
        }
        if (el.addEventListener) {
          el.addEventListener(eventType, el['event' + eventType + fn], false);
        } else if (el.attachEvent) {
          el.attachEvent('on' + eventType, el['event' + eventType + fn]);
        }
      },
      removeEvent: function(el, eventType, fn){
        if(typeof el.removeEventListener != 'undefined'){
          el.removeEventListener(eventType, el['event' + eventType + fn]);
        }else if(typeof el.detachEvent != 'undefined'){
          if(el.events){
            for (var i in el.events[eventType]) {
              if (el.events[eventType][i] == fn) {
                delete el.events[eventType][i];
              }
            }
          }
        }
      },
      eventManager: function(e){
        var vueObj = this;
        var target = e.target || e.srcElement; 
        var nodeName = target.nodeName.toLowerCase();
        while(target !== e.datas.el){
          if(nodeName == e.datas.targetNode){
            var func = target.getAttribute('func'),
                row = target.getAttribute('row'),
                prop = target.getAttribute('prop'), 
                col = target.getAttribute('col');
            if(e.datas.myselfFn){
              vueObj[func](row, prop, col, e);
            }else{
              vueObj.$emit(func, row, prop, col, e);
            }
            break;
          }
          target = target.parentNode;
          nodeName = target.nodeName.toLowerCase();
        }
      },
      tableRender: function(){
        var vueObj = this;
        vueObj.grid.render();
      },
      getColWidths: function(){
        var vueObj = this;
        var colWidths = [];
        for(var i=0;i < vueObj.tableColumns.length; i++){
          var width = vueObj.tableColumns[i].width || '';
          colWidths.push(width);
        }
        return colWidths;
      },
      getTableGrid: function(){
        return this.grid;
      },
      setColor: function(colorClass){
        var vueObj = this;
        var selected = this.getSelected();
        if(selected.length <= 0){
          return;
        }
        for(var i=0; i<selected.length; i++){
          selected[i].color = colorClass;     //对viewList数据进行颜色赋值
          var nowID = selected[i].id;
          var prop = 'color';
          vueObj.updateTableRemouldData(nowID, prop, colorClass);    //当显示数据发生改变时，对原始数据也进行改变
        }
        console.log("viewList", JSON.stringify(selected));
        this.grid.render();
        this.grid.deselectCell();  //清除选中单元格
      },
      setTrColor: function(row, TH){
        var vueObj = this;
        var record = vueObj.viewList[row];
        if (record && record['color']){
          if(TH.parentNode){
            var classname = TH.parentNode.getAttribute("class") ? TH.parentNode.getAttribute("class")+ " " + record['color'] : record['color'];
            TH.parentNode.setAttribute("class",classname); // 设置颜色标记样式 
          }
        };
      },
      getSelected: function(){
        if(this.grid && this.viewList){
          var range = this.grid.getSelected()[0];        
          if(range){
            console.log(range);
            var top = Math.min(range[0], range[2]);
            var bottom = Math.max(range[0], range[2]);    
            console.log("top",top,"bottom",bottom);    
            if(top > this.theadRow - 1){
              return this.viewList.slice(top, bottom + 1);  
            }else{
              return [];
            }            
          }else{
            return [];
          }  
        }else{
          return [];
        }
      },
      remouldNodes: function(nodes){   //处理层级节点数据
        var initObj = {};
        for(var i=0; i < nodes.length; i++){
          var idKey = nodes[i].id;
          var pid = nodes[i].pid;
          if(!initObj[idKey]){
            initObj[idKey] = nodes[i];
            if(pid && initObj[pid]){
              initObj[pid].childCount = initObj[pid].childCount ? initObj[pid].childCount + 1 : 1;
              initObj[idKey].level = initObj[pid].level + 1;
            }else{
              initObj[idKey].level = 0;
            }
          } 
        }
        for(var i=0; i < nodes.length; i++){
          var idKey = nodes[i].id;
          if(initObj[idKey].level){
            nodes[i].level = initObj[idKey].level;
          }
          if(initObj[idKey].childCount){
            nodes[i].childCount = initObj[idKey].childCount;
          }
          nodes[i]['rowNo'] = i;
        }
        return nodes;
      },
      foldTr: function(row, prop, col, e){
        var vueObj = this;  
        var tableRemouldData = vueObj.objDeepCopy(vueObj.tableRemouldData);
        var curRecord = tableRemouldData[row];
        var curLevel = curRecord.level;
        
        vueObj.collapseID[curRecord.id] = !this.collapseID[curRecord.id];
        var nindex = tableRemouldData.indexOf(curRecord);

        if (nindex >= 0) {
          for (var i = nindex + 1; i < tableRemouldData.length; i++) {
            var item = tableRemouldData[i];
            if (item.level > curLevel) {
              var isFold = vueObj.collapseID[curRecord.id];
              if(isFold){  //都隐藏
                vueObj.hideID[item.id] = vueObj.collapseID[curRecord.id];
              }else{       //显示
                var itemFold = vueObj.collapseID[item.pid] || false;
                var itemHide = vueObj.hideID[item.pid] || false;
                if(itemHide == false && itemFold == false){   //父级显示并展开
                  vueObj.hideID[item.id] = false;
                }else if(itemHide == false && itemFold == true){     //父级显示并折叠
                  vueObj.hideID[item.id] = true;
                }else if(itemHide == true){    //父级隐藏
                  vueObj.hideID[item.id] = true;
                }
              }
            }else{
              break;
            }
          };
        }

        var newData = tableRemouldData.filter(function(item){   //筛选数据，将折叠的数据删掉
          return !(vueObj.hideID[item.id] || (item.pid && vueObj.collapseID[item.pid]));
        });
        
        vueObj.viewList = vueObj.objDeepCopy(newData);
        vueObj.grid.updateSettings({"data": newData});
        vueObj.grid.render();
        
      },
      upfoldTo: function(level) {   //展开到第几级
        var vueObj = this;
        var level = level - 1;
        var tableRemouldData = vueObj.objDeepCopy(vueObj.tableRemouldData);
        vueObj.collapseID = {};
        vueObj.hideID = {};
        for(var i=0;i<tableRemouldData.length; i++){
          if(tableRemouldData[i].level == level){
            vueObj.collapseID[tableRemouldData[i].id] = true;
          }else if(tableRemouldData[i].level > level){
            vueObj.hideID[tableRemouldData[i].id] = true;
          }
        }
        vueObj.viewList = tableRemouldData.filter(function(item){   //筛选数据，将折叠的数据删掉
          return !(vueObj.hideID[item.id] || (item.pid && vueObj.collapseID[item.pid]));
        });
        vueObj.grid.updateSettings({"data": vueObj.viewList});
        vueObj.grid.render();
      },
      checkIndeterminate: function(e){
        var vueObj = this;
        var target = e.target || e.srcElement;
        var tableRemouldData = vueObj.tableRemouldData;
        var row = target.getAttribute('row');
        var curRecord = tableRemouldData[row];
        var curLevel = curRecord.level;
        vueObj.checkedID[curRecord.id] = target.checked;
        vueObj.indeterminateID[curRecord.id] = false;
        var nindex = tableRemouldData.indexOf(curRecord);
        if (nindex >= 0) {
          //往后找子集
          for (var i = nindex + 1; i < tableRemouldData.length; i++) {
            var item = tableRemouldData[i];
            if (item.level > curLevel) {
              vueObj.checkedID[item.id] = vueObj.checkedID[curRecord.id];
              vueObj.indeterminateID[item.id] = false;
            }else{
              break;
            }
          };
          vueObj.checkSiblings(curRecord);
        }
        vueObj.grid.render();
      },
      checkSiblings: function(curRecord, isSetAllParent){   //isSetAllParent 是否一次性设置所有父级indeterminate为true
        var vueObj = this;
        var tableRemouldData = vueObj.tableRemouldData;
        var nindex = tableRemouldData.indexOf(curRecord);
        var checked = vueObj.checkedID[curRecord.id];
        var parentItem;
        var siblingsItem;
        //往前找父级
        for (var i = nindex - 1; i >= 0; i--) {
          var item = tableRemouldData[i];
          if(item.id == curRecord.pid){
            parentItem = item;
            break;
          }
        };

        if(parentItem){
          //找同级
          siblingsItem = tableRemouldData.filter(function(item){   //筛选数据，将折叠的数据删掉
            return ((item.pid == curRecord.pid) && (item.id != curRecord.id));
          });

          var isSame = true;     //同级选中是否相同
          for(var i=0; i<siblingsItem.length; i++){
            isSame = (vueObj.checkedID[siblingsItem[i].id] || false) === checked;
            if(!isSame){
              break;
            }
          }
          isSetAllParent = isSetAllParent || false;   //是否一次性设置所有父级indeterminate为true
          if(!isSetAllParent){
            if(isSame && checked){   //同级相同，自己为选中，那么父级也为选中
              vueObj.checkedID[parentItem.id] = checked;
              vueObj.indeterminateID[parentItem.id] = false;
            }else if(isSame && !checked){  //同级相同，自己为不选中，那么父级也为不选中
              vueObj.checkedID[parentItem.id] = checked;
              vueObj.indeterminateID[parentItem.id] = false;
            }else{     //同级不相同，所有父级indeterminate为true
              vueObj.checkedID[parentItem.id] = false;
              vueObj.indeterminateID[parentItem.id] = true;
              isSetAllParent = true;
            }
          }else{
            vueObj.checkedID[parentItem.id] = false;
            vueObj.indeterminateID[parentItem.id] = true;
          }
          vueObj.checkSiblings(parentItem, isSetAllParent);
        }
      },
      changeCheckbox: function(row, prop, col, e){
        var vueObj = this;
        var value = !vueObj.viewList[row][prop];
        vueObj.viewList[row][prop] = value;
        vueObj.grid.updateSettings({"data": vueObj.viewList});
        var nowID = vueObj.viewList[row].id;
        vueObj.updateTableRemouldData(nowID, prop, value); //当显示数据发生改变时，对原始数据也进行改变
        vueObj.grid.render();
      },
      tableHeadClick: function(row, prop, col, e){   //头部i标签点击事件
        var target = e.target || e.srcElement;
        var classname = target.getAttribute("class") || '';
        var isSort = classname.indexOf("triangle") >= 0 ? true : false;
        var isFilter = classname.indexOf("filtrate") >= 0 ? true : false;
        if(isSort){   //点击的是排序
          this.triggerSort(row, prop, col, e);
        }else if(isFilter){   //点击的是筛选
          this.triggerFilter(row, prop, col, e);
        }
      },
      triggerSort: function(row, prop, col, e){  
        var vueObj = this;
        var target = e.target || e.srcElement;
        var classname = target.getAttribute("class") || '';
        var isActive = classname.indexOf("active") >= 0 ? true : false;
        var isUp = classname.indexOf("mc-icon-triangle-up") >= 0 ? true : false;
        vueObj.sortE = e;
        var col = e.datas.col;
        vueObj.sortCol = {};
        if(!isActive){
          vueObj.sortCol[col] = isUp ? 'up' : 'down';
        }
        vueObj.grid.render();
        vueObj.sortFilterData();
      },
      triggerFilter: function(row, prop, col, e){
        var vueObj = this;
        var allLi = [{label:'全部',rule:''}];
        vueObj.filterListData = allLi.concat(e.datas.filterRule);
        vueObj.filterE = e;
        var col = e.datas.col;
        var filterIndex = vueObj.filterCol[col];
        var isShow = vueObj.filterListState[col];
        if(filterIndex){  //判断当前列被筛选的下标
          vueObj.filterLisActive = filterIndex;
        }else{
          vueObj.filterLisActive = 0;
        }
        if(isShow){  //判断当前列筛选列表的显示状态
          vueObj.filterListState[col] = false;
          vueObj.isShowFilter = false;
        }else{
          vueObj.filterListState = {};
          vueObj.filterListState[col] = true;
          vueObj.isShowFilter = true;

          var filterListObj = vueObj.$el.getElementsByClassName("filterList")[0];
          var offset1 = vueObj.getElemPos(e.target);
          var offset2 = vueObj.getElemPos(filterListObj.parentNode);
          var el = vueObj.$el.getElementsByClassName("ht_master")[0].getElementsByClassName("wtHolder")[0];
          filterListObj.style.left = (offset1.x - offset2.x - el.scrollLeft) + "px";
          filterListObj.style.top = (offset1.y - offset2.y  + 20) + "px";
        }
      },
      changeFilter:function(index){
        var vueObj = this;
        var e = vueObj.filterE;
        var target = e.target || e.srcElement;
        var col = e.datas.col;
        vueObj.filterCol = {};
        vueObj.isShowFilter = false;
        vueObj.filterLisActive = index;
        if(index > 0){
          vueObj.filterCol[col] = index;
          vueObj.filterListState[col] = false;
        }
        vueObj.grid.render();
        vueObj.sortFilterData();
      },
      sortFilterData: function(){
        var vueObj = this;
        var data;
        var isFilter = JSON.stringify(vueObj.filterCol) == "{}" ? false : true;
        var isSort = JSON.stringify(vueObj.sortCol) == "{}" ? false : true;
        //先进行筛选
        if(isFilter){
          var e = vueObj.filterE;
          var target = e.target || e.srcElement;
          var col = e.datas.col;
          var prop = e.datas.prop;
          var index = vueObj.filterLisActive - 1;
          var headArr = vueObj.tableRemouldData.slice(0,vueObj.theadRow);
          var contentArr = vueObj.tableRemouldData.slice(vueObj.theadRow).filter(function(item){   //筛选数据，将折叠的数据删掉
            var value = item[prop];
            return eval(e.datas.filterRule[index].rule);
          });
          var allArr = headArr.concat(contentArr);
          data = allArr;
          //检测是否有折叠,有则添加
          vueObj.checkFoldTr('clear');
        }else{
          data = vueObj.tableRemouldData;
        }

        //再进行排序
        if(isSort){
          var e = vueObj.sortE;
          var target = e.target || e.srcElement;
          var classname = target.getAttribute("class") || '';
          var isUp = classname.indexOf("mc-icon-triangle-up") >= 0 ? true : false;
          var col = e.datas.col;
          var headArr = data.slice(0,vueObj.theadRow);
          var contentArr = data.slice(vueObj.theadRow).sort(vueObj.sortCompare(e.datas.prop, e.datas.sortType));
          if(!isUp){
            //倒序
            contentArr.reverse(); 
          }
          var allArr = headArr.concat(contentArr);
          data = allArr;
          //检测是否有折叠,有则清除
          vueObj.checkFoldTr('clear');
        }

        if(!isFilter && !isSort){
          //检测是否有折叠,有则添加
          vueObj.checkFoldTr('add');
        }

        vueObj.grid.updateSettings({"data": data});
        vueObj.viewList = data;
        vueObj.grid.render();
      },
      sortCompare:function(prop,type){
        return function(a,b){
          var value1 = a[prop];
          var value2 = b[prop];
          if(type == "string"){
            return value1.localeCompare(value2);
          }else if(type == "number"){
            return value1 - value2;
          }else if(type == "time"){
            var time1 = new Date(value1);
            var time2 = new Date(value2);
            return time1 - time2;
          }
        }
      },
      checkFoldTr: function(state){
        var vueObj = this;
        for(var i=0; i<vueObj.tableColumns.length; i++){
          var rendererName = vueObj.tableColumns[i].rendererName || "";
          if(rendererName == "colTree" && state == "clear"){
            vueObj.tableColumns[i].rendererName = "";
            if(vueObj.tableColumns[i].enableCheckbox){
              vueObj.tableColumns[i].enableCheckbox = false;
            }
          }else if(state == "add"){
            vueObj.tableColumns = vueObj.objDeepCopy(vueObj.columns);
          }
        }
        vueObj.grid.updateSettings({"columns": vueObj.tableColumns});
        vueObj.grid.render();
      },
      objDeepCopy: function(source){  //深度克隆数组对象
        var sourceCopy = source instanceof Array ? [] : {};
        for (var item in source) {
            sourceCopy[item] = typeof source[item] === 'object' ? this.objDeepCopy(source[item]) : source[item];
        }
        return sourceCopy;
      },
      getElemPos: function(obj){    //获取dom元素绝对位置
        var pos = {"top":0, "left":0};
         if (obj.offsetParent){
           while (obj.offsetParent){
             pos.top += obj.offsetTop;
             pos.left += obj.offsetLeft;
             obj = obj.offsetParent;
           }
         }else if(obj.x){
           pos.left += obj.x;
         }else if(obj.x){
           pos.top += obj.y;
         }
         return {x:pos.left, y:pos.top};
      },
      bindScroll: function(){
        var vueObj = this;
        var el = document.getElementsByClassName("mcTable")[0].getElementsByClassName("ht_master")[0].getElementsByClassName("wtHolder")[0];
        var fn = function(){
          var isShow = vueObj.isShowFilter;
          if(isShow){
            vueObj.filterListState = {};
            vueObj.isShowFilter = false;
          }
        }
        if (el.addEventListener) {
          el.addEventListener('scroll', fn , false);
        } else if (obj.attachEvent) {
          obj.attachEvent('onscroll', fn);
        }
      },
      bindDocumentClick: function(){
        var vueObj = this;
        var el = document;
        var fn = function(e){
          var target = e.target || e.srcElement;
          var classname = target.getAttribute("class") || '';
          var isFilterBtn = classname.indexOf("mc-icon-filtrate") >= 0 ? true : false;
          if(!isFilterBtn){
            vueObj.filterListState = {};
            vueObj.isShowFilter = false;
          } 
        }
        if (el.addEventListener) {
          el.addEventListener('click', fn , false);
        } else if (obj.attachEvent) {
          obj.attachEvent('click', fn);
        }
      },
      stopHeadContextMenu: function(){
        var vueObj = this;
        var isOpen = vueObj.contextMenu;
        if(isOpen){  //有右键功能
          var theadTdArr = this.$el.getElementsByClassName("theadBg");
          for(var i=0; i<theadTdArr.length; i++){
            theadTdArr[i].oncontextmenu = function(e){
              e.stopPropagation();
              return false;
            }
          }
        } 
      },
      checkManualColResize: function(){
        var vueObj = this;
        var isManualColResize = vueObj.manualColumnResize;
        if(isManualColResize){
          var len = vueObj.$el.getElementsByClassName("manualColumnResizerDom").length;
          var dragNodeBlock;
          var dragNodeLine;
          if(len > 0){
            dragNodeBlock = vueObj.$el.getElementsByClassName("manualColumnResizerDom")[0];
            dragNodeLine = vueObj.$el.getElementsByClassName("manualColumnResizerGuideDom")[0];
          }else{
            dragNodeBlock=document.createElement("div");
            dragNodeBlock.setAttribute("class","manualColumnResizerDom");
            vueObj.$el.appendChild(dragNodeBlock);
            dragNodeLine=document.createElement("div");
            dragNodeLine.setAttribute("class","manualColumnResizerGuideDom");
            vueObj.$el.appendChild(dragNodeLine);
          }
          var theadTdArr = this.$el.getElementsByClassName("theadBg");
          for(var i=0; i<theadTdArr.length; i++){
            var td = theadTdArr[i];
            td.onmouseover = function(){
              clearTimeout(vueObj.manualColumnResizerTimer);
              var tdOffset = vueObj.getElemPos(this);
              var offsetParent = vueObj.getElemPos(vueObj.$el);
              var tdW = this.offsetWidth;
              var tdH = this.clientHeight;
              var wtHolder = vueObj.$el.getElementsByClassName("ht_master")[0].getElementsByClassName("wtHolder")[0];
              dragNodeBlock.style.height = tdH + "px";
              dragNodeBlock.style.left = (tdOffset.x - offsetParent.x + tdW - 5 - wtHolder.scrollLeft) + "px";
              dragNodeBlock.style.top = (tdOffset.y - offsetParent.y + 1) + "px";
              var col = vueObj.grid.getCoords(this).col;
              var colspan = parseInt(this.getAttribute('colspan'));

              var lockState = dragNodeBlock.getAttribute("lockCol");
              if(lockState == null || lockState=="false"){
                dragNodeBlock.setAttribute("col", col);
                dragNodeBlock.setAttribute("colspan", colspan);
              }
            }
          }
          vueObj.bindDragfn();
        }
      },
      bindDragfn: function(){
        var vueObj = this;
        var dragNodeLine = vueObj.$el.getElementsByClassName("manualColumnResizerGuideDom")[0];
        var dragNodeBlock = vueObj.$el.getElementsByClassName("manualColumnResizerDom")[0];
        dragNodeBlock.onmouseover = function(){
          clearTimeout(vueObj.manualColumnResizerTimer);
        }
        dragNodeBlock.onmousedown = function(){
          var dragNodeLine = vueObj.$el.getElementsByClassName("manualColumnResizerGuideDom")[0];
          var dragNodeBlock = vueObj.$el.getElementsByClassName("manualColumnResizerDom")[0];
          var dragLineH = vueObj.$el.getElementsByClassName("ht_master")[0].getElementsByClassName("wtHolder")[0].clientHeight;
          dragNodeBlock.setAttribute("lockCol", true);  //锁住要拖拽的列号
          dragNodeLine.style.height = dragLineH + "px";
          dragNodeLine.style.left = parseInt(dragNodeBlock.style.left) + "px";
          dragNodeLine.style.top = parseInt(dragNodeBlock.style.top) + "px";
          vueObj.manualColumnResizerStart = parseInt(dragNodeBlock.style.left);
          document.onmousemove = function(e){
            var oEvent=e || event;
            var parentLeft = vueObj.$el.offsetLeft;
            dragNodeBlock.style.left = (oEvent.clientX - parentLeft) + "px";
            dragNodeLine.style.left = (oEvent.clientX - parentLeft) + "px";
          },
          document.onmouseup = function(e){
            document.onmousemove=null;
            document.onmouseup=null;
            var dragLineObj = vueObj.$el.getElementsByClassName("manualColumnResizerGuideDom")[0];
            var manualColumnResizerend = parseInt(dragLineObj.style.left);
            dragLineObj.style.height = "0px"; 
            var diff = manualColumnResizerend - vueObj.manualColumnResizerStart;
            var col = parseInt(dragNodeBlock.getAttribute("col"));
            var colspan = parseInt(dragNodeBlock.getAttribute("colspan"));
            if(colspan){   //如果是复杂表头，则平分增加的宽度
              for(var i=col; i<(col+colspan); i++){
                var colW = vueObj.grid.getColWidth(col) + diff / colspan;
                vueObj.colWidths[i] = colW >= vueObj.tdMinWidth ? colW : vueObj.tdMinWidth;
              }
            }else{
              var colW = vueObj.grid.getColWidth(col) + diff;
              vueObj.colWidths[col] = colW >= vueObj.tdMinWidth ? colW : vueObj.tdMinWidth;
            }
            vueObj.grid.updateSettings({"colWidths": vueObj.colWidths});
            vueObj.grid.render();
            dragNodeBlock.style.display = "none";
            setTimeout(function(){
              dragNodeBlock.style.display = "block";
            },30);
            dragNodeBlock.setAttribute("lockCol", false);  //解锁
          }
        }
      },
      checkAllRow: function(isReverse){
        var vueObj = this;
        var data = vueObj.tableRemouldData;
        for(var i = 0; i<data.length; i++){
          var nowId = data[i].id;
          if(nowId >= 0){
            var checkedState = true;
            if(isReverse){
              checkedState = false;
            }
            vueObj.checkedID[nowId] = checkedState;
          }
        }
        vueObj.indeterminateID = {};
        vueObj.grid.render();
      },
      reverseCheck: function(){
        var vueObj = this;
        var tableBodyData = vueObj.tableRemouldData.slice(vueObj.theadRow);
        for(var i=0;i<tableBodyData.length; i++){
          var nowId = tableBodyData[i].id;
          if(vueObj.checkedID[nowId]){
            vueObj.checkedID[nowId] = false;
          }else{
            vueObj.checkedID[nowId] = true;
          }
        }
        vueObj.grid.render();
      },
      clearObjFalse: function(obj){   //清除Obj中值为false的某个属性
        for(var key in obj){
          if(!obj[key]){
            delete obj[key];
          }
        }
      },
      showOptions: function(row, prop, col, e){
        var vueObj = this;
        var options = e.datas.options;
        var isMultiple = e.datas.isMultiple;
        var reference = vueObj.grid.getCell(row, col);   //选中的单元格DOM
        var value = reference.getElementsByClassName('htAutocomplete')[0].getAttribute('value');
        e.stopPropagation();

        var tableId = vueObj.tableId;
        var popperObj = document.getElementById(tableId);
        
        if(!popperObj){
          var selectNodeBlock = document.createElement("div");
          if(isMultiple){
            selectNodeBlock.setAttribute("class","selectOptions popover multiple");
          }else{
            selectNodeBlock.setAttribute("class","selectOptions popover");
          }
          selectNodeBlock.setAttribute("id", tableId);
          selectNodeBlock.innerHTML = '<div class="popover-content"></div><div class="popover-arrow" x-arrow></div>';
          document.getElementsByTagName("body")[0].appendChild(selectNodeBlock);
          popperObj = document.getElementById(tableId);
        }

        var optionsListHtml = "";
        var className =  '';
        for(var i=0; i<options.length; i++){
          if(isMultiple){   //多选
            var isHave = vueObj.findArr(options[i], value.split(','));
            if(isHave){
              className = "active";
            }else{
              className = "";
            }
          }else{            //单选
            if(options[i] == value){
              className = "active";
            }else{
              className = "";
            }
          } 
          optionsListHtml += '<li func="clickOption" row="'+ row +'" col="'+ col +'" prop="'+ prop +'" class="'+ className +'">'+ options[i] +'</li>'; 
        }
        popperObj.style.width = reference.offsetWidth + 'px';
        popperObj.getElementsByClassName("popover-content")[0].innerHTML = '<ul>'+ optionsListHtml +'</ul>'
        
        var options = {
            placement: 'bottom'
        };
        vueObj.runPopper(reference,popperObj,options);
        this.addEvent(popperObj,"li","click", this.eventManager, {'myselfFn':true, 'isMultiple':isMultiple});
      },
      clickOption: function(row, prop, col, e){
        var vueObj = this;
        var value = '';
        var isMultiple = e.datas.isMultiple;
        if(isMultiple){   //多选
          var targetClass = e.target.getAttribute("class");
          var isActive = targetClass.indexOf("active") >= 0 ? true : false;
          if(isActive){   //之前是选中，现在取消选中
            e.target.setAttribute("class",'');
          }else{
            e.target.setAttribute("class",'active');
          }
          var ulDom = e.target.parentNode;
          var activeArr = ulDom.getElementsByClassName('active');
          for(var i=0; i<activeArr.length; i++){
            if(value){
              value += ',' + activeArr[i].innerHTML;
            }else{
              value = activeArr[i].innerHTML;
            }
          }
          e.stopPropagation();
        }else{            //单选
          value = e.target.innerHTML;
        }
        vueObj.viewList[row][prop] = value;
        vueObj.grid.updateSettings({"data": vueObj.viewList});
        var nowID = vueObj.viewList[row].id;
        vueObj.updateTableRemouldData(nowID, prop, value); //当显示数据发生改变时，对原始数据也进行改变
        vueObj.grid.render();
      },
      findArr: function(value, arr){
        for(var i=0; i<arr.length; i++){
          if(value == arr[i]){
            return true;
          }
        }
        return false;
      },
      setBorder: function(isBordered){
        var vueObj = this;
        var className = vueObj.$el.getAttribute("class");
        if(isBordered){
          className = className.replace('removeBorder','');
        }else{
          className = className + ' removeBorder';
        }
        vueObj.$el.setAttribute("class", className);
      },
      showLoading: function(isLoading){
        var vueObj = this;
        vueObj.isLoading = isLoading;
      },
      updateTableRemouldData:function(id, prop, value){    //更新原始数据
        var vueObj = this;
        for(var i=0;i<vueObj.tableRemouldData.length; i++){
          if(id == vueObj.tableRemouldData[i].id){
            vueObj.tableRemouldData[i][prop] = value;
            break;
          }
        }
      },
      listenScroll: function(){   //监听scroll
        var vueObj = this;
        var obj = vueObj.$el.getElementsByClassName("ht_master")[0].getElementsByClassName("wtHolder")[0];
        obj.addEventListener('scroll',function (){
          //内容总体的高度 - 滚动条的偏移值  === 元素的高度(包含内边)但不包含外边距，边框，以及滚动条
          var scrollHeight = this.scrollHeight;
          var scrollTop = this.scrollTop;
          var clientHeight = this.clientHeight;
          if(scrollTop != 0){
            if( scrollHeight-scrollTop === clientHeight){
              //到达底部
              obj.scrollTop = scrollTop - 1;
              console.log("render表格");
              vueObj.grid.render();
            }
          }
        });
      },
      getData: function(){    //获取数据
        var vueObj = this;
        return vueObj.tableRemouldData;
      },
      updateTable: function(config){   //更新表格配置
        var vueObj = this;
        vueObj.grid.updateSettings(config);
      },
      clearStateId: function(){   //清空状态ID
        var vueObj = this;
        vueObj.collapseID = {};        //折叠的ID
        vueObj.hideID = {};            //隐藏的ID
        vueObj.checkedID = {};         //选中的ID
        vueObj.indeterminateID = {};   //不确定的ID 
      }
    }
  }
</script>
