<script>
import {defineComponent} from 'vue'
import { useBootstrapBreakpoint } from './useBreakpoint.js';
const { breakpoint } = useBootstrapBreakpoint();

export default defineComponent({
  name: "HeaderVideo",
  props: {
    // 给图片设置替代文本
    alt:         { type: String, default: '' },
    // 帧率（帧/秒），默认 20
    fps:         { type: Number, default: 15 },
    // 自动播放，默认 true
    autoplay:    { type: Boolean, default: true },
    // 播放完毕后不循环，触发跳转逻辑
    loop:        { type: Boolean, default: false },
    // 帧总数，默认 115
    framesCount: { type: Number, default: 82 },
    // 帧图所在目录
    basePath:    { type: String, default: '/openvideo/' }
  },
  data() {
    return {
      currentFrame: 0,
      timer: null,
      isLoading: true, // 加载状态
      loadingProgress: 0, // 加载进度
      preloadedImages: [] // 预加载的图片缓存
    }
  },
  methods:{
    handleVideoEnded:function (event){
      window.location.href = "/Homepage";
    },
    preloadAllImages() {
      this.isLoading = true;
      this.loadingProgress = 0;

      let loadedCount = 0;
      const totalFrames = this.frames.length;

      // 创建Promise数组
      const preloadPromises = this.frames.map((src, index) => {
        return new Promise((resolve, reject) => {
          const img = new Image();

          img.onload = () => {
            this.preloadedImages[index] = img;
            loadedCount++;
            this.loadingProgress = Math.floor(loadedCount / totalFrames * 100);
            resolve(img);
          };

          img.onerror = (e) => {
            console.error(`无法加载图片: ${src}`, e);
            loadedCount++;
            this.loadingProgress = Math.floor(loadedCount / totalFrames * 100);
            reject(e);
          };

          img.src = src;
        });
      });

      // 所有帧加载完成后开始播放
      Promise.all(preloadPromises)
          .then(() => {
            console.log("所有帧预加载完成");
            this.isLoading = false;
            this.start();
          })
          .catch(() => {
            console.log("部分帧加载失败，但仍继续播放");
            this.isLoading = false;
            this.start();
          });
    },

    start() {
      if (this.timer) return;
      const interval = 1000 / this.fps;

      this.timer = setInterval(() => {
        const next = this.currentFrame + 1;

        if (next < this.frames.length) {
          this.currentFrame = next;
        } else {
          this.stop();
          setTimeout(() => {
            window.location.href = "/Homepage";
          }, 100);
        }
      }, interval);
    },
    stop() {
      if (this.timer) {
        clearInterval(this.timer)
        this.timer = null
      }
    }
  },
  computed: {
    frames() {
      const arr = []
      for (let i = 0; i <= this.framesCount; i++) {
        // 保证五位数文件名，高位补零
        const name = String(i).padStart(2, '0') + '.jpg'
        arr.push(this.basePath + name)
      }
      return arr
    }
  },
  mounted() {
    if(this.$isMobile.phone)
    {
      this.preloadAllImages();
    }
    else
    {
      const videos = document.querySelectorAll('.startvideo');
      if (videos.length > 0) {
        videos.forEach(video => {
          video.addEventListener('ended', this.handleVideoEnded);
          console.log('为视频添加了 ended 事件监听器:', video);
        });
      } else {
        console.warn("没有找到视频元素。");
      }
    }
  },
  beforeUnmount() {
    this.stop()
  },
  watch: {
    autoplay(val) {
      val ? this.start() : this.stop()
    }
  }
})
</script>

