<template>
  <view class="simple-video-player">
    <view class="debug-info" v-if="showDebug">
      <text>平台: {{ platform }}</text>
      <text>状态: {{ status }}</text>
      <text>播放状态: {{ isPlaying ? '播放中' : '已暂停' }}</text>
    </view>
    
    <!-- APP平台使用web-view -->
    <!-- #ifdef APP-PLUS -->
    <web-view 
      v-if="webviewUrl"
      ref="videoWebview"
      :src="webviewUrl" 
      class="video-webview"
      @message="handleMessage"
    ></web-view>
    <!-- #endif -->
    
    <!-- H5平台直接使用iframe -->
    <!-- #ifdef H5 -->
    <view v-if="iframeUrl" class="h5-iframe-container">
      <iframe 
        :src="iframeUrl" 
        class="h5-iframe"
        allow="autoplay; fullscreen"
        allowfullscreen
      ></iframe>
    </view>
    <!-- #endif -->
    
    <!-- APP平台：控制按钮已集成到HTML页面中 -->
    <!-- #ifdef APP-PLUS -->
    <!-- 控制按钮现在直接在 ezviz-iframe.html 页面中 -->
    <!-- #endif -->
    
    <!-- H5平台：使用悬浮按钮（与APP平台保持一致） -->
    <!-- #ifdef H5 -->
    <view class="control-buttons-unified" v-if="!loading && iframeUrl && !error">
      <view class="control-btn-unified play-btn-unified" @click="togglePlay">
        <text class="btn-text-unified">{{ isPlaying ? '⏸ 暂停' : '▶ 播放' }}</text>
      </view>
      <view class="control-btn-unified refresh-btn-unified" @click="refresh">
        <text class="btn-text-unified">🔄 刷新</text>
      </view>
    </view>
    <!-- #endif -->
    
    <view v-if="loading" class="loading">
      <text>{{ loadingText }}</text>
    </view>
    
    <view v-if="error" class="error">
      <text>{{ errorText }}</text>
      <button @click="retry">重试</button>
      
      <!-- 即使有错误也显示控制按钮 -->
      <view class="error-controls">
        <button class="control-btn play-btn" @click="togglePlay">
          {{ isPlaying ? '⏸ 暂停' : '▶ 播放' }}
        </button>
        <button class="control-btn refresh-btn" @click="refresh">
          🔄 刷新
        </button>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  name: 'EzvizVideoPlayerSimple',
  props: {
    showDebug: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      platform: '',
      status: '未初始化',
      webviewUrl: '',    // APP平台使用
      iframeUrl: '',     // H5平台使用
      loading: false,
      loadingText: '',
      error: false,
      errorText: '',
      config: null,
      isPlaying: true // 默认自动播放
    }
  },
  mounted() {
    this.detectPlatform()
  },
  methods: {
    detectPlatform() {
      // #ifdef H5
      this.platform = 'H5'
      // #endif
      
      // #ifdef APP-PLUS
      this.platform = 'APP'
      // #endif
      
      console.log('[简单播放器] 平台:', this.platform)
    },
    
    initEzuikit(config) {
      console.log('[简单播放器] 初始化:', config)
      
      if (!config || !config.accessToken || !config.play_url) {
        this.error = true
        this.errorText = '配置参数不完整'
        return
      }
      
      this.config = config
      this.loading = true
      this.loadingText = '正在加载播放器...'
      this.status = '加载中'
      
      try {
        // #ifdef APP-PLUS
        // APP平台：使用本地HTML文件
        const token = encodeURIComponent(config.accessToken)
        const url = encodeURIComponent(config.play_url)
        this.webviewUrl = `/static/html/ezviz-iframe.html?accessToken=${token}&playUrl=${url}`
        console.log('[简单播放器] APP平台 - 使用本地HTML文件')
        console.log('[简单播放器] APP平台 - webviewUrl:', this.webviewUrl)
        // #endif
        
        // #ifdef H5
        // H5平台：直接构建萤石云iframe URL
        this.iframeUrl = 'https://open.ys7.com/ezopen/h5/iframe?' +
          'url=' + encodeURIComponent(config.play_url) +
          '&accessToken=' + encodeURIComponent(config.accessToken) +
          '&width=100%' +
          '&height=100%' +
          '&autoplay=1' +
          '&audio=1' +
          '&controls=1';
        console.log('[简单播放器] H5平台 - 直接使用萤石云iframe', this.iframeUrl)
        // #endif
        
        setTimeout(() => {
          if (this.loading) {
            this.loading = false
            this.status = '播放器已加载'
            console.log('[简单播放器] 加载完成，显示控制按钮')
            console.log('[简单播放器] 当前状态:', {
              loading: this.loading,
              webviewUrl: !!this.webviewUrl,
              iframeUrl: !!this.iframeUrl,
              platform: this.platform
            })
          }
        }, 3000)
        
      } catch (err) {
        console.error('[简单播放器] 错误:', err)
        this.error = true
        this.errorText = err.message
        this.loading = false
      }
    },
    
    handleMessage(event) {
      console.log('[简单播放器] 收到消息:', event)
      
      try {
        const data = event.detail.data
        const msg = Array.isArray(data) ? data[0] : data
        
        if (msg && msg.type === 'success') {
          this.loading = false
          this.status = '播放成功'
        } else if (msg && msg.type === 'error') {
          this.loading = false
          this.error = true
          this.errorText = msg.message || '播放失败'
        }
      } catch (err) {
        console.error('[简单播放器] 消息处理错误:', err)
      }
    },
    
    retry() {
      this.error = false
      this.errorText = ''
      if (this.config) {
        this.initEzuikit(this.config)
      }
    },
    
    // 切换播放/暂停
    // 统一的播放状态切换逻辑
    togglePlay() {
      console.log('[简单播放器] 切换播放状态:', this.isPlaying ? '暂停' : '播放')
      
      // 防止重复点击和加载中操作
      if (this.loading) {
        console.log('[简单播放器] 播放器加载中，忽略操作')
        return
      }
      
      const newPlayState = !this.isPlaying
      
      // 统一的状态更新逻辑
      if (newPlayState) {
        this.startPlayback()
      } else {
        this.pausePlayback()
      }
      
      // 返回新的播放状态
      return this.isPlaying
    },
    
    // 统一的开始播放逻辑
    startPlayback() {
      console.log('[简单播放器] 开始播放')
      
      if (!this.config) {
        console.error('[简单播放器] 配置信息不存在，无法播放')
        return
      }
      
      try {
        // 设置播放URL - 两个平台使用相同的逻辑
        // #ifdef APP-PLUS
        const token = encodeURIComponent(this.config.accessToken)
        const url = encodeURIComponent(this.config.play_url)
        this.webviewUrl = `/static/html/ezviz-iframe.html?accessToken=${token}&playUrl=${url}`
        console.log('[简单播放器] APP平台 - 设置webviewUrl')
        // #endif
        
        // #ifdef H5
        this.iframeUrl = 'https://open.ys7.com/ezopen/h5/iframe?' +
          'url=' + encodeURIComponent(this.config.play_url) +
          '&accessToken=' + encodeURIComponent(this.config.accessToken) +
          '&width=100%' +
          '&height=100%' +
          '&autoplay=1' +
          '&audio=1' +
          '&controls=1'
        console.log('[简单播放器] H5平台 - 设置iframeUrl', this.iframeUrl)
        // #endif
        
        // 统一更新状态
        this.isPlaying = true
        this.status = '播放中'
        this.error = false
        
        // 触发状态变化事件
        this.$emit('playStateChange', true)
        console.log('[简单播放器] 播放状态已更新为：播放中')
        
      } catch (error) {
        console.error('[简单播放器] 开始播放失败:', error)
        this.error = true
        this.errorText = '播放失败: ' + error.message
      }
    },
    
    // 统一的暂停播放逻辑
    pausePlayback() {
      console.log('[简单播放器] 暂停播放')
      
      try {
        // 清空播放URL - 两个平台使用相同的逻辑
        // #ifdef APP-PLUS
        this.webviewUrl = ''
        console.log('[简单播放器] APP平台 - 清空webviewUrl')
        // #endif
        
        // #ifdef H5
        this.iframeUrl = ''
        console.log('[简单播放器] H5平台 - 清空iframeUrl')
        // #endif
        
        // 统一更新状态
        this.isPlaying = false
        this.status = '已暂停'
        
        // 触发状态变化事件
        this.$emit('playStateChange', false)
        console.log('[简单播放器] 播放状态已更新为：已暂停')
        
      } catch (error) {
        console.error('[简单播放器] 暂停播放失败:', error)
      }
    },
    
    // 获取当前播放状态
    getPlayState() {
      return this.isPlaying
    },
    
    // 统一的刷新播放器逻辑
    refresh() {
      console.log('[简单播放器] 刷新播放器')
      
      if (!this.config) {
        console.error('[简单播放器] 配置信息不存在，无法刷新')
        uni.showToast({
          title: '配置信息不存在',
          icon: 'error',
          duration: 2000
        })
        return
      }
      
      try {
        // 显示刷新提示
        uni.showToast({
          title: '正在刷新...',
          icon: 'loading',
          duration: 1000
        })
        
        // 重置播放器状态
        this.error = false
        this.loading = true
        this.loadingText = '重新加载中...'
        
        // 先暂停播放
        this.pausePlayback()
        
        // 延迟重新开始播放，确保清空操作完成
        setTimeout(() => {
          try {
            // 重新开始播放
            this.startPlayback()
            
            // 显示成功提示
            uni.showToast({
              title: '刷新成功',
              icon: 'success',
              duration: 1500
            })
            
            // 重置加载状态
            setTimeout(() => {
              this.loading = false
              this.loadingText = '加载中...'
            }, 1000)
            
          } catch (error) {
            console.error('[简单播放器] 重新播放失败:', error)
            this.loading = false
            this.error = true
            this.errorText = '刷新失败: ' + error.message
            
            uni.showToast({
              title: '刷新失败',
              icon: 'error',
              duration: 2000
            })
          }
        }, 500)
        
      } catch (error) {
        console.error('[简单播放器] 刷新播放器失败:', error)
        this.loading = false
        this.error = true
        this.errorText = '刷新失败: ' + error.message
        
        uni.showToast({
          title: '刷新失败',
          icon: 'error',
          duration: 2000
        })
      }
    },
    
    // 停止播放器（页面关闭时调用）
    stopPlayer() {
      console.log('[简单播放器] 停止播放器')
      
      try {
        // 清空播放URL，停止播放
        // #ifdef APP-PLUS
        this.webviewUrl = ''
        // #endif
        // #ifdef H5
        this.iframeUrl = ''
        // #endif
        
        // 重置状态
        this.isPlaying = false
        this.status = '已停止'
        this.loading = false
        this.error = false
        
        // 触发状态变化事件
        this.$emit('playStateChange', false)
        
        console.log('[简单播放器] 播放器已停止')
      } catch (error) {
        console.error('[简单播放器] 停止播放器失败:', error)
      }
    }
  }
}
</script>

