<template>
  <div class="ju-kou-scene-page">
    <!-- 左侧视角切换按钮 -->
    <div class="view-switch-panel">
      <div class="view-switch-buttons">
        <el-button 
          :type="viewMode === 'thirdPerson' ? 'primary' : 'default'"
          @click="switchToThirdPerson"
          class="view-btn"
          :title="viewMode === 'thirdPerson' ? '当前：第三人称' : '切换到第三人称'"
        >
          <el-icon><View /></el-icon>
        </el-button>
        <el-button 
          :type="viewMode === 'firstPerson' ? 'primary' : 'default'"
          @click="switchToFirstPerson"
          class="view-btn"
          :title="viewMode === 'firstPerson' ? '当前：第一人称' : '切换到第一人称'"
        >
          <el-icon><User /></el-icon>
        </el-button>
      </div>
      <!-- 第一人称模式提示 -->
      <div v-if="viewMode === 'firstPerson'" class="mode-hint">
        <span>WASD移动 | ESC退出</span>
      </div>
    </div>

    <!-- 右侧闸门控制面板 -->
    <div class="right-panel">
      <GateControl
        ref="gateControlRef"
        :visible="showGateControl"
        :initial-position="gatePosition"
        @close="showGateControl = false"
        @position-change="handleGatePositionChange"
      />
    </div>

    <!-- 第一人称漫游控制器 -->
    <SuperMapFirstPerson
      ref="firstPersonRef"
      :viewer="viewer || window.viewer"
      :enabled="viewMode === 'firstPerson'"
      :initial-position="firstPersonPosition"
      :move-speed="5"
      :enable-collision="true"
      :enable-ground-follow="true"
      :show-instructions="true"
      @enter="onFirstPersonEnter"
      @exit="onFirstPersonExit"
      @position-change="onFirstPersonPositionChange"
    />

    <!-- 场景加载提示 -->
    <div v-if="isLoading" class="loading-overlay">
      <el-icon class="loading-icon"><Loading /></el-icon>
      <span>正在加载场景...</span>
    </div>
  </div>
</template>

<script>
import { ref, onMounted, onUnmounted, watch } from 'vue'
import { View, User, Loading } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import GateControl from '../gate-control/GateControl.vue'
import SuperMapFirstPerson from '../first-person/SuperMapFirstPerson.vue'
import { 
  loadJuKouScene, 
  unloadJuKouScene, 
  getController, 
  JuKouSceneConfig
} from '../../business-scenes/JuKouShuiZhaScene.js'

/**
 * 莒口水闸业务场景独立页面组件
 * 
 * 功能：
 * - 视角切换（第三人称/第一人称）
 * - 闸门启闭控制
 */