<template>
  <div id="beginroot" class="pageroot">
    <div id="videodiv">
      <!-- 加载进度条 -->
      <div v-if="$isMobile.phone && isLoading" class="loading-container">
        <div class="progress-container">
          <div class="progress-bar" :style="{width: loadingProgress + '%'}"></div>
        </div>
        <div class="loading-text">加载中 {{ loadingProgress }}%</div>
      </div>

      <img
          :src="frames[currentFrame]"
          id="beginwep"
          :alt="alt"
          class="simple-frame-player"
          v-if="$isMobile.phone && !isLoading"
      />
      <video v-else-if="$isMobile.tablet" poster="/logobeginPCpld.png"
             id="tbstart" muted autoplay controls="controls"
             playsinline webkit-playsinline
             class="startvideo"
             x5-video-player-type="h5-page">
        <source src="/logobeginPC.mp4" type="video/mp4"></source>
      </video>
      <video v-else poster="/logobeginPCpld.png"
             id="pcstart" muted autoplay
             playsinline webkit-playsinline
             class="startvideo"
             x5-video-player-type="h5-page">
        <source src="/logobeginPC.mp4" type="video/mp4"></source>
      </video>
    </div>
    <div id="beginbottom">
      <a href="/Homepage">
        <div class="normalcontentdiv" id="intovideoreq">
        <span class="normalcontenttitle" id="intoa">
          <u>进入kdesign.top</u>
          <img src="/intopagedir.svg" id="intopagesvg"/>
        </span>
        </div>
      </a>
    </div>
  </div>
</template>

<style scoped lang="scss">
@import "src/publicstyle.scss";
.loading-container {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  text-align: center;
  width: 80%;
  z-index: 10;
}
.progress-container {
  background-color: rgba(255, 255, 255, 0.2);
  height: 8px;
  border-radius: 4px;
  overflow: hidden;
  margin-bottom: 10px;
}

.progress-bar {
  height: 100%;
  background-color: white;
  transition: width 0.3s ease;
}

.loading-text {
  color: white;
  font-size: 14px;
}
#beginroot{
  height: 100%;
  display: flex;
  flex-direction: column;
}
#wepstart{
  @include media-breakpoint-between(xs, md) {
    visibility: visible;
    height: 100%!important;
  }
  @include media-breakpoint-up(md) {
    visibility: collapse;
    height: 0!important;
  }
}
#pcstart{
  @include media-breakpoint-between(xs, md) {
    visibility: collapse;
  }
  @include media-breakpoint-up(md) {
    visibility: visible;
  }
}
#beginbottom {
  flex-shrink: 0; /* 添加这一行，防止此元素被压缩 */
  a {
    text-decoration: none;
    width: 100%; /* 确保链接占满整个宽度 */

    .normalcontenttitle {
      transition: color 0.3s ease;
      color: white;
      text-align: center; /* 文本居中 */
      display: flex;
      justify-content: center; /* flex布局下的水平居中 */
      align-items: center; /* 垂直居中对齐图标 */
    }
    #intoa{
      @include media-breakpoint-between(xs, md) {
        font-size: 24px;
      }
      @include media-breakpoint-up(md) {
        font-size: 35px;
        line-height: 48px;
      }
    }

    &:hover {
      .normalcontenttitle {
        color: #DAA520 !important;
      }
    }
  }
}
#videodiv{
  width: 100%;
  //height: 100%;
  flex:1;
  min-height: 0;
  background-color: black;
  overflow: hidden;
  @include media-breakpoint-between(xs, md) {
  }
  @include media-breakpoint-up(md) {
  }
}
.startvideo{
  width: 100%;
  height: 100%;
  object-fit: cover;
}
#beginwep{
  width: 100%;
  height: 100%;
  object-fit: cover;
}

#intopagesvg{
  height: 100%;
  width: auto;
  max-width: 100%;
}
#intopagesvg {
  height: 1em;
  width: auto;
  margin-left: 0.5em;
}
#intovideoreq{
  margin-top: 2px;
  padding-bottom: 2px;
  transition: background 0.5s, color 0.5s;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center; /* 添加这一行使内容水平居中 */
  width: 100%; /* 确保宽度占满 */
  margin-left: 0!important;
  margin-bottom: 10px;
}
#intovideoreq .normalcontenttitle {
  width: auto !important;
  text-align: center !important;
}
</style>
