import { Component, EventEmitter, Input, OnDestroy, OnChanges, OnInit, Output, ApplicationRef, ChangeDetectorRef, ViewChild, ElementRef } from '@angular/core';
import { JsonPipe } from '@angular/common';
import { NzMessageService } from 'ng-zorro-antd/message';
import { UploadChangeParam, UploadXHRArgs } from 'ng-zorro-antd/upload';
import { ComponentBase } from './ComponentBase';


@Component({
  selector: 'app-form',
  templateUrl: './form.component.html',
  styleUrls: ['./form.component.css']
})
export class FormComponent extends ComponentBase implements OnInit, OnChanges, OnDestroy {

  // 储存数据用
  saveKey = "JJ_Vedio_Practice";
  thumbnailCacheKey = "JJ_Video_Thumbnail_Cache"; // localStorage 缓存键名

  baseData;
  
  // 储存对象
  item: any = {
    video_url: "",
    cover: "",
    title: "",
    video_title: "",
    quesArr: []
  };
  //临时储存对象
  tempItem;


  templateTypeArr = [
    {name:"选择题", value: "select"},
    {name:"拖拽题", value: "drag"},
    {name:"语音评测", value: "record"},
    // {name:"连线题", value: "line"},
    // {name:"翻翻卡", value: "flip"},
  ]

  isPreviewTemplate = false;

  // 视频片段选择弹窗相关
  isFragmentModalVisible = false;
  currentFragmentQues = null;
  currentFragmentIndex = -1;
  fragmentVideoUrl = '';
  fragmentVideoCurrentTime = 0;
  fragmentVideoDuration = 0;
  fragmentSelectedTime = 0;
  fragmentVideoElement: HTMLVideoElement = null;
  isDraggingTrack = false;
  videoThumbnails: string[] = []; // 视频帧缩略图数组
  isGeneratingThumbnails = false; // 是否正在生成缩略图
  thumbnailCount = 20; // 生成的缩略图数量
  thumbnailCache: Map<string, { thumbnails: string[], duration: number, count: number }> = new Map(); // 缩略图缓存
  @ViewChild('thumbnailContainer', { static: false }) thumbnailContainer: ElementRef; // 缩略图容器引用
  isPreviewing = false; // 是否正在预览播放
  previewTargetTime = 0; // 预览目标时间






  curSelectItem;
  isShowKK=false;
  curSelectKK;
  KKArray = [
    "i",
    "ɪ",
    "u",
    "ʊ",
    "ɑ",
    "ʌ",
    "ɝ",
    "ə",
    "ɚ",
    "ɔ",
    "æ",
    "ɛ",
    "e",
    "aɪ",
    "ɔɪ",
    "o",


    "aʊ",
    "p",
    "b",
    "t",
    "d",
    "k",
    "g",
    "tʃ",
    "dʒ",
    "f",
    "v",
    "θ",
    "ð",
    "s",
    "z",
    "ʃ",
    "ʒ",
    "h",
    "m",
    "n",
    "ŋ",
    "l",
    "r",
    "w",
    "j",
  ]
  customTypeGroupArr2 = [
    {
      name: '星星区域',
      rect: true,
    },
    {
      name: '选择区域',
      rect: true,
    },
  ]

  stepArr = [
    {label: '视频时间', value: 'ques'},
  ];

  videoSizeArr = [
    {key: '1920_1080', value: '1920 x 1080'},
    {key: '1280_720', value: '1280 x 720'},
    {key: '940_600', value: '940 x 600'},
  ]

  audioTypeArr = [
    {key: 'begin', info: '第一遍开始音频'},
    {key: 'begin_2', info: '第二遍开始音频'},
    {key: 'finish', info: '第二遍结束音频'},
  ]


  constructor(public appRef: ApplicationRef, public changeDetectorRef: ChangeDetectorRef, 
    private message: NzMessageService) {
    super(appRef, changeDetectorRef);
  }


  ngOnInit() {


    // 从 localStorage 加载缩略图缓存
    this.loadThumbnailCacheFromLocalStorage();

    // 获取存储的数据
    (<any>window).courseware.getData((data) => {


      if (data) {
        this.item = data;
      }

      this.initItem();


      console.log("this.item: ", JSON.stringify(this.item));
      
      this.changeDetectorRef.markForCheck();
      this.changeDetectorRef.detectChanges();
      this.refresh();
      
    }, this.saveKey);
  }

