// dragstart 事件：当被拖拽元素开始被拖拽时触发。

// drag 事件：当被拖拽元素被拖拽时持续触发。

// dragenter 事件：当被拖拽元素进入一个可放置目标元素时触发。该事件触发后，目标元素通常会发生视觉变化，表明它可以接受被拖拽元素的放置。

// dragover 事件：当被拖拽元素在一个可放置目标元素上移动时持续触发。通常需要在该事件中调用 event.preventDefault() 方法，以允许在目标元素上放置被拖拽元素。

// dragleave 事件：当被拖拽元素离开一个可放置目标元素时触发。该事件触发后，目标元素通常会恢复到原来的状态。

// drop 事件：当被拖拽元素被放置到一个可放置目标元素中时触发。通常需要在该事件中调用 event.preventDefault() 方法，以阻止浏览器默认的行为（比如打开文件）。

// dragend 事件：当被拖拽元素完成拖拽操作时触发。不管拖拽操作成功与否，都会触发该事件。

// 需要注意的是，dragenter 和 dragleave 事件可能会在目标元素的子元素之间交替触发。如果你希望在这种情况下只对目标元素本身进行操作，可以在事件处理程序中检查事件的 relatedTarget 属性和 target 属性，来判断是否是进入或离开目标元素本身。




