<template>
  <!-- 使用原生 scroll-view 实现滚动 -->
  <scroll-view
    class="scroll-container"
    :scroll-y="true"
    :style="{ height: height, backgroundColor: backgroundColor }"
    @scroll="onScroll"
  >
    <!-- 顶部自定义区域 -->
    <slot name="top"></slot>
    
    <!-- 视频网格列表 -->
    <view class="video-grid" :style="gridStyle">
      <view 
        class="video-item" 
        v-for="(item, index) in videoList" 
        :key="index"
        :style="itemStyle"
      >
        <!-- 视频播放器 -->
        <video
          :id="'video'+index"
          :src="item.src"
          :autoplay="item.autoplay"
          :loop="true"
          :muted="true"
          :controls="false"
          :poster="item.poster"
          :show-center-play-btn="true"
          class="video-player"
          @play="onVideoPlay(item, index)"
          @error="onVideoError(item)"
        />
        
        <!-- 蒙版层 - 拦截点击事件 -->
        <view 
          class="video-mask"
          @click="onVideoClick(item)"
        >
          <!-- 元数据区域 - 父级可控制是否显示 -->
          <view 
            class="video-meta" 
            :style="{background: metaGradient}"
            v-if="showTitle || showFavorite || showComment"
          >
            <!-- 标题 - 父级可控制是否显示 -->
            <text class="video-title" v-if="showTitle">{{ item.title }}</text>
            
            <!-- 操作按钮区域 - 父级可控制是否显示 -->
            <view class="video-actions" v-if="showFavorite || showComment">
              <!-- 收藏按钮 - 父级可控制是否显示 -->
              <view class="action-btn" v-if="showFavorite">
                <uni-icons type="heart" size="16" :color="favoriteColor" />
                <text :style="{color: favoriteTextColor}">{{ item.likes || 0 }}</text>
              </view>
              
              <!-- 评论按钮 - 父级可控制是否显示 -->
              <view class="action-btn" v-if="showComment">
                <uni-icons type="chat" size="16" :color="commentColor" />
                <text :style="{color: commentTextColor}">{{ item.comments || 0 }}</text>
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>
    
    <!-- 空数据提示 -->
    <view class="empty-container" v-if="videoList.length === 0">
      <slot name="empty" v-if="$slots.empty"></slot>
      <view v-else class="empty-content">
        <image 
          src="/static/images/empty-video.png" 
          mode="aspectFit" 
          class="empty-img"
        />
        <text class="empty-text">暂无视频数据</text>
      </view>
    </view>
  </scroll-view>
</template>