  setFragment(ques, i) {
    console.log('i: ', i);
    this.currentFragmentQues = ques;
    this.currentFragmentIndex = i;
    this.fragmentVideoUrl = this.item.video_url || '';
    const videoUrl = this.item.video_url ? this.item.video_url.replace('.mp4', '_h.mp4') : '';
    this.fragmentVideoCurrentTime = ques.time || 0;
    this.fragmentSelectedTime = ques.time || 0;
    this.videoThumbnails = [];
    this.isFragmentModalVisible = true;
    
    // 检查缓存
    const cachedData = this.thumbnailCache.get(videoUrl);
    if (cachedData) {
      console.log('使用缓存的缩略图');
      this.videoThumbnails = cachedData.thumbnails;
      this.fragmentVideoDuration = cachedData.duration;
      this.thumbnailCount = cachedData.count;
      this.changeDetectorRef.detectChanges();
    }
    
    // 等待弹窗渲染后获取视频元素
    setTimeout(() => {
      this.fragmentVideoElement = document.getElementById('fragment-video') as HTMLVideoElement;
      if (this.fragmentVideoElement) {
        // 确保设置 crossOrigin 属性（必须在设置 src 之前或重新加载时设置）
        if (!this.fragmentVideoElement.crossOrigin) {
          this.fragmentVideoElement.crossOrigin = 'anonymous';
        }
        
        // 如果视频已经加载完成，获取时长并生成缩略图
        if (this.fragmentVideoElement.readyState >= 2) {
          this.fragmentVideoDuration = this.fragmentVideoElement.duration || 0;
          if (this.fragmentSelectedTime > 0) {
            this.fragmentVideoElement.currentTime = this.fragmentSelectedTime;
          }
          // 如果缓存不存在，生成缩略图
          if (this.fragmentVideoDuration > 0 && !cachedData) {
            setTimeout(() => {
              this.generateVideoThumbnails();
            }, 100);
          }
        } else {
          // 视频未加载，等待 loadedmetadata 事件
          if (this.fragmentSelectedTime > 0) {
            this.fragmentVideoElement.currentTime = this.fragmentSelectedTime;
          }
          // 如果缓存不存在，等待加载完成后生成
          if (!cachedData) {
            // 将在 onFragmentVideoLoadedMetadata 中生成
          }
        }
      }
    }, 100);
  }

  // 视频片段弹窗 - 取消
  fragmentModalCancel() {
    // 如果正在预览，停止播放
    if (this.isPreviewing && this.fragmentVideoElement) {
      this.fragmentVideoElement.pause();
      this.isPreviewing = false;
    }
    
    this.isFragmentModalVisible = false;
    this.currentFragmentQues = null;
    this.currentFragmentIndex = -1;
    this.fragmentVideoCurrentTime = 0;
    this.fragmentVideoDuration = 0;
    this.fragmentSelectedTime = 0;
    this.fragmentVideoElement = null;
    this.isDraggingTrack = false;
    this.videoThumbnails = []; // 只清除当前显示的缩略图，保留缓存
    this.isGeneratingThumbnails = false;
    this.previewTargetTime = 0;
  }

  // 清除指定视频的缩略图缓存
  clearThumbnailCache(videoUrl?: string) {
    if (videoUrl) {
      this.thumbnailCache.delete(videoUrl);
      // 同时从 localStorage 清除
      this.removeThumbnailCacheFromLocalStorage(videoUrl);
      console.log('已清除缓存:', videoUrl);
    } else {
      // 清除所有缓存
      this.thumbnailCache.clear();
      // 同时清除 localStorage
      this.clearThumbnailCacheFromLocalStorage();
      console.log('已清除所有缩略图缓存');
    }
  }

  // 保存缩略图缓存到 localStorage
  saveThumbnailCacheToLocalStorage(videoUrl: string, cacheData: { thumbnails: string[], duration: number, count: number }) {
    try {
      // 获取现有的缓存
      const existingCache = this.getThumbnailCacheFromLocalStorage();
      
      // 更新或添加新的缓存项
      existingCache[videoUrl] = cacheData;
      
      // 限制存储的视频数量，避免超出 localStorage 大小限制（通常 5-10MB）
      const maxCachedVideos = 10; // 最多缓存10个视频的缩略图
      const cacheEntries = Object.keys(existingCache);
      
      if (cacheEntries.length > maxCachedVideos) {
        // 删除最旧的缓存（简单策略：删除第一个）
        const oldestKey = cacheEntries[0];
        delete existingCache[oldestKey];
        console.log('缓存已满，删除最旧的缓存:', oldestKey);
      }
      
      // 尝试保存到 localStorage
      const cacheJson = JSON.stringify(existingCache);
      const cacheSize = new Blob([cacheJson]).size;
      const maxSize = 100 * 1024 * 1024; // 100MB 限制，留一些余量
      
      if (cacheSize > maxSize) {
        console.warn('缩略图缓存大小超出限制，跳过保存到 localStorage');
        return;
      }
      
      localStorage.setItem(this.thumbnailCacheKey, cacheJson);
      console.log('缩略图缓存已保存到 localStorage，大小:', (cacheSize / 1024).toFixed(2), 'KB');
    } catch (error) {
      console.error('保存缩略图缓存到 localStorage 失败:', error);
      // 如果存储失败（如超出大小限制），尝试清理一些旧缓存
      if (error.name === 'QuotaExceededError') {
        console.warn('localStorage 空间不足，尝试清理旧缓存');
        this.clearOldThumbnailCache();
      }
    }
  }

