<template>
  <div class="my-layout__main">
    <el-scrollbar v-if="scroll" ref="scrollbarRef" class="my-layout__wrapper" @scroll="onScroll">
      <slot></slot>
    </el-scrollbar>
    <div v-else class="my-layout__wrapper">
      <slot></slot>
    </div>
  </div>
</template>
<script setup>
import { ref } from 'vue';
const { scroll } = defineProps({ scroll: { type: Boolean, default: true } })
const scrollbarRef = ref()
const position = ref({ left: 0, top: 0 })
function scrollTo(top, duration = 0) {
  if (duration === 0) {
    scrollbarRef.value ? scrollbarRef.value.setScrollTop(top) : ''
  } else {
    animateHeight(position.value.top, top, duration)
  }
}
function scrollToBottom() {
  scrollTo(99999999)
}

function onScroll({ scrollTop: top, scrollLeft: left }) {
  position.value = { top, left }
}
function getPosition() {
  return position.value
}

function animateHeight(startHeight, endHeight, duration) {
  const startTime = performance.now(); // 记录动画开始的时间

  function updateHeight(currentTime) {

    const timeElapsed = currentTime - startTime;
    const progress = Math.min(timeElapsed / duration, 1); // 计算动画进度

    // 计算当前的高度
    const currentHeight = startHeight + (endHeight - startHeight) * progress;

    // 设置元素的当前高度
    scrollbarRef.value.setScrollTop(currentHeight)
    if (progress < 1) {
      // 如果进度不到 100%，继续调用动画
      requestAnimationFrame(updateHeight);
    }
  }

  // 启动动画
  requestAnimationFrame(updateHeight);
}
defineExpose({
  scrollToBottom,
  scrollTo,
  getPosition

});
</script>