<template>
  <div class="app-container">
    <!-- 布局选择器 -->
    <el-select v-model="currentGrid" class="grid-select">
      <el-option
        v-for="grid in [1,4,6,9,16]"
        :key="grid"
        :label="`${grid}宫格`"
        :value="grid"
      />
    </el-select>

    <!-- 视频容器 -->
    <div 
      class="video-container"
      :style="gridStyle"
    >
      <div 
        v-for="video in currentVideos"
        :key="video.id"
        class="video-wrapper"
      >
        <video
          ref="videoPlayers"
          controls
          class="video-element"
          :src="video.url"
          muted
          playsinline
        ></video>
      </div>
    </div>

    <!-- 分页控制 -->
    <div class="pagination" v-if="totalPages > 1">
      <el-button @click="prevPage" :disabled="currentPage === 1">
        <i class="el-icon-arrow-left"></i>
      </el-button>
      <span class="page-text">{{ currentPage }}/{{ totalPages }}</span>
      <el-button @click="nextPage" :disabled="currentPage === totalPages">
        <i class="el-icon-arrow-right"></i>
      </el-button>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      currentGrid: 4,
      currentPage: 1,
      videoList: [
        { id: 1, url: 'http://vjs.zencdn.net/v/oceans.mp4',name:'aaa' },
        { id: 2, url: 'http://vjs.zencdn.net/v/oceans.mp4',name:'bbb' },
        { id: 3, url: 'http://vjs.zencdn.net/v/oceans.mp4',name:'ccc' },
        { id: 4, url: 'http://vjs.zencdn.net/v/oceans.mp4',name:'ddd' },
        { id: 5, url: 'http://vjs.zencdn.net/v/oceans.mp4',name:'eee' },
        { id: 6, url: 'http://vjs.zencdn.net/v/oceans.mp4',name:'fff' },
        { id: 7, url: 'http://vjs.zencdn.net/v/oceans.mp4',name:'ggg' },
      ],
      gridLayoutMap: {
        1:  { cols: 1, rows: 1 },
        4:  { cols: 2, rows: 2 },
        6:  { cols: 3, rows: 2 },
        9:  { cols: 3, rows: 3 },
        16: { cols: 4, rows: 4 }
      }
    }
  },

  computed: {
    gridStyle() {
      const { cols, rows } = this.gridLayoutMap[this.currentGrid]
      return {
        gridTemplateColumns: `repeat(${cols}, 1fr)`,
        gridTemplateRows: `repeat(${rows}, 1fr)`,
        aspectRatio: `${cols}/${rows}`
      }
    },

    currentVideos() {
      const start = (this.currentPage - 1) * this.currentGrid
      return this.videoList.slice(start, start + this.currentGrid)
    },

    totalPages() {
      return Math.ceil(this.videoList.length / this.currentGrid)
    }
  },

  watch: {
    currentGrid() {
      this.currentPage = 1
      this.$nextTick(this.playCurrentPage)
    },
    currentPage() {
      this.$nextTick(this.playCurrentPage)
    }
  },

  methods: {
    // 播放当前页所有视频
    async playCurrentPage() {
      try {
        // 暂停所有视频
        await this.pauseAllVideos()
        
        // 等待DOM更新
        await this.$nextTick()

        // 获取当前页视频元素
        const currentPlayers = (this.$refs.videoPlayers || [])
          .slice(0, this.currentVideos.length)

        // 批量播放处理
        const playTasks = currentPlayers.map(player => {
          player.muted = true
          return player.play().catch(error => {
            if (error.name !== 'AbortError') {
              console.warn('视频播放失败:', error)
            }
          })
        })

        await Promise.all(playTasks)
      } catch (error) {
        console.error('页面播放异常:', error)
      }
    },

    // 暂停所有视频（优化版）
    async pauseAllVideos() {
      const allPlayers = this.$refs.videoPlayers || []
      const pauseTasks = allPlayers.map(player => {
        return new Promise(resolve => {
          if (!player.paused) {
            player.addEventListener('pause', resolve, { once: true })
            player.pause()
          } else {
            resolve()
          }
        })
      })
      await Promise.all(pauseTasks)
    },

    prevPage() {
      if (this.currentPage > 1) this.currentPage--
    },

    nextPage() {
      if (this.currentPage < this.totalPages) this.currentPage++
    }
  },

  mounted() {
    this.playCurrentPage()
  }
}
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.grid-select {
  margin-bottom: 20px;
  width: 200px;
}

.video-container {
  display: grid;
  gap: 10px;
  margin: 20px 0;
  background: #2c3e50;
  border-radius: 8px;
  padding: 10px;
  min-height: 300px;
}

.video-wrapper {
  position: relative;
  padding-top: 56.25%;
  background: #000;
  border-radius: 4px;
  overflow: hidden;
}

.video-element {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.pagination {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 20px;
  margin-top: 20px;
}

.page-text {
  font-size: 16px;
  color: #409EFF;
  font-weight: 500;
}
</style>