function hasClass(el, cls) {
  if (!el || !cls) return false;
  if (cls.indexOf(' ') !== -1) throw new Error('className should not contain space.');
  if (el.classList) {
    return el.classList.contains(cls);
  } else {
    return (' ' + el.className + ' ').indexOf(' ' + cls + ' ') > -1;
  }
};
function debounce(fn, wait) {
  let timer
  let dur = wait || 400
  return () => {
    clearTimeout(timer)
    let self = this
    let args = arguments
    timer = setTimeout(() => {
      fn.apply(self, args)
    }, dur)
  }
};

export default function(){
  let context = this

  const { $vnode, showHeader, tData, attachFooter } = context

  let headerHeight=showHeader?40:0
  if (!$vnode) return null
  let fixedRight = attachFooter ? context.$el.querySelectorAll('.ant-table-fixed-right')[1] : context.$el.querySelector('.ant-table-fixed-right');
  //let fixedLeft =  context.$el.querySelector('.ant-table-fixed-left');
  let element = null
  const tableBody = context.$el.querySelector('.ant-table-body')
  const tableScroll = context.$el.querySelector('.ant-table-scroll')
  tableBody.classList.add('content');


  if (fixedRight) {
    element = fixedRight
  } else {
    element = tableScroll
  }

  if (!element) return null

  //ant-table-scroll
    // const customScrollbar = document.querySelector('.custom-scrollbarVertical');
  const customScrollbar = element
  const header = customScrollbar.querySelector('.ant-table-header>table')
  let content = tableBody

  // if (hasClass(element, 'ant-table-fixed-right')) {
  //   content = customScrollbar.querySelector('.ant-table-body-inner')
  //   content.classList.add('content')
  // }


  const scrollbarVertical = document.createElement('div');
  scrollbarVertical.style.display = 'none';

  const thumbVertical = document.createElement('div')
  thumbVertical.style.minHeight='20px' ;

  scrollbarVertical.classList.add('scrollbar')
  scrollbarVertical.classList.add('scrollbar-vertical')
  thumbVertical.classList.add('thumb')
  scrollbarVertical.appendChild(thumbVertical)
  scrollbarVertical.style.maxHeight = content.style.maxHeight;
  if (showHeader&&header) {
    scrollbarVertical.style.top=`${headerHeight}px`
  }

  const scrollbarHorizontal = document.createElement('div');
  scrollbarHorizontal.style.display = 'none';

  const thumbHorizontal = document.createElement('div')
  thumbHorizontal.style.minWidth='20px' ;

  scrollbarHorizontal.classList.add('scrollbar')
  scrollbarHorizontal.classList.add('scrollbar-horizontal')
  thumbHorizontal.classList.add('thumb')
  scrollbarHorizontal.appendChild(thumbHorizontal);

  // Track the position of the mouse on the scrollbarVertical
  let isDragging = false;
  let isDragging_x = false;
  let startY = 0, startX = 0;

  // Update the scrollbarVertical and content positions
  let tableRect
  let tableBodyRect
  let tableBodyScrollHeight
  let tableBodyScrollWidth

  ////////////////////////////////////垂直高度值
  let viewportHeight
  let thumbHeight
  ////////////////////////////////////水平宽度值
  let viewportWidth
  let thumbWidth





  let time
  function updateScrollbar(event) {
   if(!tableRect)  return
    clearTimeout(time)
    context.isScollbarSport=true
    //纵向

    const { width, height } = tableRect
    let _tableBody = event?.target ?? tableBody
    if (!height || !width) {
      return hiddenScrollbar()
    }
    if (height) {
      if (tableBodyRect.height < tableBodyScrollHeight) {
        const scrollPercent = _tableBody.scrollTop / (tableBodyScrollHeight - viewportHeight);
        let thumbPosition = scrollPercent * (viewportHeight - thumbHeight);
        if (thumbPosition > tableBodyRect.height - thumbHeight) {
          thumbPosition=tableBodyRect.height-thumbHeight
        }
        thumbVertical.style.transform=`translate3d(0,${thumbPosition}px,0)`
      }
    }
    //横向

    if (width) {

      if (tableBodyRect.width < tableBodyScrollWidth) {
        scrollbarHorizontal.style.display = 'block';
        const scrollHorizontalPercent = _tableBody.scrollLeft / (tableBodyScrollWidth - viewportWidth);
        const thumbPositionLeft = scrollHorizontalPercent * (viewportWidth - thumbWidth);
        thumbHorizontal.style.transform=`translate3d(${thumbPositionLeft}px,0,0)`
      }
    }

    time= setTimeout(() => {
      context.isScollbarSport=false
    },300)
  }
  function hiddenScrollbar() {
    scrollbarVertical.style.display = 'none';
    scrollbarHorizontal.style.display = 'none';
  }
  function showScrollbar() {

    if (parseInt(tableBodyScrollHeight) > Math.round(viewportHeight)) {
      scrollbarVertical.style.display = 'block';
    } else {
      console.log(`tableBodyScrollHeight:${tableBodyScrollHeight}`,`viewportHeight${viewportHeight}`)
      scrollbarVertical.style.display = 'none';

    }
    if (parseInt(tableBodyScrollWidth) >  Math.round(viewportWidth)) {
      scrollbarHorizontal.style.display = 'block';
    } else {
      scrollbarHorizontal.style.display = 'none';

    }
  }
  function mousemove(event) {
    if (isDragging) {
      //纵向
      const mousePosition = event.clientY - startY;
      const thumbPosition = mousePosition - tableScroll.getBoundingClientRect().top;
      const scrollPercent = thumbPosition / (tableBodyRect.height - thumbHeight);
      const scrollAmount = (tableBodyScrollHeight - tableBodyRect.height) * scrollPercent;
      tableBody.scrollTop = scrollAmount;
    }
    if (isDragging_x) {
      //横向
      const mousePosition_x = event.clientX - startX;
      const thumbPosition_x = mousePosition_x - tableScroll.getBoundingClientRect().left;
      const scrollPercent_x = thumbPosition_x / (tableBodyRect.width - thumbWidth);
      tableBody.scrollLeft = (tableBodyScrollWidth - tableBodyRect.width) * scrollPercent_x;;
    }
  }
  // Handle the mouse up event on the document
  function mouseup() {
    isDragging = false;
    isDragging_x = false;
  }
  function thumbVerticalMousedown(event) {
    event.preventDefault()
    isDragging = true;
    startY = event.clientY - thumbVertical.getBoundingClientRect().top;
  }
  function thumbHorizontalMousedown(event) {
    event.preventDefault()
    isDragging_x = true;
    startX = event.clientX - thumbHorizontal.getBoundingClientRect().left;
  }


  function scrollbarClick(event) {

    event.preventDefault();
    if (event.currentTarget.classList.contains('scrollbar-vertical')) {
      const thumbPosition = event.layerY-(thumbHeight/2);
      const scrollPercent = thumbPosition / (viewportHeight - thumbHeight);
      tableBody.scrollTop = (tableBodyScrollHeight - viewportHeight) * scrollPercent;

    } else if (event.currentTarget.classList.contains('scrollbar-horizontal')) {
      const thumbPosition_x = event.layerX-(thumbWidth/2);
      const scrollPercent_x = thumbPosition_x / (viewportWidth - thumbWidth);
      tableBody.scrollLeft = (tableBodyScrollWidth - viewportWidth) * scrollPercent_x;
    }
  }


  let resize = debounce(function () {

     tableRect=context.$el.getBoundingClientRect();
    tableBodyRect = tableBody.getBoundingClientRect();

    tableBodyScrollHeight = tableBody.scrollHeight
    tableBodyScrollWidth = tableBody.scrollWidth

    console.log(`tableBodyScrollWidth:${tableBodyScrollWidth}`,`tableBodyScrollHeight${tableBodyScrollHeight}`)
    let minNumber=20
     ////////////////////////////////////垂直高度值
   viewportHeight =tableBodyRect.height ;
   thumbHeight = (viewportHeight / tableBodyScrollHeight) * viewportHeight;
   thumbHeight = minNumber>thumbHeight?minNumber:thumbHeight
   thumbVertical.style.height = thumbHeight + 'px';
  ////////////////////////////////////水平宽度值
   viewportWidth = tableBodyRect.width;
    thumbWidth = (viewportWidth / tableBodyScrollWidth) * viewportWidth;
    thumbWidth = minNumber>thumbWidth?minNumber:thumbWidth

    thumbHorizontal.style.width = thumbWidth + 'px';



  if(!context.tData.length){
    return hiddenScrollbar()
  } else {
    showScrollbar()
  }

    let { height } = tableRect;

    if (context.$refs.a_table && height && context.autoMaxHeight) {
      let parentStyles = window.getComputedStyle(context.$el.parentNode);
        let padding= parseFloat(parentStyles.paddingTop) - parseFloat(parentStyles.paddingBottom);
        if (context.pagination) {
          padding=padding+context.paginationHeight
        }
      let y = height -(context.showHeader ? headerHeight : 0)-padding;
      if (context.$refs.a_table?.scroll?.y) {
        context.$refs.a_table.scroll.y = y;
        }
      context.$refs.a_table.$forceUpdate();
      context.$nextTick(updateScrollbar)


    }
  },300);

  function start() {


    thumbVertical.addEventListener('mousedown', thumbVerticalMousedown);
    thumbHorizontal.addEventListener('mousedown', thumbHorizontalMousedown);
    document.addEventListener('mousemove', mousemove);
    document.addEventListener('mouseup', mouseup);
    tableBody.addEventListener('scroll', updateScrollbar);
    // window.addEventListener('resize', resize);
    tableBody.parentNode.appendChild(scrollbarHorizontal);
    tableBody.parentNode.appendChild(scrollbarVertical);
    scrollbarVertical.onclick = scrollbarClick
    scrollbarHorizontal.onclick = scrollbarClick

    context.$el.addEventListener('scrollResize', resize);




    resize()
  }

  start();

  function destroy(event) {

    // document.removeEventListener('resize', resize);
    context.$el.removeEventListener('scrollResize', resize);

    tableBody.removeEventListener('scroll', updateScrollbar);
    document.removeEventListener('mouseup', mouseup);
    document.removeEventListener('mousemove', mousemove);

    thumbVertical.removeEventListener('mousedown', thumbVerticalMousedown);
    thumbHorizontal.removeEventListener('mousedown', thumbHorizontalMousedown);

    let parent = scrollbarHorizontal.parentNode;
    parent?.removeChild(scrollbarHorizontal);
    parent = scrollbarVertical.parentNode
    parent?.removeChild(scrollbarVertical);
    // window.removeEventListener('destroyScroll', destroy);

  }

  return {
    element,
    resize,
    hiddenScrollbar,
    showScrollbar,
    destroy,
    start
  }

}


