<!--
    id: 选填，没有得话给随机id
    settting: handsontable得配置，其中必填data选项
-->

<template>
  <div style="height: 100%; width: 100%">
    <div :id="id" style="overflow: auto"></div>
  </div>
</template>
<script>
import Handsontable from "handsontable-pro";
import "handsontable-pro/dist/handsontable.full.css";
import zhCN from "handsontable-pro/languages/zh-CN";
import tools from "@/utils/old-adm/scan/tools";
import "@/assets/js/chosen.jquery.min";
import "@/assets/js/handsontable-chosen-editor";
import "@/assets/css/chosen.css";
export default {
  props: {
    id: {
      type: String,
      default: function createRandomId() {
        return (
          (Math.random() * 10000000).toString(16).substr(0, 4) +
          "-" +
          new Date().getTime() +
          "-" +
          Math.random().toString().substr(2, 5)
        );
      },
    },
    // settings: {//必填
    //   type: Object
    // }
  },
  data() {
    return {
      hot: null,
      filtersArr: [],
      data: [],
      deepArr: [], //删除存储数组
    };
  },
  created() {},
  mounted() {
    // console.log(handsontable)
    // this.init()
  },
  methods: {
    getElement() {
      return {
        width: document.getElementById(this.id).clientWidth,
        height: document.getElementById(this.id).parentNode.clientHeight,
      };
    },
    // afterDocumentKeyDown(e) {
    //     this.$emit("keyDown", e)
    // },
    trimmedRows() {
      var plugin = this.hot.getPlugin("trimRows").trimmedRows;
      let dataLength = this.hot.getSourceData().length;
      let dataArr = new Array();
      for (let i = 0; i < dataLength; i++) {
        dataArr.push(i);
      }
      if (plugin.length <= 0) {
        dataArr = undefined;
      } else {
        dataArr = this.array_diff(dataArr, plugin);
      }
      this.filtersArr = dataArr;
      return dataArr || [];
    },
    //去除数组中相同的元素
    array_diff(a, b) {
      for (var i = 0; i < b.length; i++) {
        for (var j = 0; j < a.length; j++) {
          if (a[j] == b[i]) {
            a.splice(j, 1);
            j = j - 1;
          }
        }
      }
      return a;
    },
    //右键删除
    removeFm(index, amout) {
      let delData = tools.differenceArr(this.data, this.deepArr);
      this.$emit("delete", delData);
    },
    //数据发生修改后(失焦)
    tdChange(changeData, source) {
      this.$emit("change", changeData, source);
    },
    /**
     * 获取被排序后的数组
     *
     * @param changeData 发生改变的数据
     * @param source     数组
     *
     * @return array     经过排序后或者经过搜索后的数组
     */
    getParam(changeData, source, hot, trimmedArr) {
      let param = "";
      //被筛选过后的数组
      // let trimmedArr = this.trimmedRows();
      //是否启用了排序
      let isSort = hot.getPlugin("columnSorting").isSorted();
      if (trimmedArr.length && isSort) {
        //排序后的数组
        let sortArr = hot.getPlugin("columnSorting").rowsMapper.__arrayMap;
        param = changeData.map((item) => {
          return hot.getSourceDataAtRow(trimmedArr[sortArr[item[0]]]);
        });
      } else if (isSort) {
        //排序后的数组
        let sortArr = hot.getPlugin("columnSorting").rowsMapper.__arrayMap;
        param = changeData.map((item) => {
          return hot.getSourceDataAtRow(sortArr[item[0]]);
        });
      } else if (trimmedArr.length) {
        param = changeData.map((item) => {
          return hot.getSourceDataAtRow(trimmedArr[item[0]]);
        });
      } else {
        param = changeData.map((item) => {
          return hot.getSourceDataAtRow(item[0]);
        });
      }
      return param;
    },
    /**
     *
     * @param {handsontable修改参数} changeData
     * @param {*} source
     * @param {handsontabele实例} hot
     * @param {排序数组} trimmedArr
     *
     * @return 修改数值的前一个对象
     */
    getUnshiftParam(changeData, source, hot, trimmedArr) {
      //是否启用了排序
      let isSort = hot.getPlugin("columnSorting").isSorted();
      if (trimmedArr.length && isSort) {
        //排序后的数组
        let sortArr = hot.getPlugin("columnSorting").rowsMapper.__arrayMap;
        return hot.getSourceDataAtRow(
          trimmedArr[sortArr[changeData[0][0] - 1]]
        );
      } else if (isSort) {
        //排序后的数组
        let sortArr = hot.getPlugin("columnSorting").rowsMapper.__arrayMap;
        return hot.getSourceDataAtRow(sortArr[changeData[0][0] - 1]);
      } else if (trimmedArr.length) {
        //进行了筛选
        return hot.getSourceDataAtRow(trimmedArr[changeData[0][0] - 1]);
      } else {
        //没有进行排序和筛选
        return hot.getSourceDataAtRow(changeData[0][0] - 1);
      }
    },
    init(settings) {
      var hotElement = document.getElementById(this.id);
      this.data = settings.data;
      this.deepArr = this.deepCopy(settings.data);
      var hotSettings = Object.assign(
        {
          // width: this.getElement().width,
          rowHeaders: true,
          colHeaders: true,
          filters: true,
          height: this.getElement().height,
          columnSorting: true, //添加排序
          sortIndicator: true, //添加排序
          renderAllRows: true,
          autoColumnSize: true,
          // observeChanges: false, //启用observeChanges插件
          language: "zh-CN",
          manualColumnResize: true,
          manualColumnMove: true,
          dropdownMenu: [
            "filter_by_condition",
            "filter_by_value",
            "filter_action_bar",
          ],
          afterOnCellMouseDown: this.tableDown, //鼠标单击
          afterChange: this.tdChange, //修改后
          afterRemoveRow: this.removeFm, //右键删除
          afterFilter: this.trimmedRows, //排序
          // afterDocumentKeyDown: this.afterDocumentKeyDown, //鼠标单击
        },
        settings
      );
      hotSettings.maxRows = settings.maxRows;
      if (!!this.hot && this.hot.hasOwnProperty("destroy")) {
        this.hot.destroy();
        this.hot = null;
      }
      this.hot = new Handsontable(hotElement, hotSettings);
      // this.hot.view.wt.update('onCellDblClick', (row,cell) => {
      //     //Get editor and begin edit mode on current cell (maintain current double click functionality)
      //     var activeEditor = this.hot.getActiveEditor();
      //     console.log(this.hot,activeEditor)
      //     activeEditor.beginEditing();
      //     this.onDblClick(activeEditor,row,cell)
      //     //Do whatever you want...
      // });
      let pro = document.getElementById("hot-display-license-info");
      if (!!pro) {
        pro.parentNode.removeChild(pro);
      }
      return this.hot;
    },
    //双击
    // onDblClick(activeEditor,row,cell){
    //     console.log(111,activeEditor,row,cell)
    // },
    tableDown(el, rowArr) {
      if (rowArr.row < 0) {
        return false;
      }
      let filter = this.filtersArr;
      //被筛选过后的数组
      let trimmedArr = this.trimmedRows();
      //是否启用了排序
      let isSort = this.hot.getPlugin("columnSorting").isSorted();
      let myHotMainArr = this.hot.getSourceData();
      // debugger
      if (trimmedArr.length && isSort) {
        let sortArr = this.hot.getPlugin("columnSorting").rowsMapper.__arrayMap;
        let infos = myHotMainArr[trimmedArr[sortArr[rowArr.row]]];
        this.getInfors(infos, rowArr);
      } else if (isSort) {
        //排序后的数组
        let sortArr = this.hot.getPlugin("columnSorting").rowsMapper.__arrayMap;
        let infos = myHotMainArr[sortArr[rowArr.row]];
        this.getInfors(infos, rowArr);
      } else if (trimmedArr.length) {
        let infos = myHotMainArr[trimmedArr[rowArr.row]];
        this.getInfors(infos, rowArr);
      } else {
        let infos = myHotMainArr[rowArr.row];
        this.getInfors(infos, rowArr);
      }
    },
    getInfors(obj, row) {
      this.$emit("mouseDown", obj, row);
    },
    //工具函数浅复制深拷贝，防止共用存储空间
    deepCopy(obj) {
      var out = [],
        i = 0,
        len = obj.length;
      for (; i < len; i++) {
        if (obj[i] instanceof Array) {
          out[i] = this.deepcopy(obj[i]);
        } else out[i] = obj[i];
      }
      return out;
    },
  },
};
</script>
<style lang="less">
.htDropdownMenu:not(.htGhostTable) {
  z-index: 4060;
}
</style>
