
import { Directive, nextTick } from 'vue'
/**
 * 监听el-table表格数据变化滚动到底部-指令
 */
export const tableScrollBottom: Directive = {
    mounted(el) {
        const $el = el.querySelector('.el-scrollbar__wrap');//需要滚动的容器
        const bodyEl = el.querySelector('.el-table__body tbody');//el-table表格容器
        // 创建观察器对象
        el._observer__ = new MutationObserver((mutationsList) => {
            // 遍历所有变动
            for (const mutation of mutationsList) {
                if (mutation.type === 'childList') {
                    // 监听到有新节点加入，说明表格中有新数据
                    const tableEl = el.querySelector('.el-table__body');
                    if (!tableEl) {
                        continue;
                    }
                    if (tableEl.clientHeight === 0) {
                        // 隐藏弹窗清除监听
                        if (el.__my_observer__) {
                            el._observer__.disconnect()
                            el._observer__ = null
                            delete el.__my_observer__
                        }
                        continue;
                    }
                    // console.log(tableEl, ":tableEl", tableEl.clientHeight);
                    nextTick(() => {
                        // 平滑滚动到底部
                        $el.style.scrollBehavior = 'smooth';
                        $el.scrollTop = tableEl.clientHeight
                    })
                }
            }
        });
        // 开始监听表格元素的变化
        el._observer__.observe(bodyEl, { childList: true });
    },
    unmounted(el) {
        // 销毁观察器对象
        if (el.__my_observer__) {
            el._observer__.disconnect()
            el._observer__ = null
            delete el.__my_observer__
        }
    },
    // 手动滚动到底部触发的事件
    // mounted(el, binding) {
    //     const fn = binding.value;
    //     el._scroll_bottom_fn = fn;
    //     const $el = el.querySelector('.el-scrollbar__wrap');
    //     $el.addEventListener('scroll', scrollHandler);
    //     function scrollHandler() {
    //         // 上取整数
    //         const currentScroll = Math.ceil($el.scrollHeight) - Math.ceil($el.scrollTop)
    //         if (Math.ceil(currentScroll) === Math.ceil($el.clientHeight)) {
    //             nextTick(() => fn());
    //         }
    //     }
    // },
    // unmounted(el) {
    //     const $el = el.querySelector('.el-scrollbar__wrap');
    //     $el.addEventListener('scroll', el._scroll_bottom_fn);
    //     delete el._scroll_bottom_fn;
    // },
}