import { ref } from 'vue'
import useMapStore from '@/map/stores/mapStore'

/**
 * @function useMapViewSnapshot
 * @description 提供捕获与恢复地图视角的组合式函数，适用于在页面间切换时保持用户视角。
 * @returns {{
 *  viewSnapshot: import('vue').Ref<Record<string, number>|null>,
 *  captureViewSnapshot: (force?: boolean) => Record<string, number>|null,
 *  restoreViewSnapshot: (options?: { duration?: number, clearAfterRestore?: boolean }) => Promise<boolean>,
 *  clearViewSnapshot: () => void
 * }}
 */
export function useMapViewSnapshot() {
  const mapStore = useMapStore()
  const viewSnapshot = ref(null)

  /**
   * @function captureViewSnapshot
   * @description 捕获当前地图视角，可选择是否强制覆盖已有快照。
   * @param {boolean} [force=false] 是否强制覆盖已有快照
   * @returns {Record<string, number>|null} 记录的视角信息
   */
  const captureViewSnapshot = (force = false) => {
    if (!force && viewSnapshot.value) {
      return viewSnapshot.value
    }

    if (!mapStore.isReady()) {
      return null
    }

    try {
      const { camera } = mapStore.services()
      const currentView = camera.getCurrentView()
      if (currentView) {
        viewSnapshot.value = { ...currentView }
      }
      return viewSnapshot.value
    } catch (error) {
      console.warn('捕获地图视角失败:', error)
      return null
    }
  }

  /**
   * @function restoreViewSnapshot
   * @description 恢复此前捕获的地图视角，默认恢复后清空快照。
   * @param {{ duration?: number, clearAfterRestore?: boolean }} [options] 恢复参数
   * @returns {Promise<boolean>} 是否成功发起恢复
   */
  const restoreViewSnapshot = async (options = {}) => {
    if (!viewSnapshot.value || !mapStore.isReady()) {
      return false
    }

    const { duration = 1, clearAfterRestore = true } = options
    const snapshot = viewSnapshot.value

    try {
      const { camera } = mapStore.services()
      await camera.flyTo({
        lon: snapshot.lon,
        lat: snapshot.lat,
        height: snapshot.height,
        heading: snapshot.heading ?? 0,
        pitch: snapshot.pitch ?? -45,
        roll: snapshot.roll ?? 0,
        duration
      })
      if (clearAfterRestore) {
        viewSnapshot.value = null
      }
      return true
    } catch (error) {
      console.warn('恢复地图视角失败:', error)
      return false
    }
  }

  /**
   * @function clearViewSnapshot
   * @description 主动清除已缓存的地图视角快照。
   */
  const clearViewSnapshot = () => {
    viewSnapshot.value = null
  }

  return {
    viewSnapshot,
    captureViewSnapshot,
    restoreViewSnapshot,
    clearViewSnapshot
  }
}

export default useMapViewSnapshot