export default {
  name: 'JuKouShuiZhaPage',
  
  components: {
    GateControl,
    SuperMapFirstPerson,
    View,
    User,
    Loading
  },
  
  props: {
    viewer: {
      type: Object,
      default: null
    },
    visible: {
      type: Boolean,
      default: false
    }
  },
  
  emits: ['scene-loaded', 'scene-unloaded', 'view-change', 'gate-change'],
  
  setup(props, { emit }) {
    const isLoading = ref(false)
    const viewMode = ref('thirdPerson')
    const showGateControl = ref(true)
    const gatePosition = ref(0)
    
    const firstPersonPosition = ref({
      lon: 119.144412,
      lat: 25.866431,
      height: 35,
      heading: 0,
      pitch: -10
    })
    
    const gateControlRef = ref(null)
    const firstPersonRef = ref(null)
    
    let thirdPersonCameraState = null
    const isInitialized = ref(false)
    
    const loadScene = async () => {
      if (!props.viewer) {
        ElMessage.warning('Viewer 未初始化')
        return
      }
      
      isLoading.value = true
      
      try {
        await loadJuKouScene(props.viewer, {
          initialPosition: gatePosition.value,
          onGateNodesReady: (gateNames) => {
            if (gateControlRef.value) {
              gateControlRef.value.updateGateList(gateNames)
            }
            isInitialized.value = true
            emit('scene-loaded')
          },
          onSceneReady: (entity) => {
            console.log('✅ 场景已加载:', entity)
          },
          onError: (error) => {
            console.error('❌ 场景加载失败:', error)
            ElMessage.error('场景加载失败: ' + error)
            isLoading.value = false
          }
        })
        
        isLoading.value = false
      } catch (error) {
        console.error('加载场景异常:', error)
        ElMessage.error('加载场景异常')
        isLoading.value = false
      }
    }
    
    const unloadScene = () => {
      if (viewMode.value === 'firstPerson') {
        viewMode.value = 'thirdPerson'
      }
      
      unloadJuKouScene()
      isInitialized.value = false
      emit('scene-unloaded')
    }
    
    const switchToThirdPerson = () => {
      if (viewMode.value === 'thirdPerson') return
      
      viewMode.value = 'thirdPerson'
      restoreThirdPersonCamera()
      emit('view-change', { mode: 'thirdPerson' })
    }
    
    const switchToFirstPerson = () => {
      if (viewMode.value === 'firstPerson') return
      
      // 使用 props.viewer 或 window.viewer
      const viewer = props.viewer || window.viewer
      if (!viewer) {
        ElMessage.warning('Viewer 未初始化')
        return
      }
      
      console.log('🔄 切换到第一人称视角...')
      
      saveThirdPersonCamera(viewer)
      viewMode.value = 'firstPerson'
      emit('view-change', { mode: 'firstPerson', position: firstPersonPosition.value })
      ElMessage.success('已进入第一人称漫游，点击画面开始')
    }
    
    const saveThirdPersonCamera = (viewer) => {
      if (!viewer) return
      thirdPersonCameraState = {
        position: viewer.camera.position.clone(),
        heading: viewer.camera.heading,
        pitch: viewer.camera.pitch,
        roll: viewer.camera.roll
      }
      console.log('📸 第三人称相机状态已保存')
    }
    
    const restoreThirdPersonCamera = () => {
      const viewer = props.viewer || window.viewer
      if (!viewer || !thirdPersonCameraState) return
      
      viewer.camera.setView({
        destination: thirdPersonCameraState.position,
        orientation: {
          heading: thirdPersonCameraState.heading,
          pitch: thirdPersonCameraState.pitch,
          roll: thirdPersonCameraState.roll
        }
      })
      console.log('📸 第三人称相机状态已恢复')
    }
    
    const handleGatePositionChange = (data) => {
      const controller = getController()
      if (!controller || !controller.isInitialized) return
      
      if (typeof data === 'number') {
        gatePosition.value = data
        controller.setAllGatePosition(data)
      } else if (data && data.gateName && typeof data.position === 'number') {
        controller.setSingleGatePosition(data.gateName, data.position)
      }
      
      emit('gate-change', data)
    }
    
    const onFirstPersonEnter = () => {
      console.log('✅ 进入第一人称漫游模式')
    }
    
    const onFirstPersonExit = () => {
      viewMode.value = 'thirdPerson'
    }
    
    const onFirstPersonPositionChange = (position) => {}
    
    watch(() => props.visible, (newVal) => {
      if (newVal && !isInitialized.value) {
        loadScene()
      } else if (!newVal && isInitialized.value) {
        unloadScene()
      }
    }, { immediate: true })
    
    onUnmounted(() => {
      if (isInitialized.value) {
        unloadScene()
      }
    })
    
    return {
      isLoading,
      viewMode,
      showGateControl,
      gatePosition,
      firstPersonPosition,
      gateControlRef,
      firstPersonRef,
      loadScene,
      unloadScene,
      switchToThirdPerson,
      switchToFirstPerson,
      handleGatePositionChange,
      onFirstPersonEnter,
      onFirstPersonExit,
      onFirstPersonPositionChange
    }
  }
}
</script>

<style scoped>
.ju-kou-scene-page {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  pointer-events: none;
  z-index: 100;
}

/* 左侧视角切换面板 */
.view-switch-panel {
  position: absolute;
  top: 80px;
  left: 20px;
  display: flex;
  flex-direction: column;
  gap: 8px;
  pointer-events: auto;
}

/* 视角切换按钮组 */
.view-switch-buttons {
  display: flex;
  flex-direction: row;
  gap: 8px;
}

.view-btn {
  width: 44px;
  height: 44px;
  padding: 0;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
}

/* 右侧闸门控制面板需要可点击 */
.right-panel {
  position: absolute;
  top: 30px;
  right: 20px;
  pointer-events: auto;
}

/* 加载提示可点击 */
.loading-overlay {
  pointer-events: auto;
}

.view-btn .el-icon {
  font-size: 20px;
}

.mode-hint {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 2px;
  padding: 8px 10px;
  background: rgba(255, 255, 255, 0.95);
  border-radius: 6px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
  color: #d48806;
  font-size: 11px;
  text-align: center;
  line-height: 1.3;
}

/* 加载提示 */
.loading-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 15px;
  color: #fff;
  font-size: 16px;
  pointer-events: auto;
  z-index: 1000;
}

.loading-icon {
  font-size: 40px;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}
</style>