<template>
  <teleport to="body">
    <!-- 遮罩层 -->
    <Transition name="drawer-fade">
      <div
        v-if="modelValue"
        class="fixed top-0 left-0 w-screen h-screen bg-black/50 z-[1]"
        :style="`--transition-duration: ${props.transitionDuration}ms;`"
        @click="closeDrawer"
      ></div>
    </Transition>

    <!-- 抽屉面板 -->
    <Transition name="drawer-slide" @after-leave="onTransitionEnd">
      <div
        v-if="modelValue"
        class="fixed bottom-0 left-0 z-[2] flex w-screen flex-col rounded-t-lg bg-white shadow-lg"
        :style="`--transition-duration: ${props.transitionDuration}ms;${panelStyle}`"
      >
        <header class="flex-shrink-0">
          <slot name="header"></slot>
        </header>
        <main class="flex-grow overflow-y-auto max-h-[55vh]">
          <slot></slot>
        </main>
      </div>
    </Transition>
  </teleport>
</template>

<script lang="ts" setup>

const props = defineProps({
  modelValue: {
    type: Boolean,
    required: true,
  },
  transitionDuration: {
    type: Number,
    default: 250,
  },
  panelStyle:{
    type:String,
    default: ''
  }
});

const emit = defineEmits(['update:modelValue']);

const closeDrawer = () => {
  emit('update:modelValue', false);
};


// 防止页面滚动
watch(
  () => props.modelValue,
  (isOpen) => {
    document.body.style.overflow = isOpen ? 'hidden' : '';
  }
);

// 组件卸载时恢复滚动
onUnmounted(() => {
  document.body.style.overflow = '';
});

// 过渡动画结束后，可以执行一些清理操作
const onTransitionEnd = () => {
  // console.log('Transition ended');
};
</script>

<style lang="scss" scoped>
/* Transitions are defined here to use the dynamic --transition-duration variable */
.drawer-fade-enter-active,
.drawer-fade-leave-active {
  transition: opacity var(--transition-duration) ease;
}

.drawer-fade-enter-from,
.drawer-fade-leave-to {
  opacity: 0;
}

.drawer-slide-enter-active,
.drawer-slide-leave-active {
  transition: transform var(--transition-duration) ease;
}

.drawer-slide-enter-from,
.drawer-slide-leave-to {
  transform: translateY(100%);
}
</style>