<script>
export default {
  name: 'video-grid-enhanced',
  props: {
    // 视频数据列表
    videoList: {
      type: Array,
      required: true,
      default: () => []
    },
    // 每行列数
    columns: {
      type: Number,
      default: 2
    },
    // 间距
    gap: {
      type: String,
      default: '10px'
    },
    // 容器高度
    height: {
      type: String,
      default: '100vh'
    },
    // 背景颜色
    backgroundColor: {
      type: String,
      default: '#FFFFFF'
    },
    // 是否显示标题
    showTitle: {
      type: Boolean,
      default: false
    },
    // 是否显示收藏按钮
    showFavorite: {
      type: Boolean,
      default: false
    },
    // 是否显示评论按钮
    showComment: {
      type: Boolean,
      default: false
    },
    // 收藏图标颜色
    favoriteColor: {
      type: String,
      default: '#ff5a5f'
    },
    // 收藏文字颜色
    favoriteTextColor: {
      type: String,
      default: '#666'
    },
    // 评论图标颜色
    commentColor: {
      type: String,
      default: '#3399ff'
    },
    // 评论文字颜色
    commentTextColor: {
      type: String,
      default: '#666'
    },
    // 元数据背景渐变
    metaGradient: {
      type: String,
      default: 'linear-gradient(transparent, rgba(0,0,0,0.7))'
    },
    // 是否自动播放中央视频
    autoPlayCenter: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      currentPlayIndex: null, // 当前播放的视频索引
      scrollTop: 0, // 当前滚动位置
    };
  },
  computed: {
    gridStyle() {
      return {
        display: 'grid',
        gridTemplateColumns: `repeat(${this.columns}, 1fr)`,
        gap: this.gap,
        padding: '10px',
        backgroundColor: this.backgroundColor
      };
    },
    itemStyle() {
      const aspectRatio = 0.75; // 4:3比例
      return {
        position: 'relative',
        overflow: 'hidden',
        borderRadius: '8px',
        backgroundColor: this.backgroundColor,
        aspectRatio: aspectRatio
      };
    }
  },
  mounted() {
    // 自动播放第一个视频
    // this.$nextTick(() => {
    //   if (this.videoList.length > 0) {
    //     setTimeout(() => {
    //       this.playVideo(0);
    //     }, 500);
    //   }
    // });
  },
  methods: {
    // 播放指定视频
    playVideo(index) {
      // 停止当前播放的视频
      if (this.currentPlayIndex !== null) {
        this.pauseVideo(this.currentPlayIndex);
      }
      
      // 播放新视频
      if (index < this.videoList.length) {
        this.currentPlayIndex = index;
        const videoId = 'video' + index;
        const videoContext = uni.createVideoContext(videoId, this);
        if (videoContext) {
          try {
            videoContext.play();
          } catch (error) {
            console.error('Error playing video:', error);
          }
        }
      }
    },
    
    // 暂停指定视频
    pauseVideo(index) {
      if (index < this.videoList.length) {
        const videoId = 'video' + index;
        const videoContext = uni.createVideoContext(videoId, this);
        if (videoContext) {
          videoContext.pause();
        }
      }
    },
    
    // 停止所有视频
    stopAllVideos() {
      for (let i = 0; i < this.videoList.length; i++) {
        this.pauseVideo(i);
      }
    },
    
    // 视频播放事件
    onVideoPlay(item, index) {
      this.playVideo(index);
    },
    
    // 视频点击事件 - 通过蒙版层触发
    onVideoClick(item) {
      console.log("拦截事件",item)
      this.$emit('video-click', item);
    },
    
    // 视频播放错误
    onVideoError(item) {
      try {
        console.error('视频播放失败:', item);
        uni.showToast({
          title: `视频${item.title}加载失败`,
          icon: 'none'
        });
        
        // 尝试播放下一个视频
        if (this.currentPlayIndex !== null && this.currentPlayIndex + 1 < this.videoList.length) {
          setTimeout(() => {
            this.playVideo(this.currentPlayIndex + 1);
          }, 500);
        }
      } catch (error) {
        console.error('Error in onVideoError:', error);
      }
    },
    
    // 滚动事件处理
    onScroll(e) {
      this.scrollTop = e.detail.scrollTop;
      this.$emit('scroll', e);
      
      // 自动播放最靠近屏幕中央的视频
      if (this.autoPlayCenter) {
        this.$nextTick(() => {
          this.autoPlayCenterVideo();
        });
      }
    },
    
    // 自动播放屏幕中央的视频
    autoPlayCenterVideo() {
      if (this.currentPlayIndex === null) return;
      
      // 获取视频项高度
      const videoItem = this.$el.querySelector('.video-item');
      if (!videoItem) return;
      
      const itemHeight = videoItem.clientHeight;
      const screenCenter = this.scrollTop + window.innerHeight / 2;
      
      // 找到最接近屏幕中央的视频
      let centerIndex = Math.floor((screenCenter - itemHeight / 2) / itemHeight) * this.columns;
      
      // 限制范围
      centerIndex = Math.max(0, Math.min(centerIndex, this.videoList.length - 1));
      
      // 如果中央视频变化了，播放新视频
      if (centerIndex !== this.currentPlayIndex) {
        this.playVideo(centerIndex);
      }
    }
  }
};
</script>

<style scoped lang="scss">
.scroll-container {
  width: 100%;
  overflow: hidden;
}

.video-grid {
  padding: 8px;
}

.video-item {
  position: relative;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
}

.video-player {
  width: 100%;
  height: 100%;
  display: block;
  background: #f7f7f7;
}

/* 蒙版层样式 - 覆盖整个视频项 */
.video-mask {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 10;
  display: flex;
  flex-direction: column;
  justify-content: flex-end;
}

.video-meta {
  padding: 12px;
}

.video-title {
  font-size: 14px;
  line-height: 1.5;
  color: white;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
  overflow: hidden;
  text-overflow: ellipsis;
}

.video-actions {
  display: flex;
  justify-content: flex-end;
  margin-top: 10px;
}

.action-btn {
  display: flex;
  align-items: center;
  margin-left: 15px;
  
  text {
    font-size: 12px;
    margin-left: 4px;
    color: white;
  }
}

.empty-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 300px;
}

.empty-content {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.empty-img {
  width: 150px;
  height: 150px;
  opacity: 0.5;
}

.empty-text {
  font-size: 16px;
  color: #999;
  margin-top: 20px;
}
</style>