<style scoped>
.simple-video-player {
  width: 100%;
  height: 100%;
  position: absolute;
  top: 0;
  left: 0;
  background: #000;
}

.debug-info {
  position: absolute;
  top: 10rpx;
  left: 10rpx;
  background: rgba(0,0,0,0.7);
  color: white;
  padding: 10rpx;
  font-size: 24rpx;
  z-index: 100;
}

.debug-info text {
  display: block;
  margin: 5rpx 0;
}

.video-webview {
  width: 100%;
  height: 100%;
  position: absolute;
  top: 0;
  left: 0;
}

/* H5平台iframe容器 */
.h5-iframe-container {
  width: 100%;
  height: 100%;
  position: absolute;
  top: 0;
  left: 0;
  background: #000;
}

.h5-iframe {
  width: 100%;
  height: 100%;
  border: none;
  display: block;
}

.loading {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  background: rgba(0,0,0,0.8);
  color: white;
  font-size: 28rpx;
  z-index: 50;
}

.error {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background: rgba(255,0,0,0.8);
  color: white;
  font-size: 28rpx;
  z-index: 50;
  padding: 40rpx;
}

.error text {
  margin-bottom: 30rpx;
  text-align: center;
}

.error button {
  background: white;
  color: #333;
  padding: 20rpx 40rpx;
  border-radius: 10rpx;
}

