<template>
  <view class="visual-monitoring-page">
    <!-- <view class="fixed-header">
      <text class="header-title">移动式检修车间</text>
    </view> -->
    
    <!-- 内容区域 -->
    <view class="tabbar-content">
      <!-- <demo /> -->
      <view class="no-data-container" v-if="!ezstate">
        <!-- <view class="no-data-icon">📹</view>
        <text class="no-data-text">暂无监控数据</text> -->
      </view>

      <!-- 视频播放区域 -->
      <view v-else-if="ezstate" class="video-wrapper">
        <!-- H5平台使用iframe -->
        <!-- #ifdef H5 -->
        <iframe 
          :src="iframeUrl" 
          class="video-iframe"
          frameborder="0"
          allow="autoplay; fullscreen"
        ></iframe>
        <!-- #endif -->
        
        <!-- APP平台使用web-view -->
        <!-- #ifdef APP-PLUS -->
        <web-view 
          :src="webviewUrl"
          @message="handleWebviewMessage"
          class="video-webview"
        ></web-view>
        <!-- #endif -->
      </view>
      
      
      <!-- API测试按钮 -->
      <!-- <view class="test-section" v-if="!ezstate">
        <button @click="checkDevice" class="test-btn">检查设备状态</button>
        <button @click="toggleDebug" class="test-btn">
          {{ debugMode ? '关闭调试' : '开启调试' }}
        </button>
        <button @click="getVideoData" class="test-btn">启动视频播放</button>
      </view> -->

    </view>
  </view>
</template>

<script>
import tokenManager from '@/utils/ezvizTokenManager.js'
import deviceChecker from '@/utils/ezvizDeviceChecker.js'