  // 从 localStorage 加载缩略图缓存
  loadThumbnailCacheFromLocalStorage() {
    try {
      const cacheJson = localStorage.getItem(this.thumbnailCacheKey);
      if (!cacheJson) {
        return;
      }
      
      const cacheData = JSON.parse(cacheJson);
      
      // 将对象转换为 Map
      for (const [videoUrl, data] of Object.entries(cacheData)) {
        this.thumbnailCache.set(videoUrl, data as { thumbnails: string[], duration: number, count: number });
      }
      
      console.log('从 localStorage 加载缩略图缓存，视频数量:', this.thumbnailCache.size);
    } catch (error) {
      console.error('从 localStorage 加载缩略图缓存失败:', error);
      // 如果解析失败，清除损坏的缓存
      localStorage.removeItem(this.thumbnailCacheKey);
    }
  }

  // 从 localStorage 获取所有缓存（返回对象格式）
  getThumbnailCacheFromLocalStorage(): { [key: string]: { thumbnails: string[], duration: number, count: number } } {
    try {
      const cacheJson = localStorage.getItem(this.thumbnailCacheKey);
      if (!cacheJson) {
        return {};
      }
      return JSON.parse(cacheJson);
    } catch (error) {
      console.error('读取 localStorage 缓存失败:', error);
      return {};
    }
  }

  // 从 localStorage 删除指定视频的缓存
  removeThumbnailCacheFromLocalStorage(videoUrl: string) {
    try {
      const existingCache = this.getThumbnailCacheFromLocalStorage();
      delete existingCache[videoUrl];
      localStorage.setItem(this.thumbnailCacheKey, JSON.stringify(existingCache));
    } catch (error) {
      console.error('从 localStorage 删除缓存失败:', error);
    }
  }

  // 清除 localStorage 中的所有缩略图缓存
  clearThumbnailCacheFromLocalStorage() {
    try {
      localStorage.removeItem(this.thumbnailCacheKey);
    } catch (error) {
      console.error('清除 localStorage 缓存失败:', error);
    }
  }

  // 清理旧的缩略图缓存（保留最新的几个）
  clearOldThumbnailCache() {
    try {
      const existingCache = this.getThumbnailCacheFromLocalStorage();
      const cacheEntries = Object.keys(existingCache);
      
      // 只保留最新的3个缓存
      if (cacheEntries.length > 3) {
        const entriesToKeep = cacheEntries.slice(-3);
        const newCache: { [key: string]: any } = {};
        entriesToKeep.forEach(key => {
          newCache[key] = existingCache[key];
        });
        localStorage.setItem(this.thumbnailCacheKey, JSON.stringify(newCache));
        console.log('已清理旧缓存，保留最新的', entriesToKeep.length, '个');
      }
    } catch (error) {
      console.error('清理旧缓存失败:', error);
    }
  }

  // 视频片段弹窗 - 确认
  fragmentModalOk() {
    if (this.currentFragmentQues) {
      // 保存选中的时间
      this.currentFragmentQues.time = this.fragmentSelectedTime;
      this.save();
      
      // 触发变更检测，确保分钟和秒输入框更新
      this.changeDetectorRef.detectChanges();
      
      // 在下一个变更检测周期再次触发，确保视图完全更新
      setTimeout(() => {
        this.changeDetectorRef.detectChanges();
      }, 0);
    }
    this.fragmentModalCancel();
  }

