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


@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 = [];

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

  }


  ngOnInit() {

    this.getBookTextLis();
   
  

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

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

  onSelectWordChange(e, ques, key='data') {
    console.log('e: ', e);
    ques[key] = e;
    ques.text = null;
    ques.translation = null;
    ques.audio_url = null;
    ques.pic_url = null;
    ques.optionCount = 0;
    ques.optionArr = [];
   this.refreshQuesRes(ques);

   this.autoFillOption(ques);


    this.save();
  }

  setOptionCount(e, ques) {

    // 判断 最小0 最大10
    ques.optionCount = Number(e.target.value < 0 ? 0 : e.target.value);

    console.log('ques.optionArr.length: ', ques.optionArr.length);

    this.autoFillOption(ques);
    this.save();
  }

  autoFillText(ques) {
    const tempList = ques.text.split('');
    ques.optionCount = tempList.length;
    
    ques.optionArr = [];
    for (let i = 0; i < ques.optionCount; i++) {
      ques.optionArr.push({
        text: tempList[i],
      });
    }

    this.save();
  }

  autoFillOption(ques) {

    if (ques.optionTypeText) {
        
      if (ques.optionCount <= 0) {  
        const tempList = ques.text.split(' ');
        ques.optionCount = tempList.length;
        
        for (let i = 0; i < ques.optionCount; i++) {
          ques.optionArr.push({
            text: tempList[i],
          });
        }
      }
    } 

    if (ques.optionArr.length > ques.optionCount) {
      ques.optionArr.length = ques.optionCount;
    } else if (ques.optionArr.length < ques.optionCount) {
      for (let i = ques.optionArr.length; i < ques.optionCount; i++) {
        ques.optionArr.push({
          
        });
      }
    }
    

    // if (ques.optionArr.length == 0) {
    //   console.log('add ...');
    //     ques.optionArr.push(
    //     {
    //       wordData: ques.wordData,
    //       answer: 'isRight'
    //     }
    //   );
    // }

    // if (ques.optionArr.length > ques.optionCount) {
    //   ques.optionArr.length = ques.optionCount;
    // } else if (ques.optionArr.length < ques.optionCount) {
    //   for (let i = ques.optionArr.length; i < ques.optionCount; i++) {
    //     ques.optionArr.push({
    //       answer: 'isWrong',
    //       wordData: this.getUnusedWord(ques),
    //     });
    //   }
    // }

    // this.refreshOptionRes(ques);
  }

 /**
 * 获取一个未在选项数组中使用过的单词
 * @param ques 问题对象,包含 optionArr 选项数组
 * @returns 返回一个未使用的单词对象,如果所有单词都已使用则返回 null
 */
getUnusedWord(ques: any): any {
  // 获取选项数组中已使用的所有单词
  const usedWords = ques.optionArr.map(option => option.wordData?.word);
  
  // 从 curBookWords 中过滤出未使用的单词
  const availableWords = this.curBookWords.filter(word => 
    !usedWords.includes(word.word)
  );
  
  // 如果没有可用的未使用单词,返回 null
  if (availableWords.length === 0) {
    return null;
  }
  
  // 从可用单词中随机返回一个
  const randomIndex = Math.floor(Math.random() * availableWords.length);
  return availableWords[randomIndex];
}




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


    // 使用Promise方式的GET请求
    getDataPromise(url, params: any): Promise<any> {

      let httpParams = new HttpParams();
      Object.keys(params).forEach(key => {
        httpParams = httpParams.append(key, params[key]);
      });
  
      return this.http.get(`${this.baseUrl}/${url}`, { params: httpParams })
        .toPromise()
        .then(response => {
          this.message.success('获取成功');
          return response;
        })
        .catch(error => {
          this.message.error('获取失败');
          throw error;
        });
    }

    getBookDefalutData() {

      return [
        {
          "id": 1,
          "pictureBookId": 101,
          "word": "elephant",
          "partOfSpeech": "noun",
          "wordTranslation": "大象",
          "exampleSentence": "The elephant is the largest land animal.",
          "wordAudioUrl": "https://staging-teach.cdn.ireadabc.com/614039db2e4c4798c4b47f9d7f10a07f.mp3",
          "exampleSentenceAudioUrl": "https://audio.com/elephant-sentence.mp3",
          "exampleSentenceTranslation": "大象是最大的陆地动物。",
          "imageUrl": "https://staging-teach.cdn.ireadabc.com/deecc7b9fcbb93cdd40cf6f8a07f7942.jpeg",
          "britishPhonetic": "ˈelɪfənt",
          "americanPhonetic": "ˈeləfənt",
          "englishDefinition": "A very large plant-eating mammal with a prehensile trunk",
          "backContent": {},
          "createdTime": "2024-03-15T08:30:00.000Z"
        },
        {
          "id": 2,
          "pictureBookId": 101,
          "word": "giraffe",
          "partOfSpeech": "noun",
          "wordTranslation": "长颈鹿",
          "exampleSentence": "The giraffe has a very long neck.",
          "wordAudioUrl": "https://staging-teach.cdn.ireadabc.com/c18e34fbfe55871a998136eaa7f66e38.mp3",
          "exampleSentenceAudioUrl": "https://audio.com/giraffe-sentence.mp3",
          "exampleSentenceTranslation": "长颈鹿有着很长的脖子。",
          "imageUrl": "https://staging-teach.cdn.ireadabc.com/954c6daccc0ab7da9c80f2d48c339a16.jpeg",
          "britishPhonetic": "dʒɪˈrɑːf",
          "americanPhonetic": "dʒəˈræf",
          "englishDefinition": "A large African mammal with a very long neck and legs",
          "backContent": {},
          "createdTime": "2024-03-15T08:31:00.000Z"
        },
        {
          "id": 3,
          "pictureBookId": 101,
          "word": "penguin",
          "partOfSpeech": "noun",
          "wordTranslation": "企鹅",
          "exampleSentence": "The penguin waddles across the ice.",
          "wordAudioUrl": "https://staging-teach.cdn.ireadabc.com/7ef29a4858d8f8593ddd14b78b114620.mp3",
          "exampleSentenceAudioUrl": "https://audio.com/penguin-sentence.mp3",
          "exampleSentenceTranslation": "企鹅在冰面上摇摇摆摆地走。",
          "imageUrl": "https://staging-teach.cdn.ireadabc.com/73c1a51a2727df3e296d6f682e0f74c0.jpeg",
          "britishPhonetic": "ˈpeŋɡwɪn",
          "americanPhonetic": "ˈpeŋɡwɪn",
          "englishDefinition": "A flightless aquatic bird of the Southern Hemisphere",
          "backContent": {},
          "createdTime": "2024-03-15T08:32:00.000Z"
        },
        {
          "id": 4,
          "pictureBookId": 101,
          "word": "butterfly",
          "partOfSpeech": "noun",
          "wordTranslation": "蝴蝶",
          "exampleSentence": "A beautiful butterfly landed on the flower.",
          "wordAudioUrl": "https://staging-teach.cdn.ireadabc.com/b195f83341ea48c59bb1d7bc36224703.mp3",
          "exampleSentenceAudioUrl": "https://audio.com/butterfly-sentence.mp3",
          "exampleSentenceTranslation": "一只美丽的蝴蝶落在花朵上。",
          "imageUrl": "https://staging-teach.cdn.ireadabc.com/d084a9eaa9cccd4b94f96f1220c2bd4b.jpeg",
          "britishPhonetic": "ˈbʌtəflaɪ",
          "americanPhonetic": "ˈbʌtərflaɪ",
          "englishDefinition": "An insect with two pairs of large wings that are often brightly colored",
          "backContent": {},
          "createdTime": "2024-03-15T08:33:00.000Z"
        },
        {
          "id": 5,
          "pictureBookId": 101,
          "word": "dolphin",
          "partOfSpeech": "noun",
          "wordTranslation": "海豚",
          "exampleSentence": "The dolphin jumped high out of the water.",
          "wordAudioUrl": "https://staging-teach.cdn.ireadabc.com/8ce06364d3384544e136e3d8579f520b.mp3",
          "exampleSentenceAudioUrl": "https://audio.com/dolphin-sentence.mp3",
          "exampleSentenceTranslation": "海豚从水中高高跃起。",
          "imageUrl": "https://staging-teach.cdn.ireadabc.com/84995798a53e78f74a9e297c684fa890.jpeg",
          "britishPhonetic": "ˈdɒlfɪn",
          "americanPhonetic": "ˈdɑːlfɪn",
          "englishDefinition": "A marine mammal known for its intelligence and playfulness",
          "backContent": {},
          "createdTime": "2024-03-15T08:34:00.000Z"
        }

      ]


    }


  // callAPIGetData(url, params: any) {
  //   // 构建查询参数
  //   let httpParams = new HttpParams();
  //   Object.keys(params).forEach(key => {
  //     httpParams = httpParams.append(key, params[key]);
  //   });

  //   // 配置请求头
  //   const headers = new HttpHeaders()
  //     // .set('Authorization', 'Bearer ' + localStorage.getItem('token'));

  //   // 发起GET请求
  //   this.http.get(`${this.baseUrl}/url`, { 
  //     headers,
  //     params: httpParams
  //   }).subscribe({
  //     next: (response: any) => {
  //       console.log('获取数据成功:', response);
  //       this.message.success('获取成功');
  //       // 处理返回的数据
  //       return response;
  //     },
  //     error: (error) => {
  //       console.error('获取数据失败:', error);
  //       this.message.error('获取失败: ' + error.message);
  //     }
  //   });
  // }

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

  getBookTextLis() {
    console.log('in getBookTextLis');
   
    const call_back = (res) => {
      console.log('getBookTextLis res: ', res);
    };
   
    if ((<any>window).commonPostMessageWithCallback != null) {

      (<any>window).commonPostMessageWithCallback({
        action: 'getPictureBookTextList'
      }, call_back);
    } else {
      setTimeout(() => {
        this.getBookTextLis();
      }, 100);
    }


    // if ((<any>window).courseware.getPictureBookTextList) {
    //   (<any>window).courseware.getPictureBookTextList((data) => {
    //     console.log('getPictureBookTextList data: ', data);
    //   });
    // } else {
    //   console.log('not find getPictureBookTextList');
    // }
    
  }

}