
import { ref, onMounted, onUnmounted } from 'vue'

export function useKeyboardScroll() {
  const scrollPosition = ref(0)
  const keyboardHeight = ref(0)

  let keyboardShowHandler = null
  let keyboardHideHandler = null

  // 保存当前滚动位置
  const saveScrollPosition = () => {
    // 获取当前页面的滚动位置
    const pages = getCurrentPages()
    if (pages.length > 0) {
      scrollPosition.value = pages[pages.length - 1].scrollTop || 0
    }
  }

  // 恢复滚动位置
  const restoreScrollPosition = () => {
    // 延迟恢复，确保页面布局已更新
    setTimeout(() => {
      const pages = getCurrentPages()
      if (pages.length > 0) {
        const page = pages[pages.length - 1]
        if (page && typeof page.setData === 'function') {
          page.setData({
            scrollTop: scrollPosition.value
          })
        }
      }
    }, 100)
  }

  onMounted(() => {
    // 监听键盘显示事件
    keyboardShowHandler = (e) => {
      keyboardHeight.value = e.height
      saveScrollPosition()
    }

    // 监听键盘隐藏事件
    keyboardHideHandler = () => {
      keyboardHeight.value = 0
      restoreScrollPosition()
    }

    // 绑定事件监听器
    uni.onKeyboardHeightChange(keyboardShowHandler)
    uni.onKeyboardHeightChange(keyboardHideHandler)
  })

  onUnmounted(() => {
    // 清理事件监听器
    if (keyboardShowHandler) {
      uni.offKeyboardHeightChange(keyboardShowHandler)
    }
    if (keyboardHideHandler) {
      uni.offKeyboardHeightChange(keyboardHideHandler)
    }
  })

  return {
    keyboardHeight,
    scrollPosition,
    restoreScrollPosition
  }
}