  // 视频加载元数据
  onFragmentVideoLoadedMetadata(event) {
    const video = event.target;
    // 确保设置 crossOrigin 属性
    if (!video.crossOrigin) {
      video.crossOrigin = 'anonymous';
    }
    this.fragmentVideoDuration = video.duration || 0;
    this.fragmentVideoElement = video;
    if (this.fragmentSelectedTime > 0) {
      video.currentTime = this.fragmentSelectedTime;
    }
    
    // 检查缓存
    const videoUrl = this.item.video_url ? this.item.video_url.replace('.mp4', '_h.mp4') : '';
    const cachedData = this.thumbnailCache.get(videoUrl);
    
    // 视频元数据加载完成后，如果缓存不存在则生成缩略图
    if (this.fragmentVideoDuration > 0 && this.isFragmentModalVisible && !cachedData) {
      // 延迟一下确保视频完全准备好
      setTimeout(() => {
        this.generateVideoThumbnails();
      }, 200);
    } else if (cachedData && this.videoThumbnails.length === 0) {
      // 如果缓存存在但缩略图数组为空，从缓存恢复
      this.videoThumbnails = cachedData.thumbnails;
      this.changeDetectorRef.detectChanges();
    }
  }

  // 视频加载错误处理
  onFragmentVideoError(event) {
    console.error('视频加载错误:', event);
    const video = event.target;
    if (video.error) {
      console.error('视频错误代码:', video.error.code, '错误信息:', video.error.message);
      // 如果是因为跨域问题，尝试重新设置
      if (video.error.code === MediaError.MEDIA_ERR_SRC_NOT_SUPPORTED) {
        //this.message.create('warning', '视频加载失败，可能是跨域问题。请确保视频服务器支持 CORS。');
      }
    }
  }

  // 视频时间更新
  onFragmentVideoTimeUpdate(event) {
    const video = event.target;
    
    // 如果正在预览，检查是否到达目标时间
    if (this.isPreviewing && video.currentTime >= this.previewTargetTime) {
      video.pause();
      video.currentTime = this.previewTargetTime;
      this.isPreviewing = false;
      this.message.create('success', '预览完成，已到达指定时间节点');
      return;
    }
    
    if (!this.isDraggingTrack) {
      this.fragmentVideoCurrentTime = video.currentTime;
      const previousSelectedIndex = Math.floor(this.fragmentSelectedTime);
      this.fragmentSelectedTime = video.currentTime;
      // 只有当时间跨越到新的缩略图索引时才滚动（避免频繁滚动）
      const currentSelectedIndex = Math.floor(this.fragmentSelectedTime);
      if (currentSelectedIndex !== previousSelectedIndex) {
        this.scrollToActiveThumbnail();
      }
    }
  }

  // 效果试看：从0开始播放到指定时间节点
  onVideoPreview() {
    if (!this.fragmentVideoElement) {
      this.message.create('warning', '视频未加载，请稍候再试');
      return;
    }

    if (!this.fragmentSelectedTime || this.fragmentSelectedTime <= 0) {
      this.message.create('warning', '请先选择时间节点');
      return;
    }

    const video = this.fragmentVideoElement;
    
    // 设置预览目标时间
    this.previewTargetTime = this.fragmentSelectedTime;
    this.isPreviewing = true;
    
    // 跳转到0秒并开始播放
    video.currentTime = 0;
    video.play().then(() => {
      this.message.create('info', '开始预览，将播放到 ' + this.formatTime(this.previewTargetTime));
    }).catch((error) => {
      console.error('播放失败:', error);
      this.message.create('error', '播放失败，请检查视频');
      this.isPreviewing = false;
    });
  }

  // 轨道拖动开始
  onFragmentTrackStart() {
    this.isDraggingTrack = true;
  }

  // 轨道拖动中
  onFragmentTrackChange(value: number) {
    this.fragmentSelectedTime = value;
    if (this.fragmentVideoElement) {
      this.fragmentVideoElement.currentTime = value;
    }
    // 滚动到对应的缩略图
    this.scrollToActiveThumbnail();
  }

  // 轨道拖动结束
  onFragmentTrackEnd() {
    this.isDraggingTrack = false;
    if (this.fragmentVideoElement) {
      this.fragmentVideoElement.currentTime = this.fragmentSelectedTime;
    }
  }

  onVideoIsAccessibleInCDN(url: string) {
    console.log('视频已上传到CDN:', url);
    this.fragmentVideoUrl = url;
    this.changeDetectorRef.detectChanges();
  }

  // 格式化时间显示
  formatTime(seconds: number): string {
    if (!seconds || isNaN(seconds)) {
      return '00:00';
    }
    const mins = Math.floor(seconds / 60);
    const secs = Math.floor(seconds % 60);
    return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
  }

