import { onMounted, onBeforeUnmount } from 'vue';

export function useWindowResize(callback) {

  let resizeTimer = null
  let handleResize = () => {
    clearTimeout(resizeTimer)
    resizeTimer = setTimeout(() => {
      callback()
    }, 200)
  }
  let observer = new ResizeObserver(handleResize);

  onMounted(() => {
    // 监听侧边栏宽度改变，右边图表要重新绘制
    observer.observe(document.querySelector('.sidebar-container'))
    window.addEventListener('resize', callback);
  });

  onBeforeUnmount(() => {
    if (observer) {
      observer.disconnect();
      clearTimeout(resizeTimer)
      resizeTimer = null
      observer = null
      handleResize = null
    }
    window.removeEventListener('resize', callback);
  });
}