import {
  Component,
  EventEmitter,
  Input,
  OnDestroy,
  OnChanges,
  OnInit,
  Output,
  ApplicationRef,
  ChangeDetectorRef,
  AfterViewInit
} from '@angular/core';
import { JsonPipe } from '@angular/common';
import { removeItemFromArr } from '../play/Unit';
import { resolve } from 'dns';
import { rejects } from 'assert';


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

  // 储存数据用
  saveKey = "OP72";
  // 储存对象
  item;


  fileList = [];

  typeArr = [];
  limit = 0;
  uploadData = {};
  bytes = 1024;

  root_group_arr = [];

  myContent = `
  注释：

    整体设置：
    （只添加一个大组）
    文本-1: 结束按钮文本
    音频-1: 开始引导音频
    音频-2: 结束引导音频

    内容数据：
    (有几道题添加几个大组)
    组-1:第一题
    文本-1: 第一组中间泡泡的文字
    图片-1: 第一组中间泡泡的图片
    
    子项组-1: 左右瓶子的图片和文字 (可能只有一个瓶子)
      -> 文本-1: 左边瓶子文本
      -> 图片-1: 左边瓶子图片

      -> 文本-2: 右边瓶子文本
      -> 图片-2: 右边瓶子图片
    
    ... （以此类推）


  `

  constructor(private appRef: ApplicationRef, private changeDetectorRef: ChangeDetectorRef) {

  }

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

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

  ngOnInit() {

    this.item = {};

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

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

      this.init();
      this.changeDetectorRef.markForCheck();
      this.changeDetectorRef.detectChanges();
      this.refresh();

    }, this.saveKey);
  }

  ngAfterViewInit() {



  }
  ngOnChanges() {
  }

  ngOnDestroy() {
  }


  init() {

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

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



  /**
   * 储存图片数据
   * @param e
   */
  onImageUploadSuccess(e, key, item=null) {
    if (!item) {
      item = this.item;
    }

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

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

  onWordAudioUploadSuccess(e, idx) {
    this.item.wordList[idx].audio = e.url;
    this.save();
  }

  onBackWordAudioUploadSuccess(e, idx) {
    this.item.wordList[idx].backWordAudio = e.url;
    this.save();
  }

  onVideoUploadSuccess(e, item=null) {

    console.log(' in onVideoUploadSuccess')
    if (!item) {
      item = this.item;
    }
    item.video_url = e.url;
    this.save();
  }


  saveFormGroup(e) {
    this.item.group_arr = e;
    this.save();
  }





  async uploadDirectorFinish(e) {
    console.log("in uploadDirectorFinish data: ", e);
    const textArr = this.getTextArr(e, '1');
    const imageArr = this.getImageArr(e, '1');
    const audioArr = this.getAudioArr(e, '1');

    // const group_arr = this.item.group_arr;

    if (!this.item.group_arr || this.item.group_arr.length == 0) {
      this.addGroupBtnClick();
    } 

    //模板自定义读取
    await this.setGroupByTextArr(textArr, this.item.group_arr);
    await this.setGroupByImageArr(imageArr, this.item.group_arr);
    await this.setGroupByAudioArr(audioArr, this.item.group_arr);

    console.log('textArr: ', textArr);
    console.log('imageArr: ', imageArr);
    console.log('audioArr: ', audioArr);
   
    this.save();
    
  }

  async setGroupByTextArr(subFileList, group_arr) {

    const text_arr = [];
    const len = 3;
    for (let i=0; i<len; i++) {
      if (!subFileList[i]) {
        break;
      }
      const text = await this.getFileTextValue(subFileList[i]);
      text_arr[i] = {value: text};
    }
    group_arr[0].text_arr = text_arr;
  }

  setGroupByAudioArr(subFileList, group_arr) {
    const audio_arr = [];
    const len = 3;
    for (let i=0; i<len; i++) {
      if (!subFileList[i]) {
        break;
      }
      const url = this.getFileAudioValue(subFileList[i]);
      audio_arr[i] = {value: url};
    }
    group_arr[0].audio_arr = audio_arr;
  }

  setGroupByImageArr(subFileList, group_arr) {
    const image_arr = [];
    const len = 1;
    for (let i=0; i<len; i++) {
      if (!subFileList[i]) {
        break;
      }
      const url = this.getFileImageValue(subFileList[i]);
      image_arr[i] = {value: url};
    }
    group_arr[0].image_arr = image_arr;
  }

  setGroupByVideoArr(subFileList, group_arr) {

  }

  async getFileTextValue(oneData) {

    const file = oneData.originFileObj;

    return new Promise((resolve, rejects) => {
      if (file.type.startsWith('text')) {
        const reader = new FileReader();
        reader.onload = (e) => {
          const fileContent = e.target.result;
          // console.log(fileContent);
          resolve(fileContent);
        };
        reader.readAsText(file);
      } else {
        resolve("");
      }

    })
  }

  getFileImageValue(oneData) {
    return oneData?.response?.url || '';  
  }
 
  getFileAudioValue(oneData) {
    return oneData?.response?.url || '';  
  }
 


  getTextArr(fileList, part=null) {
    const targetArr = fileList.filter(it => {
      const {originFileObj} = it;
      const index = originFileObj.type.indexOf("text");
      return (index != -1);
    })
    return this.filterPartByName(targetArr, part);
  }

  getAudioArr(fileList, part=null) {
    const targetArr = fileList.filter(it => {
      const {originFileObj} = it;
      const index = originFileObj.type.indexOf("audio");
      return (index != -1);
    })
    return this.filterPartByName(targetArr, part);
  }

  getImageArr(fileList, part=null) {
    const targetArr = fileList.filter(it => {
      const {originFileObj} = it;
      const index = originFileObj.type.indexOf("image");
      return (index != -1);
    })
    return this.filterPartByName(targetArr, part);
  }

  getVideoArr(fileList, part=null) {
    const targetArr = fileList.filter(it => {
      const {originFileObj} = it;
      const index = originFileObj.type.indexOf("video");
      return (index != -1);
    })
    return this.filterPartByName(targetArr, part);
  }

  filterPartByName(subFileList, part=null) {
    if (part == null) {
      return subFileList;
    }

    const newArr = subFileList.filter(it => {
      const {originFileObj} = it;
      const nameArr = originFileObj.name.split("_");
      const partId = nameArr[0];
      it.nameId = nameArr[1];
      return (partId == part);
    })
    return this.sortByNameId(newArr);
  }

  sortByNameId(arr) {
    arr.sort(function(a, b) {
      return a.nameId - b.nameId;
    });
    return arr;
  }




  addGroupBtnClick() {
    this.item.group_arr.push({
      text_arr: [],
      anim_arr: [],
      image_arr: [],
      audio_arr: [],
      video_arr: [],
      sub_group_arr: [],
    })

    this.save();
  }

  handleChange(e) {
    console.log("e: ", e);
  }
 
  handlePreview(e) {
    console.log(" handlePreview e: ", e);
  }
 
  handleRemove(e) {
    console.log("handleRemove e: ", e);
  }
 
  handleUpload(e) {
    console.log("handleUpload e: ", e);
  }
 
  handleError(e) {
    console.log("handleError e: ", e);
  }
 


  beforeUpload() {
    
  }

  removeFile(file) {

  }

  preview(file) {

  }

  remove(file) {

  }

  customReq(it) {

  }

  headers(file) {

  }





  saveFormGroupGlobal(e) {
    console.log("root e: ", e);
    this.item.global_setting = e;
    this.save();
  }

  async uploadDirectorFinishGlobal(e) {
    console.log("in uploadDirectorFinishRoot data: ", e);
 
    
  }






  /**
   * 储存数据
   */
  save() {
    (<any>window).courseware.setData(this.item, null, this.saveKey);

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

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

}