  // 生成视频帧缩略图
  async generateVideoThumbnails() {
    if (!this.fragmentVideoElement) {
      return;
    }
    
    // 如果视频时长还没有获取到，尝试从视频元素获取
    if (!this.fragmentVideoDuration && this.fragmentVideoElement.duration) {
      this.fragmentVideoDuration = this.fragmentVideoElement.duration;
    }
    
    if (!this.fragmentVideoDuration || this.fragmentVideoDuration <= 0) {
      console.warn('视频时长未获取到，无法生成缩略图');
      return;
    }

    // 检查缓存
    const videoUrl = this.item.video_url ? this.item.video_url.replace('.mp4', '_h.mp4') : '';
    const cachedData = this.thumbnailCache.get(videoUrl);
    if (cachedData && cachedData.thumbnails.length > 0) {
      console.log('使用缓存的缩略图，跳过生成');
      this.videoThumbnails = cachedData.thumbnails;
      this.thumbnailCount = cachedData.count;
      this.changeDetectorRef.detectChanges();
      return;
    }

    this.isGeneratingThumbnails = true;
    this.videoThumbnails = [];
    
    const video = this.fragmentVideoElement;
    
    // 确保设置 crossOrigin 属性
    if (!video.crossOrigin) {
      video.crossOrigin = 'anonymous';
      // 如果视频已经加载，需要重新加载
      if (video.readyState >= 2) {
        const currentSrc = video.src;
        video.src = '';
        video.crossOrigin = 'anonymous';
        video.src = currentSrc;
        // 等待视频重新加载
        await new Promise((resolve, reject) => {
          const onLoadedMetadata = () => {
            video.removeEventListener('loadedmetadata', onLoadedMetadata);
            video.removeEventListener('error', onError);
            resolve(null);
          };
          const onError = () => {
            video.removeEventListener('loadedmetadata', onLoadedMetadata);
            video.removeEventListener('error', onError);
            reject(new Error('视频重新加载失败'));
          };
          video.addEventListener('loadedmetadata', onLoadedMetadata);
          video.addEventListener('error', onError);
        });
      }
    }
    
    const canvas = document.createElement('canvas');
    const ctx = canvas.getContext('2d');
    canvas.width = 160; // 缩略图宽度
    canvas.height = 90; // 缩略图高度 (16:9 比例)

    this.thumbnailCount = Math.round(this.fragmentVideoDuration);
    const interval = this.fragmentVideoDuration / this.thumbnailCount;
    const originalTime = video.currentTime;
    const originalPaused = video.paused;

    // 暂停视频
    if (!video.paused) {
      video.pause();
    }

    // 逐个提取帧
    try {
      for (let i = 0; i < this.thumbnailCount; i++) {
        const time = i * interval;
        await this.seekToTime(video, time);
        
        // 等待视频帧加载
        await new Promise(resolve => setTimeout(resolve, 100));
        
        // 绘制当前帧到 canvas
        ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
        
        // 转换为 base64 图片，添加错误处理
        try {
          const thumbnail = canvas.toDataURL('image/jpeg', 0.7);
          this.videoThumbnails.push(thumbnail);
        } catch (error) {
          console.error('生成缩略图失败 (可能是跨域问题):', error);
          // 如果跨域问题无法解决，使用占位符
          this.videoThumbnails.push('data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTYwIiBoZWlnaHQ9IjkwIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciPjxyZWN0IHdpZHRoPSIxNjAiIGhlaWdodD0iOTAiIGZpbGw9IiNlZWUiLz48dGV4dCB4PSI1MCUiIHk9IjUwJSIgZm9udC1zaXplPSIxNCIgZmlsbD0iIzk5OSIgdGV4dC1hbmNob3I9Im1pZGRsZSIgZHk9Ii4zZW0iPuaXoOazleWKoOi9veWbvueJhzwvdGV4dD48L3N2Zz4=');
        }
        
        // 更新视图
        this.changeDetectorRef.detectChanges();
      }
    } catch (error) {
      console.error('生成缩略图过程中出错:', error);
      this.message.create('error', '生成缩略图失败，可能是跨域问题。请确保视频服务器支持 CORS。');
    }

    // 恢复视频状态
    if (!originalPaused) {
      video.play();
    } else {
      await this.seekToTime(video, originalTime);
    }

    // 将生成的缩略图存入缓存
    if (this.videoThumbnails.length > 0) {
      const videoUrl = this.item.video_url ? this.item.video_url.replace('.mp4', '_h.mp4') : '';
      const cacheData = {
        thumbnails: [...this.videoThumbnails], // 创建副本避免引用问题
        duration: this.fragmentVideoDuration,
        count: this.thumbnailCount
      };
      this.thumbnailCache.set(videoUrl, cacheData);
      // 同时保存到 localStorage
      this.saveThumbnailCacheToLocalStorage(videoUrl, cacheData);
      console.log('缩略图已缓存，视频URL:', videoUrl, '缩略图数量:', this.videoThumbnails.length);
    }

    this.isGeneratingThumbnails = false;
    this.changeDetectorRef.detectChanges();
  }

