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": 4,
  //             "text": "Hank Hammer"
  //         },
  //         {
  //             "number": 5,
  //             "text": "MEET THE TOOL TEAM"
  //         },
  //         {
  //             "number": 5,
  //             "text": "Tia Tape Measure"
  //         },
  //         {
  //             "number": 5,
  //             "text": "Hank Hammer"
  //         },
  //         {
  //             "number": 6,
  //             "text": "Sammy Saw"
  //         },
  //         {
  //             "number": 6,
  //             "text": "Sophie Screwdriver"
  //         },
  //         {
  //             "number": 7,
  //             "text": "Today is the big contest. Hank is very excited! He jumps out of bed."
  //         },
  //         {
  //             "number": 8,
  //             "text": "He brushes his teeth and gets ready."
  //         },
  //         {
  //             "number": 9,
  //             "text": "\"Have a fun day,\" his mom says."
  //         },
  //         {
  //             "number": 9,
  //             "text": "“Good luck at the contest.\""
  //         },
  //         {
  //             "number": 10,
  //             "text": "\"Thanks, Mom,\" Hank says as he rushes out the door."
  //         },
  //         {
  //             "number": 11,
  //             "text": "\"Hi, everyone! Are you ready for the big contest?\" asks Hank."
  //         },
  //         {
  //             "number": 12,
  //             "text": "\"We're ready!\" they yell."
  //         },
  //         {
  //             "number": 13,
  //             "text": "\"I have the wood,\" says Sammy."
  //         },
  //         {
  //             "number": 13,
  //             "text": "\"I have the nails,\" says Tia."
  //         },
  //         {
  //             "number": 14,
  //             "text": "“I have the red paint and the blue paint,\"says Sophie."
  //         },
  //         {
  //             "number": 15,
  //             "text": "“And I have the plans,\" says Hank."
  //         },
  //         {
  //             "number": 16,
  //             "text": "“We are going to build the best birdhouse!\"says Sammy."
  //         },
  //         {
  //             "number": 17,
  //             "text": "\"It's time to start,\"says Sophie."
  //         },
  //         {
  //             "number": 17,
  //             "text": "\"What do we do?\" asks Tia."
  //         },
  //         {
  //             "number": 18,
  //             "text": "“Just follow my plan,\" says Hank."
  //         },
  //         {
  //             "number": 18,
  //             "text": "“I have everything mapped out right here.\""
  //         },
  //         {
  //             "number": 19,
  //             "text": "“First, we measure everything,\""
  //         },
  //         {
  //             "number": 19,
  //             "text": "says Hank."
  //         },
  //         {
  //             "number": 20,
  //             "text": "\"That's my job,\" says Tia."
  //         },
  //         {
  //             "number": 20,
  //             "text": "“Great!\"says Hank."
  //         },
  //         {
  //             "number": 21,
  //             "text": "\"Next, we cut the wood,\""
  //         },
  //         {
  //             "number": 21,
  //             "text": "says Hank."
  //         },
  //         {
  //             "number": 22,
  //             "text": "\"That's my job,\" says Sammy."
  //         },
  //         {
  //             "number": 22,
  //             "text": "\"Great!\" says Hank."
  //         },
  //         {
  //             "number": 23,
  //             "text": "\"Then, we put the house together,\""
  //         },
  //         {
  //             "number": 23,
  //             "text": "says Hank."
  //         },
  //         {
  //             "number": 24,
  //             "text": "“I'll hold the nails. You can pound them in,\"says Sophie."
  //         },
  //         {
  //             "number": 24,
  //             "text": "\"Great!\"says Hank."
  //         },
  //         {
  //             "number": 25,
  //             "text": "\"Now we paint it,\" says Hank."
  //         },
  //         {
  //             "number": 26,
  //             "text": "\"We can all do that,\" says Sophie."
  //         },
  //         {
  //             "number": 26,
  //             "text": "\"Great!\" says Hank."
  //         },
  //         {
  //             "number": 27,
  //             "text": "The birdhouse is done. The tool team sets it on the table next to the other ones."
  //         },
  //         {
  //             "number": 28,
  //             "text": "\"It's prefect,\"says Hank."
  //         },
  //         {
  //             "number": 29,
  //             "text": "“I think we built the best one,\""
  //         },
  //         {
  //             "number": 29,
  //             "text": "says Sammy."
  //         },
  //         {
  //             "number": 30,
  //             "text": "\"And we did it together,\" says Tia."
  //         },
  //         {
  //             "number": 31,
  //             "text": "\"I have one more thing to add,\""
  //         },
  //         {
  //             "number": 31,
  //             "text": "says Hank."
  //         },
  //         {
  //             "number": 32,
  //             "text": "\"Now it's perfect,\" says Sammy."
  //         }
  //     ]
  // }
  //   this.bookTextList = resData1.data;
    

  //   this.bookTextList = this.filterDuplicateText( 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 targetLength = arr.length - 4;
    if (targetLength % 2 !== 0) {
      targetLength--; // 确保是双数
    }
  
    // // 计算可以开始截取的最大起始位置
    // const maxStartIndex = arr.length - targetLength;
    // 随机选择一个起始位置
    const startIndex = Math.floor(Math.random() * targetLength);
    
    // 截取数组
    return arr.slice(startIndex, startIndex + targetLength);
  }

}