/* 错误状态下的控制按钮 */
.error-controls {
  display: flex;
  gap: 20rpx;
  margin-top: 30rpx;
  justify-content: center;
}

.error-controls .control-btn {
  flex: 1;
  max-width: 200rpx;
  height: 60rpx;
  border-radius: 8rpx;
  font-size: 24rpx;
  font-weight: bold;
  color: white;
  border: none;
  display: flex;
  align-items: center;
  justify-content: center;
}

.error-controls .play-btn {
  background: linear-gradient(135deg, #46a049 0%, #4caf50 100%);
}

.error-controls .refresh-btn {
  background: linear-gradient(135deg, #2196f3 0%, #21cbf3 100%);
}

/* 控制按钮 */
.control-buttons {
  position: absolute;
  bottom: 30rpx;
  left: 50%;
  transform: translateX(-50%);
  display: flex;
  gap: 20rpx;
  z-index: 100;
}

.control-btn {
  background: rgba(0, 0, 0, 0.75);
  color: white;
  border: 2rpx solid rgba(255, 255, 255, 0.6);
  padding: 16rpx 32rpx;
  border-radius: 40rpx;
  font-size: 24rpx;
  font-weight: 600;
  min-width: 140rpx;
  backdrop-filter: blur(10rpx);
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.3);
  transition: all 0.2s ease;
}

.control-btn:active {
  background: rgba(0, 0, 0, 0.9);
  transform: scale(0.96);
}

.play-btn {
  background: rgba(46, 125, 50, 0.85);
  border-color: rgba(76, 175, 80, 0.9);
}

.play-btn:active {
  background: rgba(46, 125, 50, 1);
}

.refresh-btn {
  background: rgba(25, 118, 210, 0.85);
  border-color: rgba(33, 150, 243, 0.9);
}

.refresh-btn:active {
  background: rgba(25, 118, 210, 1);
}

/* 统一的控制按钮样式 - APP平台使用 cover-view */
.control-buttons-cover {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translateX(-50%);
  display: flex;
  gap: 20rpx;
  z-index: 999;
}

.control-btn-cover {
  background: rgba(0, 0, 0, 0.75);
  border: 2rpx solid rgba(255, 255, 255, 0.6);
  border-radius: 40rpx;
  padding: 16rpx 32rpx;
  min-width: 140rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s ease;
}

.play-btn-cover {
  background: rgba(46, 125, 50, 0.85);
  border-color: rgba(76, 175, 80, 0.9);
}

.refresh-btn-cover {
  background: rgba(25, 118, 210, 0.85);
  border-color: rgba(33, 150, 243, 0.9);
}

.btn-text {
  color: white;
  font-size: 24rpx;
  font-weight: 600;
  text-align: center;
}

/* 统一的控制按钮样式 - H5平台使用 view */
.control-buttons-unified {
  position: fixed;
  top: 50%;;
  left: 50%;
  transform: translateX(-50%);
  display: flex;
  gap: 20rpx;
  z-index: 999;
}

.control-btn-unified {
  background: rgba(0, 0, 0, 0.75);
  border: 2rpx solid rgba(255, 255, 255, 0.6);
  border-radius: 40rpx;
  padding: 16rpx 32rpx;
  min-width: 140rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.3s ease;
  user-select: none;
}

.control-btn-unified:hover {
  transform: scale(1.05);
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.3);
}

.control-btn-unified:active {
  transform: scale(0.95);
}

.play-btn-unified {
  background: rgba(46, 125, 50, 0.85);
  border-color: rgba(76, 175, 80, 0.9);
}

.play-btn-unified:hover {
  background: rgba(46, 125, 50, 0.95);
  border-color: rgba(76, 175, 80, 1);
}

.refresh-btn-unified {
  background: rgba(25, 118, 210, 0.85);
  border-color: rgba(33, 150, 243, 0.9);
}

.refresh-btn-unified:hover {
  background: rgba(25, 118, 210, 0.95);
  border-color: rgba(33, 150, 243, 1);
}

.btn-text-unified {
  color: white;
  font-size: 24rpx;
  font-weight: 600;
  text-align: center;
  pointer-events: none;
}
</style>