  // 跳转到指定时间
  seekToTime(video: HTMLVideoElement, time: number): Promise<void> {
    return new Promise((resolve) => {
      const onSeeked = () => {
        video.removeEventListener('seeked', onSeeked);
        resolve();
      };
      video.addEventListener('seeked', onSeeked);
      video.currentTime = time;
    });
  }

  // 点击缩略图跳转到对应时间
  onThumbnailClick(time: number) {
    this.fragmentSelectedTime = time;
    if (this.fragmentVideoElement) {
      this.fragmentVideoElement.currentTime = time;
    }
    // 点击时也滚动到该缩略图（虽然已经在可视区域，但可以确保居中）
    setTimeout(() => {
      this.scrollToActiveThumbnail();
    }, 100);
  }

  // 滚动到激活的缩略图位置（居中显示）
  scrollToActiveThumbnail() {
    if (!this.thumbnailContainer || !this.fragmentVideoDuration || this.thumbnailCount <= 0) {
      return;
    }

    const container = this.thumbnailContainer.nativeElement;
    const selectedIndex = Math.floor(this.fragmentSelectedTime);
    
    // 确保索引在有效范围内
    if (selectedIndex < 0 || selectedIndex >= this.videoThumbnails.length) {
      return;
    }

    const thumbnailElement = document.getElementById(`thumbnail-${selectedIndex}`);
    if (!thumbnailElement) {
      return;
    }

    // 计算滚动位置，使缩略图居中
    const containerRect = container.getBoundingClientRect();
    const thumbnailRect = thumbnailElement.getBoundingClientRect();
    const containerScrollLeft = container.scrollLeft;
    const containerWidth = containerRect.width;
    const thumbnailWidth = thumbnailRect.width;
    const thumbnailLeft = thumbnailElement.offsetLeft;

    // 计算目标滚动位置：缩略图中心对齐容器中心
    const targetScrollLeft = thumbnailLeft - (containerWidth / 2) + (thumbnailWidth / 2);

    // 平滑滚动
    container.scrollTo({
      left: targetScrollLeft,
      behavior: 'smooth'
    });
  }

  // 获取缩略图对应的时间
  getThumbnailTime(index: number): number {
    if (!this.fragmentVideoDuration || this.thumbnailCount <= 0) {
      return 0;
    }
    if (index >= this.thumbnailCount) {
      return this.fragmentVideoDuration;
    }
    // 使用与生成缩略图时相同的计算方式：每秒一张图
    // 索引0对应0秒，索引1对应1秒，索引2对应2秒...
    return index;
  }

  // 判断缩略图是否处于激活状态（当前时间在该帧范围内）
  isThumbnailActive(index: number): boolean {
    if (!this.fragmentVideoDuration || this.thumbnailCount <= 0) {
      return false;
    }
    const thumbnailTime = this.getThumbnailTime(index);
    // 由于每秒一张图，每个缩略图代表1秒的时间范围
    // 索引i代表时间[i, i+1)秒，最后一个索引代表[lastIndex, duration]秒
    // 使用向下取整来判断当前时间属于哪个缩略图
    const selectedIndex = Math.floor(this.fragmentSelectedTime);
    return selectedIndex === index;
  }

  initItem() {
   
  }




  templateTypeChange(e) {
    console.log("in templateTypeChange e: ", e);
    this.item.templateType = e;
    this.save();
  }






  createShell() {
    this.item.wordList.push({
      word: '',
      audio: '',
      backWord: '',
      backWordAudio: '',
    });
    this.save();
  }

  removeShell(idx) {
    this.item.wordList.splice(idx, 1);
    this.save();
  }


  ngOnChanges() {
  }

  ngOnDestroy() {
  }


  itemSplitTypeChange(e, it) {
    it.splitType = e;
    this.save();
  }
  videoTypeChange(e) {
    console.log('e: ', e);
    this.item.videoType = e;
    this.save();
  }

  addBtnClick() {
    this.item.quesArr.push({
      itemType: 'jump'
    });
    this.save();
  }



