import { ref, onUnmounted } from 'vue'
import * as Cesium from 'cesium'

/**
 * 双 Viewer 管理 Composable
 * 创建和管理两个独立的 Cesium Viewer，用于并排对比显示
 *
 * 参考：WuRenJi 项目的双地图实现
 */
export function useDualViewers() {
  /** @type {import('vue').Ref<Cesium.Viewer | null>} */
  const leftViewer = ref(null)

  /** @type {import('vue').Ref<Cesium.Viewer | null>} */
  const rightViewer = ref(null)

  /** 是否启用相机同步 */
  let cameraSyncEnabled = false

  /** 相机同步监听器的移除函数 */
  let removeCameraSync = null

  /**
   * 初始化左侧 Viewer
   * @param {string} containerId - 容器 DOM ID
   * @param {Object} options - Cesium.Viewer 配置选项
   * @returns {Cesium.Viewer}
   */
  const initLeftViewer = (containerId, options = {}) => {
    if (leftViewer.value) {
      console.warn('[useDualViewers] 左侧 Viewer 已存在')
      return leftViewer.value
    }

    console.log('[useDualViewers] 初始化左侧 Viewer...')

    const defaultOptions = {
      animation: false,
      baseLayerPicker: false,
      fullscreenButton: false,
      geocoder: false,
      homeButton: false,
      infoBox: false,
      sceneModePicker: false,
      selectionIndicator: false,
      timeline: false,
      navigationHelpButton: false,
      scene3DOnly: true,
      requestRenderMode: true, // 启用按需渲染
      maximumRenderTimeChange: Infinity
    }

    leftViewer.value = new Cesium.Viewer(containerId, {
      ...defaultOptions,
      ...options
    })

    console.log('[useDualViewers] 左侧 Viewer 初始化完成')
    return leftViewer.value
  }

  /**
   * 初始化右侧 Viewer
   * @param {string} containerId - 容器 DOM ID
   * @param {Object} options - Cesium.Viewer 配置选项
   * @returns {Cesium.Viewer}
   */
  const initRightViewer = (containerId, options = {}) => {
    if (rightViewer.value) {
      console.warn('[useDualViewers] 右侧 Viewer 已存在')
      return rightViewer.value
    }

    console.log('[useDualViewers] 初始化右侧 Viewer...')

    const defaultOptions = {
      animation: false,
      baseLayerPicker: false,
      fullscreenButton: false,
      geocoder: false,
      homeButton: false,
      infoBox: false,
      sceneModePicker: false,
      selectionIndicator: false,
      timeline: false,
      navigationHelpButton: false,
      scene3DOnly: true,
      requestRenderMode: true, // 启用按需渲染
      maximumRenderTimeChange: Infinity
    }

    rightViewer.value = new Cesium.Viewer(containerId, {
      ...defaultOptions,
      ...options
    })

    console.log('[useDualViewers] 右侧 Viewer 初始化完成')
    return rightViewer.value
  }

  /**
   * 设置相机到指定位置
   * @param {Cesium.Viewer} viewer
   * @param {Object} view - 相机视图配置
   */
  const setCameraView = (viewer, view) => {
    if (!viewer) return

    viewer.camera.setView({
      destination: Cesium.Cartesian3.fromDegrees(
        view.lon || 106.5516,
        view.lat || 29.5630,
        view.height || 5000
      ),
      orientation: {
        heading: Cesium.Math.toRadians(view.heading || 0),
        pitch: Cesium.Math.toRadians(view.pitch || -45),
        roll: view.roll || 0
      }
    })
  }

  /**
   * 启用相机同步
   * 左侧相机移动时，右侧相机自动跟随
   */
  const enableCameraSync = () => {
    if (!leftViewer.value || !rightViewer.value) {
      console.warn('[useDualViewers] 无法启用相机同步：Viewer 未初始化')
      return
    }

    if (cameraSyncEnabled) {
      console.warn('[useDualViewers] 相机同步已启用')
      return
    }

    console.log('[useDualViewers] 启用相机同步')

    // 监听左侧相机变化
    const syncHandler = () => {
      if (!rightViewer.value) return

      const leftCamera = leftViewer.value.camera
      const rightCamera = rightViewer.value.camera

      // 同步右侧相机到左侧相机位置
      rightCamera.setView({
        destination: leftCamera.position.clone(),
        orientation: {
          heading: leftCamera.heading,
          pitch: leftCamera.pitch,
          roll: leftCamera.roll
        }
      })
    }

    leftViewer.value.camera.changed.addEventListener(syncHandler)
    cameraSyncEnabled = true

    // 保存移除函数
    removeCameraSync = () => {
      if (leftViewer.value) {
        leftViewer.value.camera.changed.removeEventListener(syncHandler)
      }
      cameraSyncEnabled = false
      console.log('[useDualViewers] 相机同步已禁用')
    }
  }

  /**
   * 禁用相机同步
   */
  const disableCameraSync = () => {
    if (removeCameraSync) {
      removeCameraSync()
      removeCameraSync = null
    }
  }

  /**
   * 调整 Viewer 大小（在容器尺寸变化时调用）
   */
  const resizeViewers = () => {
    if (leftViewer.value?.canvas) {
      leftViewer.value.resize()
    }
    if (rightViewer.value?.canvas) {
      rightViewer.value.resize()
      // 触发相机变化事件，确保同步
      if (cameraSyncEnabled) {
        rightViewer.value.camera.changed.raiseEvent()
      }
    }
  }

  /**
   * 销毁 Viewer
   */
  const destroyViewers = () => {
    console.log('[useDualViewers] 销毁 Viewers...')

    disableCameraSync()

    if (leftViewer.value) {
      leftViewer.value.destroy()
      leftViewer.value = null
    }

    if (rightViewer.value) {
      rightViewer.value.destroy()
      rightViewer.value = null
    }

    console.log('[useDualViewers] Viewers 已销毁')
  }

  // 组件卸载时自动清理
  onUnmounted(() => {
    destroyViewers()
  })

  return {
    leftViewer,
    rightViewer,
    initLeftViewer,
    initRightViewer,
    setCameraView,
    enableCameraSync,
    disableCameraSync,
    resizeViewers,
    destroyViewers
  }
}

export default useDualViewers