function _animate(prevRect, target, callback) {
  var ms = 300;

  if (ms) {
    var currentRect = target.getBoundingClientRect();

    if (prevRect.nodeType === 1) {
      prevRect = prevRect.getBoundingClientRect();
    }

    _css(target, 'transition', 'none');
    _css(target, 'transform', 'translate3d(0,' +
      (prevRect.top - currentRect.top) + 'px,0)'
    );

    target.offsetWidth; // 触发重绘
    //放在timeout里面也可以
    // setTimeout(function() {
    //     _css(target, 'transition', 'all ' + ms + 'ms');
    //     _css(target, 'transform', 'translate3d(0,0,0)');
    // }, 0);
    _css(target, 'transition', 'all ' + ms + 'ms');
    _css(target, 'transform', 'translate3d(0,0,0)');

    // clearTimeout(target.animated);
    target.animated = function () {
      _css(target, 'transition', '');
      _css(target, 'transform', '');
      target.animated = false;
      callback && callback();

    };
  }
}
//给元素添加style
function _css(el, prop, val) {
  var style = el && el.style;

  if (style) {
    if (val === void 0) {
      if (document.defaultView && document.defaultView.getComputedStyle) {
        val = document.defaultView.getComputedStyle(el, '');
      } else if (el.currentStyle) {
        val = el.currentStyle;
      }

      return prop === void 0 ? val : val[prop];
    } else {
      if (!(prop in style)) {
        prop = '-webkit-' + prop;
      }

      style[prop] = val + (typeof val === 'string' ? '' : 'px');
    }
  }
}
export default {
  data() {
    return {
      isDraggable: false,
      removeDragEve: null
    }
    //  this.isDraggable=false


  },
  mounted() {

    if (this.rowDrag&&this.$refs.a_table && this.elementTableContent) {

      let table = this.$refs.a_table.$el;
      let currentRowList = this.elementTableBodyList;

      let currentRow, targetRow
      let currentRowIndex = -1;
      let targetRowIndex = -1,prevTargetRowIndex = -1
      let _this = this;

      const tableBody = this.tableBody;
      let draggedList = []
      let thead = tableBody.querySelector('thead')?.offsetHeight ?? 0
      let headerHeight = 0
      if (tableBody.previousSibling.className?.includes('ant-table-header')) {
        headerHeight = tableBody.previousSibling.scrollHeight
      } else {
        headerHeight = -thead
      }

      let dragLine = this.createDragLine();
      dragLine.rowEdge = true;
      tableBody.appendChild(dragLine.$el);

      let mousedown = function (event) {
        if (event.button === 0) { // 鼠标左键
          //isMouseDown = false;


          currentRow = event.target.closest(".row-drag-icon");
          if (!currentRow) return
          currentRow = currentRow.closest('tr')
          currentRowIndex = currentRow.rowIndex;
          currentRow.setAttribute("draggable", true)

          for (let i = 0; i < currentRowList.length; i++) {
            let node = currentRowList[i]?.rows[currentRowIndex] ?? null
            if (node) {
              node.setAttribute("draggable", true);
            }
          }
        }

      };
      let dragstart = function (event) {

        event.dataTransfer.setData("text", currentRowIndex);
        for (let i = 0; i < currentRowList.length; i++) {
          let node = currentRowList[i]?.rows[currentRowIndex] ?? null
          if (node) {
            node.classList.add("dragged-row");
            draggedList.push(node)

          }
        }
      }
      let dragover = function (event) {

        event.preventDefault();
        targetRow = event.target.closest("tr");

        if (!targetRow || !targetRow.parentNode || !currentRow || targetRow.parentNode.nodeName == 'THEAD') {
          dragLine.show = false
          dragLine.y = 0
          dragLine.x = 0
          targetRowIndex = -1
          prevTargetRowIndex = -1
          return false
        }
        targetRowIndex = targetRow.rowIndex;
        for (let i = 0; i < draggedList.length; i++) {
          let classList=draggedList[i].classList
          if (classList.contains('drag-over')) {
            classList.remove('drag-over')
          }
        }
        draggedList = []

        for (let i = 0; i < currentRowList.length; i++) {
          let node = currentRowList[i]?.rows[targetRowIndex] ?? null
          if (node) {
            let classList = node.classList
            if (!classList.contains('drag-over')) {
              classList.add('drag-over');
              draggedList.push(node)
            }
          }
        }
        if (targetRowIndex === prevTargetRowIndex) {
          return false
        }

        if (currentRowIndex < targetRowIndex) {
          dragLine.y = targetRow.offsetTop + targetRow.offsetHeight
        } else {
          dragLine.y = targetRow.offsetTop
        }
        dragLine.show = true
        dragLine.x = tableBody.scrollLeft
        // console.log('scrollHeight',tableBody.scrollHeight)
        //  console.log('offsetHeight',tableBody.offsetHeight)
        console.log('drag-over',dragLine.y)
        //   console.log(tableBody.scrollTop)
        //   if (tableBody.offsetHeight - 2 <= dragLine.y&&(tableBody.scrollTop+tableBody.offsetHeight)<tableBody.scrollHeight) {
        //     if(tableBody.scrollTop > 0){
        //     }
        //  //   tableBody.scrollTop = tableBody.scrollTop + (targetRow.offsetHeight / 2)
        //   }
        prevTargetRowIndex=targetRowIndex

      }
      let dragend = function (event) {
        event.preventDefault()

       // _this.elementTableContent.onmouseout()
        for (let i = 0; i < currentRowList.length; i++) {
          let node = currentRowList[i]?.rows[currentRowIndex]
          node?.classList.remove("dragged-row");
          node?.removeAttribute("draggable");
        }
        currentRow.removeAttribute("draggable")
        for (let i = 0; i < draggedList.length; i++) {
          draggedList[i].classList.remove("drag-over");
        }
        draggedList = []
        dragLine.show = false
        dragLine.y = 0
        dragLine.x = 0
        if (!targetRow || targetRowIndex === -1) {
          targetRow = null
          currentRow = null
          targetRowIndex = -1
          currentRowIndex = -1
          return false
        }


        let currentRowRect = currentRow.getBoundingClientRect();
        let targetRowRect = targetRow.getBoundingClientRect();
        let next = targetRowRect
        let fnList = []

        currentRowList.forEach(function (body, bodyIndex) {

          let _targetRow = body.rows[targetRowIndex]
          let _currentRow = body.rows[currentRowIndex]
          if (currentRowIndex < targetRowIndex) {
            for (let i = targetRowIndex; i > currentRowIndex; i--) {
              if (i !== targetRowIndex) {
                let row = body.rows[i]
                if (row) {
                  let r = row.getBoundingClientRect();
                  _animate(next, row);
                  fnList.push(row.animated)
                  if (bodyIndex === currentRowList.length - 1) {
                    next = r
                  }
                }
              }
            }
            _targetRow.parentNode.insertBefore(_currentRow, _targetRow.nextSibling)
            _animate(targetRowRect, _targetRow);
          } else {
            for (let i = targetRowIndex; i < currentRowIndex; i++) {
              if (i !== targetRowIndex) {
                let row = body.rows[i]
                if (row) {
                  let r = row.getBoundingClientRect();
                  _animate(next, row);
                  fnList.push(row.animated)
                  if (bodyIndex === currentRowList.length - 1) {
                    next = r
                  }
                }
              }
            }
            _targetRow.parentNode.insertBefore(_currentRow, _targetRow);
            _animate(targetRowRect, _targetRow);
          }
          _animate(currentRowRect, _currentRow);
          fnList.push(_targetRow.animated, _currentRow.animated);
        })

        return setTimeout(function () {
          fnList.forEach(fn => {
            fn()
          })
          let i = currentRowIndex;
          let h_count = 0
          if (thead) {
            i = i - 1
            h_count = -1
          }
          let handleResult = function (dataSource =_this.dataSource) {

            dataSource.splice(targetRowIndex + h_count, 0, dataSource.splice(i, 1)[0]);
          }

          if (_this.$listeners.rowDragend) {
            _this.$emit('rowDragend', event, {
            currentRecord: _this.dataSource[i],
              currentRowNode:currentRow,
              dataSource:_this.dataSource,
              handleResult
            })
          } else {
            handleResult()
          }
          targetRow = null
          targetRowIndex = -1
          currentRowIndex = -1
          currentRow = null

        }, 300)
      }
      table.addEventListener("mousedown", mousedown);
      table.addEventListener("dragstart", dragstart);
       table.addEventListener("dragover", dragover);
      table.addEventListener("dragend",dragend);


      this.removeDragEve = function () {
        table.removeEventListener('mousedown',mousedown)
        table.removeEventListener('dragstart',dragstart)
        table.removeEventListener('dragover',dragover)
        table.removeEventListener('dragend',dragend)
        dragLine = null
        table=null

      }

    }
  },
  destroyed() {
    this.removeDragEve?.()






  },
  methods: {

  },
}