export default {
    data() {
        return {
            keepDown: false,
            keyValue: 'workorderId',
            // 按shfit键实现多选
            startIndex: null
        }
    },
    mounted() {
        this._keydownBind = e => {
            if (e.keyCode === 16 && e.shiftKey) {
                this.keepDown = true;
            }
        }
        this._keyupBind = e => {
            this.keepDown = false;
        }
        window.addEventListener('keydown', this._keydownBind);
        window.addEventListener('keyup', this._keyupBind);
    },
    deactivated() {
        window.removeEventListener('keydown', this._keydownBind)
        window.removeEventListener('keyup', this._keyupBind)
    },
    activated() {
        window.addEventListener('keydown', this._keydownBind);
        window.addEventListener('keyup', this._keyupBind);
    },
    beforeDestroy() {
        window.removeEventListener('keydown', this._keydownBind)
        window.removeEventListener('keyup', this._keyupBind)
    },
    methods: {
        handleSelectionChange(selection, row) {
            const data = this.$refs.tableRef.tableData; // 获取table当前数据
            const startIdx = this.startIndex; // 获取首次选择对应列的索引
            const lastindex = data.findIndex(v => v === selection[selection.length - 1])
            this.selectedRows = selection;
            if (this.keepDown && selection.includes(data[startIdx])) {
              const sum = Math.abs(startIdx - lastindex) + 1; // 用户可能反向选取，所以要取绝对值
              const min = Math.min(startIdx, lastindex); // 获取起点和终点较小的值
              let i = 0;
              while (i < sum) {
                const index = min + i;
                if (!this.selectedRows.includes(data[index])) {
                  this.$refs.tableRef.toggleRowSelection(data[index], true);
                }
                i++;
              }
            } else {
              this.startIndex = lastindex
              
            }
            this.ids = this.selectedRows.map(item => item[this.keyValue])
            this.single = this.selectedRows.length !== 1
            this.multiple = !this.selectedRows.length
        }
    }
}
