<template>
  <div>
    <el-affix :offset="affixOffset">
      <el-anchor
        :direction="direction"
        :type="type"
        :offset="anchorOffset"
        @click="handleAnchorClick"
      >
        <el-anchor-link
          v-for="item in anchorList"
          :href="'#' + item.title"
          :title="item.name"
          @click="e => handleLinkClick(e, item.title)"
        />
      </el-anchor>
    </el-affix>
  </div>
</template>

<script setup>
import { ref, onMounted, getCurrentInstance } from 'vue'

const props = defineProps({
  direction: {
    type: String,
    default: 'vertical'
  },
  type: {
    type: String,
    default: 'default'
  },
  anchorOffset: {
    type: Number,
    default: 30
  },
  affixOffset: {
    type: Number,
    default: 60
  },
  anchorList: {
    type: Array,
    default: () => {
      return []
    }
  },
  // 新增：滚动容器的选择器
  scrollContainerSelector: {
    type: String,
    default: ''
  },
  // 新增：滚动到元素时额外的偏移量
  scrollOffset: {
    type: Number,
    default: 0
  },
  domIndex: {
    type: Number,
    default: 1
  }
})

const emit = defineEmits(['anchor-click'])

// 处理锚点点击
const handleAnchorClick = e => {
  // 阻止默认的锚点跳转
  e.preventDefault()
}

// 处理链接点击
const handleLinkClick = (e, anchorId) => {
  e.preventDefault()
  e.stopPropagation()

  emit('anchor-click', anchorId)

  // 延迟执行滚动，确保 DOM 已经更新
  setTimeout(() => {
    scrollToAnchor(anchorId)
  }, 50)
}

// 滚动到锚点
const scrollToAnchor = anchorId => {
  const targetElement = document.getElementById(anchorId)
  if (!targetElement) return

  let scrollContainer
  if (props.scrollContainerSelector) {
    scrollContainer = document.querySelectorAll(props.scrollContainerSelector)
  }
  if (scrollContainer.length > 0) {
    // 计算在容器内的相对位置
    const containerRect = scrollContainer[props.domIndex].getBoundingClientRect()
    const targetRect = targetElement.getBoundingClientRect()

    // 计算滚动位置
    const scrollTop =
      targetRect.top -
      containerRect.top +
      scrollContainer[props.domIndex].scrollTop -
      props.scrollOffset
    // 平滑滚动
    scrollContainer[props.domIndex].scrollTo({
      top: scrollTop,
      behavior: 'smooth'
    })
  } else {
    // 如果没有指定容器，使用默认滚动
    targetElement.scrollIntoView({
      behavior: 'smooth',
      block: 'start'
    })
  }
}

// 暴露方法给父组件
defineExpose({
  scrollToAnchor
})
</script>
