// 创建一个水平滚动跟随函数
const createHorizontalScrollFollow = () => {
    // 获取表格相关元素
    const tableBody = document.querySelector('.ant-table-scroll .ant-table-body');
    const tableHeader = document.querySelector('.ant-table-scroll thead');
    const table = document.querySelector('.ant-table-scroll table');

    const width = table.offsetWidth - 2;

    // 滚动事件处理函数
    const scrollHandler = () => {
        const scrollLeft = -tableBody.scrollLeft;
        tableHeader.style.transform = `translateX(${scrollLeft}px)`;
    }

    // 绑定滚动事件
    const bindScroll = () => {
        tableBody.addEventListener('scroll', scrollHandler);
        const scrollLeft = -tableBody.scrollLeft;
        tableHeader.style.transform = `translateX(${scrollLeft}px)`;
        // 设置表头宽度与表格一致
        tableHeader.style.width = `${width}px`;
    }

    // 取消绑定滚动事件
    const unbindScroll = () => {
        tableBody.removeEventListener('scroll', scrollHandler);
        tableHeader.style.transform = 'initial';
        tableHeader.style.width = 'initial';
    }

    // 返回绑定和取消绑定滚动事件的方法
    return {
        bindScroll,
        unbindScroll,
        width,
    }
};

// 创建一个设置表头宽度的辅助函数
const createHeaderWidthSetter = (tableWidth) => {
    // 获取所有表头元素
    const headers = document.querySelectorAll('.header')&&document.querySelectorAll('.header');

    const cellWidth = document.querySelectorAll('.bodyCell')[0]&& document.querySelectorAll('.bodyCell')[0].getBoundingClientRect().width;

    // 设置表头宽度
    const setWidth = () => {
        for (let i = 0; i < headers.length; i++) {
            const header = headers[i];
            header.style.width = `${cellWidth}px`;
        }
    }

    // 清除表头宽度
    const clearWidth = () => {
        for (let i = 0; i < headers.length; i++) {
            const header = headers[i];
            header.style.width = 'initial';
        }
    }

    // 返回设置和清除表头宽度的方法
    return {
        setWidth,
        clearWidth,
    }
}

/**
 * 创建表格外层容器的边距设置器
 * @returns {Object} 边距设置器对象，包含设置边距和清除边距的方法
 */
const createTableContainerMarginSetter = () => {
    const tableContainerNode = document.querySelector('.table');
    const style = tableContainerNode.style;

    /**
     * 设置表格外层容器的边距
     */
    const setMargin = () => {
        style.marginLeft = '-10px';
        style.marginRight = '-10px';
    }

    /**
     * 清除表格外层容器的边距
     */
    const clearMargin = () => {
        style.marginLeft = 'initial';
        style.marginRight = 'initial';
    }

    return {
        setMargin,
        clearMargin,
    }
}

function throttle(func, delay) {  
  let lastCall = 0;  
  return function(...args) {  
    const now = new Date().getTime();  
    if (now - lastCall < delay) {  
      return;  
    }  
    lastCall = now;  
    return func.apply(this, args);  
  };  
}

/**
* 监听滚动事件，为指定元素的表头添加 sticky 类
* @param {string} element - 要监听滚动事件的元素选择器
*/
const sticky = (element) => {
    const scrollHelper = createHorizontalScrollFollow();
    const headerWidthSetter = createHeaderWidthSetter(scrollHelper.width);
    const tableWpMarginSetter = createTableContainerMarginSetter();
    const topComponentHeight = 52.36;

    //是否添加了sticky
    let isSticky = false;

    // 监听滚动事件
    document.querySelector(element).addEventListener('scroll', throttle(function (arg) {
        const tables = document.querySelectorAll('table'); // 获取页面中所有的表格
        const tableWp = document.querySelectorAll('.table')[0];

        const { scrollHeight, clientHeight, scrollTop } = arg.srcElement;
        const scrollDistanceFromBottom = scrollHeight - clientHeight - scrollTop;

        const rect = tables[0].getBoundingClientRect(); // 获取第一个表格的位置信息
        for (let i = 0; i < tables.length; i++) {
            const table = tables[i];
            const thead = table.querySelector('thead'); // 获取表格的表头元素
            if (rect.top <= topComponentHeight && rect.bottom >= thead.offsetHeight) {
                if (isSticky) return;
                // 当第一个表格的顶部超出视口顶部且底部超出表头高度时，为表头添加 sticky 类
                thead.classList.add('sticky');
                if (i == 1) {
                    thead.classList.add('index0');
                    isSticky = true;
                }
                if(scrollDistanceFromBottom < 30){
                    tableWp.classList.add('increase-content-height');
                }
                scrollHelper.bindScroll();
                headerWidthSetter.setWidth();
                tableWpMarginSetter.setMargin();
            } else {
                if (!isSticky) return;
                // 否则移除 sticky 类
                thead.classList.remove('sticky');
                tableWp.classList.remove('increase-content-height');
                if (i == 1) {
                    thead.classList.remove('index0');
                    isSticky = false;
                }
                scrollHelper.unbindScroll();
                headerWidthSetter.clearWidth();
                tableWpMarginSetter.clearMargin();
            }
        }
    },0));
}

export default sticky;