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

/**
 * 屏幕宽度管理composable
 */
export function useScreenWidth() {
  // 当前屏幕宽度
  const screenWidth = ref(0)
  
  /**
   * 获取当前屏幕宽度
   */
  const updateScreenWidth = () => {
    // #ifdef H5
    screenWidth.value = window.innerWidth
    // #endif
    
    // #ifdef MP-WEIXIN || APP-PLUS
    const systemInfo = uni.getSystemInfoSync()
    screenWidth.value = systemInfo.screenWidth
    // #endif
  }
  
  /**
   * 监听屏幕宽度变化
   */
  const handleResize = () => {
    updateScreenWidth()
  }
  
  // 初始化和清理
  onMounted(() => {
    updateScreenWidth()
    
    // #ifdef H5
    window.addEventListener('resize', handleResize)
    window.addEventListener('orientationchange', handleResize)
    // #endif
  })
  
  onUnmounted(() => {
    // #ifdef H5
    window.removeEventListener('resize', handleResize)
    window.removeEventListener('orientationchange', handleResize)
    // #endif
  })
  
  return {
    screenWidth,
    updateScreenWidth,
  }
}
