import { Component, EventEmitter, Input, OnDestroy, OnChanges, OnInit, Output, ApplicationRef, ChangeDetectorRef } 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";

  baseData;
  
  // 储存对象
  item: any = {
    video_url: "",
    cover: "",
    title: "",
    video_title: "",
  };
  //临时储存对象
  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; // 生成的缩略图数量






  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() {


    // 获取存储的数据
    (<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 || '';
    this.fragmentVideoCurrentTime = ques.time || 0;
    this.fragmentSelectedTime = ques.time || 0;
    this.videoThumbnails = [];
    this.isFragmentModalVisible = true;
    
    // 等待弹窗渲染后获取视频元素并生成缩略图
    setTimeout(() => {
      this.fragmentVideoElement = document.getElementById('fragment-video') as HTMLVideoElement;
      if (this.fragmentVideoElement) {
        if (this.fragmentSelectedTime > 0) {
          this.fragmentVideoElement.currentTime = this.fragmentSelectedTime;
        }
        // 生成视频帧缩略图
        this.generateVideoThumbnails();
      }
    }, 100);
  }

  // 视频片段弹窗 - 取消
  fragmentModalCancel() {
    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;
  }

  // 视频片段弹窗 - 确认
  fragmentModalOk() {
    if (this.currentFragmentQues) {
      this.currentFragmentQues.time = this.fragmentSelectedTime;
      this.save();
    }
    this.fragmentModalCancel();
  }

  // 视频加载元数据
  onFragmentVideoLoadedMetadata(event) {
    const video = event.target;
    this.fragmentVideoDuration = video.duration || 0;
    this.fragmentVideoElement = video;
    if (this.fragmentSelectedTime > 0) {
      video.currentTime = this.fragmentSelectedTime;
    }
  }

  // 视频时间更新
  onFragmentVideoTimeUpdate(event) {
    if (!this.isDraggingTrack) {
      const video = event.target;
      this.fragmentVideoCurrentTime = video.currentTime;
      this.fragmentSelectedTime = video.currentTime;
    }
  }

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

  // 轨道拖动中
  onFragmentTrackChange(value: number) {
    this.fragmentSelectedTime = value;
    if (this.fragmentVideoElement) {
      this.fragmentVideoElement.currentTime = value;
    }
  }

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

  // 格式化时间显示
  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 || !this.fragmentVideoDuration) {
      return;
    }

    this.isGeneratingThumbnails = true;
    this.videoThumbnails = [];
    
    const video = this.fragmentVideoElement;
    const canvas = document.createElement('canvas');
    const ctx = canvas.getContext('2d');
    canvas.width = 160; // 缩略图宽度
    canvas.height = 90; // 缩略图高度 (16:9 比例)

    const interval = this.fragmentVideoDuration / this.thumbnailCount;
    const originalTime = video.currentTime;
    const originalPaused = video.paused;

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

    // 逐个提取帧
    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 图片
      const thumbnail = canvas.toDataURL('image/jpeg', 0.7);
      this.videoThumbnails.push(thumbnail);
      
      // 更新视图
      this.changeDetectorRef.detectChanges();
    }

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

    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;
    }
  }

  // 获取缩略图对应的时间
  getThumbnailTime(index: number): number {
    if (!this.fragmentVideoDuration) {
      return 0;
    }
    if (index >= this.thumbnailCount) {
      return this.fragmentVideoDuration;
    }
    return (index * this.fragmentVideoDuration) / this.thumbnailCount;
  }

  // 判断缩略图是否处于激活状态（当前时间在该帧范围内）
  isThumbnailActive(index: number): boolean {
    if (!this.fragmentVideoDuration) {
      return false;
    }
    const currentTime = this.getThumbnailTime(index);
    const nextTime = index < this.thumbnailCount - 1 
      ? this.getThumbnailTime(index + 1) 
      : this.fragmentVideoDuration;
    return this.fragmentSelectedTime >= currentTime && this.fragmentSelectedTime < nextTime;
  }

  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() {

    // if (this.tempItem) {
    //   this.item.tempItem = this.tempItem;
    // }

    // if (this.customTypeGroupArr) {
    //   this.item.customTypeGroupArr = this.customTypeGroupArr;
    // }

    (<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();
  }

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

    
  }

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

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

    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]);
        }
      });
    }
  }



}