  deleteBtnClick(i) {
    this.item.quesArr.splice(i, 1);
    this.save();
  }



  radioChange(e, item, key) {
    console.log('e: ', e);
    item[key] = e;
    this.save();
  }

  onVideoUploadSuccess(e, item, key) {
    console.log('e: ', e);
    item[key] = e.url;
    this.save();
  }

  videoSeeked(e) {

  }

  videoError(e) {

  }

  videoLoaded(e, it) {

  }


  saveHotZone(group, e) {
    console.log('e: ', e);
    const {bgItem, hotZoneItemArr} = e;

    group.bgItem = bgItem;
    group.hotZoneItemArr = hotZoneItemArr;

    this.save();
  }

  saveHotZone2(group, e) {
    console.log('e2: ', e);
    const {bgItem, hotZoneItemArr} = e;

    group.bgItem2 = bgItem;
    group.hotZoneItemArr2 = hotZoneItemArr;

    this.save();
  }


  getLRC(evt) {
    this.item.lrcData = evt;
    this.save();

  }

  onVideoUploaded(res) {

    console.log('onVideoUploaded: ', res);

    this.item.video_url = res.url;
    this.save();
  }

  isTurnPageChange(e) {
    console.log("e: ", e);
  }
  

  onItemImgUploadSuccess(e, item, key='pic_url') {
    item[key] = e.url;
    // console.log('item: ', item);
    this.save();
  }

  onItemAudioUploadSuccess(e, item, key='audio_url') {
    item[key] = e.url;
    this.save();
    // console.log('item: ', item);
  }

  onDeletaImg(item, key) {
    delete item[key];
    this.save();
  }
  /**
   * 储存图片数据
   * @param e
   */
  onImageUploadSuccess(e) {


    this.item.video_cover_pic = e.url;
    this.save();
  }

  /**
   * 储存音频数据
   * @param e
   */
  onAudioUploadSuccess(e, key, it) {
    it[key] = e.url;
    this.save();
  }

  KKBtnClick(it) {
    this.curSelectItem = it;
    this.isShowKK = true
  }

  KKHandleCancel() {
    this.isShowKK = false;
    this.curSelectKK = null;
    this.curSelectItem = null;
  }

  KKHandleOk() {

    // if (!this.curSelectItem.KKText) {
    //   this.curSelectItem.KKText = '';
    // }
    this.curSelectItem.KKText = this.curSelectKK;
   
    this.KKHandleCancel();

    this.save();
  }
 
  saveItemText(it, key) {
    console.log('it: ', it);
    this.save();
  }

  getItemHasInputPic(it) {
    return it.labelArr && it.labelArr[0]?.type == 'inputPic';
  }

  getItemHasInputAudio(it) {
    return it.labelArr && it.labelArr[0]?.type == 'inputAudio';
  }

  getItemHasInputText(it) {
    return it.labelArr && it.labelArr[0]?.type == 'inputText';
  }

  getItemHasTargetType(it, targetType) {
    return it.labelArr && it.labelArr[0]?.type == targetType;
  }

  addListItem(it, key) {

    if (!it[key]) {
      it[key] = [];
    }
    it[key].push({});
  }

  deleteListItem(arr, i) {
    arr.splice(i, 1);
    // this.save();
  }
 

  showPreviewTemplate() {
    this.isPreviewTemplate = true;

      //正常模板显示 赋值数据
      if (this.baseData && this.item.tempItem) {

        this.tempItem = this.item.tempItem;
      } else {
        
        this.tempItem = {}
        this.tempItem.quesArr = [];
        // this.addOnePageBtnClick();
      }

  }

  hidePreviewTemplate() {
    this.isPreviewTemplate = false;
  }

  addOnePartBtnClick() {
    this.item.partArr.push( 
      {
        type: "text"
      }
    );
    
    this.save();
  }

  addOnePageBtnClick() {
 
    this.item.quesArr.push( 
      {
        questionArr: [
          {
            type: "select",
            text: "",
            optionArr: []
          }
        ]
      }
    );
    
    this.save();
  }

  addOneOption(ques) {
    if (!ques.optionArr) {
      ques.optionArr = [];
    }
    ques.optionArr.push({
    });
    this.save();
  }

  deleteOptionBtnClick(arr, i) {
    arr.splice(i, 1);
    this.save();
  }

  deletePartBtnClick(i) {
    this.item.partArr.splice(i, 1);
    this.save();
  }

  deletePageBtnClick(i) {
    this.item.quesArr.splice(i, 1);
    this.save();
  }

