<template>
  <div class="vslam-preview-container">
    <!-- 顶部工具栏 -->
    <!-- <VSlamToolbar 
      :map-name="mapName"
      :running="runningState"
      :robot-position="robotPosition"
      :robot-visible="robotVisiable"
      @refresh="handleRefresh"
      @back="handleBack"
    /> -->

    <!-- 主内容区域 -->
    <div class="vslam-main-content">
      <!-- 3D 渲染视图 -->
      <VSlamView 
        ref="vslamView"
        :map-name="mapName"
        :current-view="currentView"
        :boot-mode="bootModeIsCheck"
        :replay-state="replayState"
        :ui-config="uiConfig"
      />

      <!-- 右侧控制面板 -->
      <VSlamControlPanel 
        v-model="controlPanelVisible"
        :current-view="currentView"
        :boot-mode="bootModeIsCheck"
        :running="runningState"
        :manual-control-visible="btnsVisiable.controlVisiable"
        :realtime-video-visible="btnsVisiable.cameraVisiable"
        @view-change="handleViewChange"
        @boot-toggle="handleBootToggle"
        @replay="handleReplay"
        @fullscreen="handleFullscreen"
      />
      
      <!-- 构建进度浮动卡片 -->
      <BuildingProgressCard :map-name="mapName" />
    </div>

    <!-- MQTT 通信组件 -->
    <MqttComp 
      ref="mqtt" 
      :topics="mqttTopics" 
      @message-received="handleMqttMessage" 
    />

    <!-- 全屏遮罩 -->
    <div v-if="fullScreen.state" class="fullscreen-overlay">
      <el-button 
        type="info" 
        icon="el-icon-close" 
        circle 
        class="exit-fullscreen-btn"
        @click="exitFullscreen"
      />
    </div>
  </div>
</template>

<script>
import { mapState, mapMutations, mapActions } from 'vuex'
import VSlamToolbar from './components/VSlamToolbar'
import VSlamView from './components/VSlamView'
import VSlamControlPanel from './components/VSlamControlPanel'
import BuildingProgressCard from './components/BuildingProgressCard'
import MqttComp from '@/components/Mqtt/mqttComp.vue'