export default {
  data() {
    return {
      ezstate: false,
      debugMode: true,
      videoLoaded: false,
      isRecording: false,
      isPlaying: true,
      // 播放器URL配置
      iframeUrl: '', // H5平台使用
      webviewUrl: '', // APP平台使用
      // 设备配置
      playUrl: "ezopen://open.ys7.com/GE9147469/1.hd.live",
      accessToken: '',
    }
  },
  onLoad() {
    console.log('视觉监控页面加载')
    this.getVideoData()

  },
  onShow() {
    console.log('📱 视觉监控页面显示，触发页面更新')
    // 可以在这里添加重新连接摄像头等逻辑
    this.getVideoData()
  },
  onUnload() {
    console.log('📱 视觉监控页面卸载，停止播放器')
    this.stopVideoPlayer()
  },
  onHide() {
    console.log('📱 视觉监控页面隐藏，停止播放器')
    this.stopVideoPlayer()
  },
  methods: {
    // 切换调试模式
    toggleDebug() {
      this.debugMode = !this.debugMode
      console.log('调试模式:', this.debugMode ? '开启' : '关闭')
      
      uni.showToast({
        title: this.debugMode ? '调试模式已开启' : '调试模式已关闭',
        icon: 'success',
        duration: 1500
      })
    },


    // 处理播放状态变化（由播放器组件触发）
    handlePlayStateChange(isPlaying) {
      console.log('📡 播放状态变化:', isPlaying ? '播放中' : '已暂停')
      this.isPlaying = isPlaying
    },

    // 检查设备状态
    async checkDevice() {
      console.log('🔍 开始检查设备状态...')
      
      const playUrl = "ezopen://open.ys7.com/GE9147469/1.hd.live"
      
      uni.showLoading({
        title: '检查设备中...'
      })
      
      try {
        const result = await deviceChecker.comprehensiveCheck(playUrl)
        
        uni.hideLoading()
        
        if (result.success) {
          const status = result.isOnline ? '在线' : '离线'
          const message = `设备 ${result.deviceSerial}: ${status}\n设备名: ${result.device.deviceName || '未知'}`
          
          uni.showModal({
            title: '设备检查结果',
            content: message,
            showCancel: false
          })
          
          console.log('✅ 设备检查结果:', result)
        } else {
          uni.showModal({
            title: '设备检查失败',
            content: result.error,
            showCancel: false
          })
          console.error('❌ 设备检查失败:', result.error)
        }
      } catch (error) {
        uni.hideLoading()
        uni.showToast({
          title: '检查异常',
          icon: 'error',
          duration: 3000
        })
        console.error('设备检查异常:', error)
      }
    },

    async getVideoData() {
      console.log('🎬 开始初始化视频播放器...')
      
      try {
        // 使用TokenManager自动获取AccessToken
        try {
          console.log('🔑 开始获取AccessToken...')
          this.accessToken = await tokenManager.getValidAccessToken()
          console.log('✅ AccessToken获取成功:', this.accessToken.substring(0, 20) + '...')
        } catch (error) {
          console.error('❌ 自动获取AccessToken失败:', error)
          
          // 使用备用token
          console.log('🔄 使用备用AccessToken')
          this.accessToken = "at.4q22023n62a4knwpcx1yxavda1sfqfo5-3ns0ca16sb-1wgwwc3-aj2mctqys"
          
          uni.showToast({
            title: 'AccessToken自动获取失败，使用备用token',
            icon: 'none',
            duration: 3000
          })
        }

        // 构建播放器URL
        const token = encodeURIComponent(this.accessToken)
        const url = encodeURIComponent(this.playUrl)
        
        // 根据平台构建不同的URL
        // #ifdef H5
        // H5平台：使用完整的URL路径
        this.iframeUrl = `/static/html/ezviz-iframe.html?accessToken=${token}&playUrl=${url}`
        console.log('📱 H5平台 - iframeUrl:', this.iframeUrl)
        // #endif
        
        // #ifdef APP-PLUS
        // APP平台：使用本地路径
        this.webviewUrl = `/static/html/ezviz-iframe.html?accessToken=${token}&playUrl=${url}`
        console.log('📱 APP平台 - webviewUrl:', this.webviewUrl)
        // #endif
        
        // 启用视频状态
        this.ezstate = true
        console.log('✅ 播放器URL配置完成')
        
      } catch (error) {
        console.error('❌ 初始化视频失败:', error)
        uni.showToast({
          title: '视频初始化失败',
          icon: 'none',
          duration: 3000
        })
      }
    },
    
    // 处理webview消息（APP平台）
    handleWebviewMessage(event) {
      console.log('📨 收到webview消息:', event)
      // 可以在这里处理从播放器HTML页面发来的消息
    },
    
    // 停止视频播放器
    stopVideoPlayer() {
      try {
        console.log('🛑 停止视频播放器')
        
        // 重置页面状态
        this.ezstate = false
        this.videoLoaded = false
        this.isPlaying = false
        
        // 清空URL
        this.iframeUrl = ''
        this.webviewUrl = ''
        
        console.log('✅ 播放器已停止')
      } catch (error) {
        console.error('❌ 停止视频播放器失败:', error)
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.visual-monitoring-page {
  width: 100%;
  height: 100%;
  background: #f5f6fa;
}
  
/* 内容区域 */
.tabbar-content {
  width: 100%;
  height: 100%;
  padding: 30rpx;
  overflow-y: auto;
  display: flex;
  flex-direction: column;
  gap: 30rpx;
  box-sizing: border-box;
  margin-top: 10px;
}

/* 视频外层容器 */
.video-wrapper {
  width: 100%;
  height: calc(100vh - 180rpx); /* 减去头部和底部tabbar */
  // min-height: 400px;
  // display: flex;
  // justify-content: center;
  // align-items: stretch;
  // border-radius: 16rpx;
  // overflow: hidden;
  // box-shadow: 0 8rpx 24rpx rgba(0, 0, 0, 0.2);
  // background: #000;
}

/* H5平台的iframe样式 */
.video-iframe {
  width: 100%;
  height: 100%;
  border: none;
  // background: #000;
}

/* APP平台的webview样式 */
.video-webview {
  width: 100%;
  height: 100%;
  background: #000;
}

/* 无数据状态 */
.no-data-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 400rpx;
  background: linear-gradient(135deg, #f5f7fa 0%, #e3e7f0 100%);
  border-radius: 16rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.08);
}

.no-data-icon {
  font-size: 120rpx;
  margin-bottom: 20rpx;
  opacity: 0.6;
}

.no-data-text {
  font-size: 32rpx;
  color: #666;
}

/* 视频信息区域 */
.video-info {
  display: flex;
  gap: 20rpx;
  padding: 20rpx 30rpx;
  background: white;
  border-radius: 12rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.08);
}

.info-item {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8rpx;
  padding: 15rpx 10rpx;
  background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
  border-radius: 10rpx;
}

.info-label {
  font-size: 24rpx;
  color: #666;
  white-space: nowrap;
}

.info-value {
  font-size: 26rpx;
  font-weight: bold;
  color: #333;
  
  &.online {
    color: #4caf50;
  }
}

/* 视频控制按钮区域 */
.control-section {
  display: flex;
  gap: 20rpx;
  padding: 0 10rpx;
}

.control-btn {
  flex: 1;
  height: 80rpx;
  border-radius: 12rpx;
  font-size: 28rpx;
  font-weight: bold;
  color: white;
  border: none;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.15);
  transition: all 0.3s ease;
}

.init-btn {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.init-btn:active {
  background: linear-gradient(135deg, #5568d3 0%, #6a4193 100%);
  transform: scale(0.98);
}

.pause-btn {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
}

.pause-btn:active {
  background: linear-gradient(135deg, #e082ea 0%, #e4465b 100%);
  transform: scale(0.98);
}

.test-section {
  padding: 40rpx;
  display: flex;
  flex-direction: column;
  gap: 20rpx;
  align-items: center;
}

.test-btn {
  background: #007aff;
  color: white;
  border: none;
  border-radius: 8rpx;
  padding: 20rpx 40rpx;
  font-size: 28rpx;
  width: 300rpx;
}

.test-btn:active {
  background: #0056b3;
}

.camera-status {
  background: white;
  border-radius: 12rpx;
  padding: 25rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 8rpx rgba(0,0,0,0.05);
  display: flex;
  gap: 30rpx;
}

.status-item {
  flex: 1;
  display: flex;
  align-items: center;
  gap: 20rpx;
}

.status-icon {
  font-size: 48rpx;
}

.camera-icon {
  color: #666;
}

.recording-icon {
  color: #ff4444;
}

.status-info {
  display: flex;
  flex-direction: column;
  gap: 5rpx;
}

.status-label {
  font-size: 24rpx;
  color: #666;
}

.status-value {
  font-size: 28rpx;
  font-weight: bold;
  
  &.online {
    color: #4caf50;
  }
  
  &.offline {
    color: #999;
  }
  
  &.recording {
    color: #ff4444;
  }
  
  &.inactive {
    color: #666;
  }
}

.video-container {
  background: white;
  border-radius: 12rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 8rpx rgba(0,0,0,0.05);
  overflow: hidden;
}

.video-placeholder {
  padding: 60rpx;
  text-align: center;
}

.placeholder-image {
  width: 300rpx;
  height: 200rpx;
  margin-bottom: 30rpx;
  border-radius: 10rpx;
}

.placeholder-text {
  display: block;
  font-size: 28rpx;
  color: #666;
  margin-bottom: 30rpx;
}

.connect-button {
  background-color: #3f51b5;
  color: white;
  padding: 20rpx 40rpx;
  border-radius: 10rpx;
  font-size: 28rpx;
}

.video-player {
  padding: 30rpx;
  text-align: center;
}

.video-text {
  display: block;
  font-size: 32rpx;
  color: #333;
  margin-bottom: 30rpx;
}

.video-controls {
  display: flex;
  gap: 20rpx;
  justify-content: center;
}

.control-button {
  background-color: #3f51b5;
  color: white;
  padding: 15rpx 30rpx;
  border-radius: 8rpx;
  font-size: 24rpx;
}

.monitoring-settings {
  background: white;
  border-radius: 15rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 4rpx 12rpx rgba(0,0,0,0.1);
}

.settings-header {
  margin-bottom: 30rpx;
}

.settings-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.setting-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30rpx;
  
  &:last-child {
    margin-bottom: 0;
  }
}

.setting-label {
  font-size: 28rpx;
  color: #333;
}

.picker-view {
  display: flex;
  align-items: center;
  gap: 10rpx;
  padding: 15rpx 20rpx;
  background-color: #f8f8f8;
  border-radius: 8rpx;
  border: 2rpx solid #e0e0e0;
}

.picker-arrow {
  color: #999;
  font-size: 20rpx;
}

.recording-history {
  background: white;
  border-radius: 15rpx;
  box-shadow: 0 4rpx 12rpx rgba(0,0,0,0.1);
  overflow: hidden;
}

.history-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx;
  border-bottom: 2rpx solid #f0f0f0;
}

.history-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.clear-button {
  background-color: #ff4444;
  color: white;
  padding: 10rpx 20rpx;
  border-radius: 6rpx;
  font-size: 24rpx;
}

.history-list {
  height: 400rpx;
}

.history-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx;
  border-bottom: 2rpx solid #f0f0f0;
  
  &:last-child {
    border-bottom: none;
  }
}

.history-info {
  display: flex;
  flex-direction: column;
  gap: 5rpx;
}

.history-time {
  font-size: 28rpx;
  color: #333;
  font-weight: bold;
}

.history-duration {
  font-size: 24rpx;
  color: #666;
}

.history-actions {
  display: flex;
  gap: 15rpx;
}

.action-button {
  background-color: #3f51b5;
  color: white;
  padding: 8rpx 16rpx;
  border-radius: 6rpx;
  font-size: 22rpx;
  
  &.delete {
    background-color: #ff4444;
  }
}
</style>