  // 添加题目到视频节点
  addOneQuestion(ques) {
    if (!ques.questionArr) {
      ques.questionArr = [];
    }
    ques.questionArr.push({
      type: "select",
      text: "",
      optionArr: []
    });
    this.save();
  }

  // 删除视频节点中的题目
  deleteQuestionBtnClick(ques, questionIndex) {
    if (ques.questionArr && ques.questionArr.length > questionIndex) {
      ques.questionArr.splice(questionIndex, 1);
      this.save();
    }
  }

  // 从总秒数获取分钟数
  getMinutes(ques): number {
    if (!ques.time) {
      return 0;
    }
    return Math.floor(ques.time / 60);
  }

  // 从总秒数获取秒数（小数部分）
  getSeconds(ques): number {
    if (!ques.time) {
      return 0;
    }
    return Math.round((ques.time % 60) * 10) / 10; // 保留一位小数
  }

  // 从分钟和秒更新总秒数
  updateTimeFromMinutesSeconds(ques, minutes: number, seconds: number) {
    const totalSeconds = (minutes || 0) * 60 + (seconds || 0);
    ques.time = totalSeconds;
    this.save();
  }

  checkboxChange(e, it, key) {
    console.log('e: ', e);

    it[key] = e;
    this.save();
  }

  addSubOptArr(option) {
    if (!option.subOptArr) {
      option.subOptArr = [];
    }

    option.subOptArr.push({});
  }

  /**
   * 储存数据
   */
  save() {

    (<any>window).courseware.setData(this.item, null, this.saveKey);

    this.refresh();
    console.log('this.item = ' + JSON.stringify(this.item));

    this.message.create('success', "保存成功");

  }

  /**
   * 刷新 渲染页面
   */
  refresh() {
    setTimeout(() => {
      this.appRef.tick();
    }, 1);
  }

  // 截图
  handleOnCapture(e) {
    console.log(e)
    const href = URL.createObjectURL(e)
    const box = document.createElement('a')
    box.download = this.item.title ? this.item.title + ".jpg" : "未命名" + ".jpg"
    box.href = href
    box.click()
  }

  /**
   * 储存图片数据
   * @param e
   */
  onImageUploadSuccess_new(e, index) {
    this.item.dataArr[index].cover = e.url
    this.save();
  }

  onVideoUploaded_new(e, index) {
    this.item.dataArr[index].video_url = e.url
    this.save();
  }

  /**
   * 删除卡片
   */
  onRemoveVideo() {

    
  }

  /** 添加卡片 */
  onAddData() {
    this.item.dataArr.push({
      title: "",
      cover: "",
      video_url: ""
    })
    this.save()
  }

  onParentRef(e) {
    const item = this.item;

    if (!item.file) return;
    const uploadXHRArgs:UploadXHRArgs={
      file: item.file,
      name:'file',
      onProgress:(en,file)=>{
        e.handleChange({
          file: file, 
          fileList: [file],
          type:"progress",
          event:en
        });
      },
      onSuccess(ret, file, xhr) {        
        e.handleChange({
          file: {...file,response:ret}, 
          fileList: [file],
          type:"success",
        });
      },
    }
    e.customReq(uploadXHRArgs);
    const upFile: UploadChangeParam = {
      file: item.file, 
      fileList: [item.file],
      type:"start"
    };
    e.handleChange(upFile);
  }

  onDragOver(event: DragEvent) {
    event.preventDefault();
  }


  onDrop(event: DragEvent) {
    event.preventDefault();
    const items = event.dataTransfer?.items;

    if (items) {
      this.handleItems(items);
    }
  }

  handleItems(items: DataTransferItemList) {
    for (let i = 0; i < items.length; i++) {
      const item = items[i];

      if (item.kind === "file") {
        const entry = item.webkitGetAsEntry();
        this.traverseFileTree(entry,item);
      }
    }
  }

  traverseFileTree(item: any,entity?:DataTransferItem) {
    if (item.isFile) {
      const file = entity.getAsFile();
      
      this.item.dataArr.push({
        title: item.name.replace(`.mp4`,``),
        cover: "",
        video_url: "",
        file: file,
        batch:true
      });
      this.save()
      // 处理文件，可以上传等操作
    } else if (item.isDirectory) {
      this.item.unitTitle = item.name;
      const directoryReader = item.createReader();
      directoryReader.readEntries((entries: any) => {
        for (let i = 0; i < entries.length; i++) {
          this.traverseFileTree(entries[i],entries[i]);
        }
      });
    }
  }



}