export default {
  name: 'VSlamPreview',
  components: {
    VSlamToolbar,
    VSlamView,
    VSlamControlPanel,
    BuildingProgressCard,
    MqttComp
  },
  data() {
    return {
      mapName: '',
      controlPanelVisible: true,
      mqttTopics: []
    }
  },
  computed: {
    ...mapState('vslam', [
      'currentView',
      'bootModeIsCheck',
      'runningState',
      'robotPosition',
      'robotVisiable',
      'replayState',
      'fullScreen',
      'uiConfig',
      'btnsVisiable'
    ])
  },
  created() {
    // 从路由参数获取地图名称
    this.mapName = this.$route.params.mapName
    
    if (!this.mapName) {
      this.$message.error('地图名称参数缺失')
      this.$router.push('/map/list')
      return
    }
    
    // 初始化 Vuex Store
    this.updateMapName(this.mapName)
    
    // 设置 MQTT 主题
    this.mqttTopics = [
      { topic: `${this.$mqttPrefix}/exploration/localization/pose` },
      { topic: `${this.$mqttPrefix}/visualization/object` },
      { topic: `${this.$mqttPrefix}/exploration/planning/trajectory` },
      { topic: `${this.$mqttPrefix}/ability/function/action/exec/state` }
    ]
  },
  beforeDestroy() {
    // 清理状态
    this.vslamClear()
  },
  methods: {
    ...mapMutations('vslam', [
      'SET_ROBOT_POSITION',
      'SET_ROBOT_VISIABLE'
    ]),
    ...mapActions('vslam', [
      'updateMapName',
      'setCurrentView',
      'setBootMode',
      'setReplayState',
      'setFullScreen',
      'vslamClear'
    ]),
    
    /**
     * 处理 MQTT 消息
     */
    handleMqttMessage(topic, message) {
      try {
        // 检查消息是否为空
        if (!message || message === 'undefined') {
          console.warn('[MQTT] 收到空消息:', topic)
          return
        }
        
        const data = JSON.parse(message)
        
        if (topic.endsWith('/localization/pose')) {
          this.handlePoseUpdate(data)
        } else if (topic.endsWith('/visualization/object')) {
          this.handleVisualizationObject(data)
        } else if (topic.endsWith('/planning/trajectory')) {
          this.handlePlanningTrajectory(data)
        } else if (topic.endsWith('/exec/state')) {
          this.handleActionExecState(data)
        }
      } catch (err) {
        console.error('[MQTT] 消息解析失败:', { topic, message, error: err.message })
      }
    },
    
    /**
     * 处理机器人位姿更新
     */
    handlePoseUpdate(data) {
      if (!data.args || !data.args[0] || !data.args[0].pose) return
      
      const pose = data.args[0].pose
      const modelOffset = this.uiConfig.offset || [0, 0, 0]
      
      // 更新 Vuex 中的位置信息
      if (pose.lidar && pose.lidar.length > 2) {
        this.SET_ROBOT_POSITION({
          x: pose.lidar[0].toFixed(2),
          y: pose.lidar[1].toFixed(2),
          z: pose.lidar[2].toFixed(2)
        })
      }
      
      // 通知 VSlamView 更新机器人位姿
      if (this.$refs.vslamView) {
        const robotPosition = {
          x: pose.xyz[0] + modelOffset[0],
          y: pose.xyz[1] + modelOffset[1],
          z: pose.xyz[2] + modelOffset[2]
        }
        const yaw = pose.rpy[2]
        
        this.$refs.vslamView.updateRobotPose(robotPosition, yaw)
      }
    },
    
    /**
     * 处理可视化对象显示
     */
    handleVisualizationObject(data) {
      if (this.$refs.vslamView) {
        this.$refs.vslamView.updateVisualizationObjects(data)
      }
    },
    
    /**
     * 处理规划轨迹显示
     */
    handlePlanningTrajectory(data) {
      if (this.$refs.vslamView) {
        this.$refs.vslamView.updatePlanningTrajectory(data)
      }
    },
    
    /**
     * 处理动作执行状态（用于创建子地图等功能）
     */
    handleActionExecState(data) {
      // 预留接口，后续实现
      console.log('Action exec state:', data)
    },
    
    /**
     * 处理视角切换
     */
    handleViewChange(view) {
      this.setCurrentView(view)
    },
    
    /**
     * 处理引导模式切换
     */
    handleBootToggle(enabled) {
      this.setBootMode(enabled)
      
      // 通过 MQTT 通知后端
      const topic = `${this.$mqttPrefix}/param/setup`
      const payload = {
        nav_explore: {
          auto_mode: !enabled
        }
      }
      this.$refs.mqtt.publish(topic, JSON.stringify(payload))
    },
    
    /**
     * 处理回放
     */
    handleReplay() {
      this.setReplayState(this.replayState + 1)
    },
    
    /**
     * 处理全屏
     */
    handleFullscreen(type) {
      if (type === 'webpage') {
        this.setFullScreen({ name: 'webpage', state: true })
      } else if (type === 'window') {
        this.requestFullscreen()
        this.setFullScreen({ name: 'window', state: true })
      }
    },
    
    /**
     * 请求浏览器全屏
     */
    requestFullscreen() {
      const el = document.documentElement
      if (el.requestFullscreen) {
        el.requestFullscreen()
      } else if (el.webkitRequestFullScreen) {
        el.webkitRequestFullScreen()
      } else if (el.mozRequestFullScreen) {
        el.mozRequestFullScreen()
      } else if (el.msRequestFullscreen) {
        el.msRequestFullscreen()
      }
    },
    
    /**
     * 退出全屏
     */
    exitFullscreen() {
      if (this.fullScreen.name === 'window') {
        if (document.exitFullscreen) {
          document.exitFullscreen()
        } else if (document.webkitCancelFullScreen) {
          document.webkitCancelFullScreen()
        } else if (document.mozCancelFullScreen) {
          document.mozCancelFullScreen()
        } else if (document.msExitFullscreen) {
          document.msExitFullscreen()
        }
      }
      this.setFullScreen({ name: 'webPage', state: false })
    },
    
    /**
     * 刷新页面
     */
    handleRefresh() {
      this.$refs.vslamView?.refresh()
    },
    
    /**
     * 返回地图列表
     */
    handleBack() {
      this.$router.push('/map/list')
    }
  }
}
</script>

<style lang="scss" scoped>
.vslam-preview-container {
  width: 100%;
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: #000;
  overflow: hidden;
}

.vslam-main-content {
  flex: 1;
  position: relative;
  overflow: hidden;
}

.fullscreen-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 9999;
  background: #000;
}

.exit-fullscreen-btn {
  position: absolute;
  top: 20px;
  right: 20px;
  z-index: 10000;
}
</style>

