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 { HttpClient, HttpHeaders, HttpParams } from '@angular/common/http';
import { URLSearchParams } from 'url';

// 在文件顶部，import 语句下面，组件类之前声明
declare function commonPostMessageWithCallback(params: any, callback: (res: any) => void): void;

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

  // 储存数据用
  saveKey = "JJ_Game_Parent_Child";

  
  // 储存对象
  item;
  //临时储存对象
  tempItem;


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



  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: '第二遍结束音频'},
  ]

 // API基础地址
 private baseUrl = 'http://staging-teach.ireadabc.com';

 curBookWords = [];
 selectedWord: any; 
  bookTextList = [];
  randomSentenceList = [];

  
  constructor(private appRef: ApplicationRef, private changeDetectorRef: ChangeDetectorRef, 
    private message: NzMessageService, private http: HttpClient) {

  }


  ngOnInit() {

    this.getBookTextList();
   
  

    this.item = {};

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


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

      this.initItem();


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

  initItem() {
   
  }

  autoFill()
  {

    this.item.quesArr = [];

    this.addOnePageBtnClick(false);

    const ques = this.item.quesArr[0];
    this.randomSentenceList = this.getRandomList(this.bookTextList);

    if (this.randomSentenceList.length > 10) {
      this.randomSentenceList.length = 10;
    }

    console.log('this.randomSentenceList : ' + this.randomSentenceList );

    ques.optionArr = [];
    for (let i = 0; i <  this.randomSentenceList.length; i++) {
      ques.optionArr.push({
        text: this.randomSentenceList[i].text,
      });
    }

    console.log('this.item: ' , this.item);
    this.save();
    
  }

  filterDuplicateText(arr: any[]): any[] {
    // 使用 Map 来记录已经出现过的 text
    const textMap = new Map();
    
    // 使用 filter 过滤数组
    return arr.filter(item => {
      // 如果这个 text 还没有出现过，就把它加入 Map 并保留这个元素
      if (!textMap.has(item.text)) {
        textMap.set(item.text, true);
        return true;
      }
      // 如果这个 text 已经出现过，就过滤掉这个元素
      return false;
    });
  }


  init() {

    if (!this.item.quesArr) {
      this.item.quesArr = [];
    }

    // this.getDataPromise('e-library/v1/factory/word-exercise-cards', {
    // });

    // this.curBookWords = this.getBookDefalutData();

  }




  ngOnChanges() {
  }

  ngOnDestroy() {
  }

  compareWord(word1: any, word2: any): boolean {
    return (word1 && word2) ? word1.word === word2.word : word1 === word2;
  }







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

  }




  onVideoUploaded(res, item, key) {
    if (!item) {
      item = this.item;
    }
    console.log('onVideoUploaded: ', res);

    item[key] = res.url;
    this.save();
  }


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


  onDeleteVideo(item, key) {
    item[key] = '';
    this.save();
  }

  /**
   * 储存图片数据
   * @param e
   */
  onImageUploadSuccess(e, key, item) {

    if (!item) {
      item = this.item;
    }
    item[key] = e.url;
    this.save();
  }

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



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


 


  addOnePageBtnClick(isSave = true) {
 
    const ques = {
      optionArr:[],
      quesTypeText: true,
      quesTypeAudio: true,
      quesTypePic: true,
      optionCount: 0,
      optionTypeText: true,
      optionTypeAudio: false,
      optionTypePic: false,
      video_url:''
    };
    this.item.quesArr.push( 
      ques
    );
    


    // this.refreshQuesRes();
    if (isSave) {
      this.save();
    }
  }

  addOneOption(ques) {
    ques.optionArr.push({
      answer: 'isWrong',
      isFill: false
    });
    this.save();
  }

  deleteOptionBtnClick(ques, i) {
    ques.optionArr.splice(i, 1);
    ques.optionCount = ques.optionArr.length;
    this.save();
  }

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

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

    it[key] = e;

    this.refreshQuesRes(it);

    this.save();
  }

  refreshQuesRes(ques) {
    return;
    if (ques.quesTypeText) {
      if (!ques.text) {
        ques.text = ques.wordData.exampleSentence;
      }

      if (!ques.translation) {
        ques.translation = ques.wordData.exampleSentenceTranslation;
      }
    }
    if (ques.quesTypeAudio && !ques.audio_url) {
      ques.audio_url = ques.wordData.wordAudioUrl;
    }
    if (ques.quesTypePic && !ques.pic_url) {
      ques.pic_url = ques.wordData.imageUrl;
    }

  }

  refreshOptionRes(ques) {
    ques.optionArr.forEach(option => {
      if (ques.optionTypeText) {
        if (!option.text) {
          option.text = option.wordData.word;
        }
        if (!option.translation) {
          option.translation = option.wordData.wordTranslation;
        }
      }
      if (ques.optionTypeAudio && !option.audio_url) {
        option.audio_url = option.wordData.wordAudioUrl;
      }
      if (ques.optionTypePic && !option.pic_url) {
        option.pic_url = option.wordData.imageUrl;
      }
    });
  }

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

    it[key] = e;

    this.refreshOptionRes(it);
    this.save();
  }



  /**
   * 储存数据
   */
  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);
  }

  getBookTextList() {

    // let resData1 =  

    // {
    //   "msg": "success",
    //   "data": [
    //     {
    //       "number": 3,
    //       "text": "Mara the Mermaid Meets a Sea Turtle"
    //     },
    //     {
    //       "number": 5,
    //       "text": "I see a sea turtle!"
    //     },
    //     {
    //       "number": 6,
    //       "text": "I see one green sea turtle, and one brown sea turtle."
    //     },
    //     {
    //       "number": 8,
    //       "text": "I see four long flippers."
    //     },
    //     {
    //       "number": 10,
    //       "text": "I see one big shell."
    //     },
    //     {
    //       "number": 12,
    //       "text": "I see many little eggs."
    //     },
    //     {
    //       "number": 14,
    //       "text": "I see a sea turtle eating seaweed!"
    //     }
    //   ]
    // }
    // this.bookTextList = resData1.data;
    

    // this.bookTextList = this.filterDuplicateText( this.bookTextList);


    // console.log('this.bookTextList: ', this.bookTextList);
  
    
    // return;

    console.log(' in getBookTextList');
    const call_back = (res) => {
      console.log('getBookTextList res: ', res);

      const resData = JSON.parse(res);
      if (resData.msg == 'success') {

        this.bookTextList = resData.data;
        // this.getRandomList(resData.data);
      }
    };

    // 检查方法是否存在
    const checkAndCall = () => {
      if (typeof commonPostMessageWithCallback === 'function') {
        commonPostMessageWithCallback({
          action: 'getPictureBookTextList'
        }, call_back);
      } else {
        // setTimeout(checkAndCall, 100);
      }
    };

    checkAndCall();

    this.bookTextList = this.filterDuplicateText( this.bookTextList);

  }

  getRandomList(arr) {
    if (!arr || arr.length <= 4) {
      return arr;
    }
  
    // 计算需要返回的数组长度（原数组长度减4，并确保是双数）
    let startMaxLength = arr.length - 4;
    // if (startMaxLength % 2 !== 0) {
    //   startMaxLength--; // 确保是双数
    // }
  
    // // 计算可以开始截取的最大起始位置
    // const maxStartIndex = arr.length - targetLength;
    // 随机选择一个起始位置
    const startIndex = Math.floor(Math.random() * startMaxLength);
    const minEndIndex = startIndex + 4;
    const maxEndIndex = arr.length;
    const endIndex = Math.floor(Math.random() * (maxEndIndex - minEndIndex)) + minEndIndex;
    
    // 截取数组
    // return arr.slice(startIndex, startIndex + startMaxLength);
    const randomArr =  arr.slice(startIndex, endIndex);
    console.log('randomArr: ', randomArr);

    if (randomArr.length % 2 !== 0) {
      randomArr.length--; // 确保是双数
    }
    return randomArr;
  }

}