import {Component, EventEmitter, Input, OnDestroy, OnChanges, OnInit, Output, ApplicationRef, ElementRef, ViewChild} from '@angular/core';
import { defaultData } from '../../assets/default/formData/defaultData.js'

@Component({
  selector: 'app-form',
  templateUrl: './form.component.html',
  styleUrls: ['./form.component.scss']
})

export class FormComponent implements OnInit, OnChanges, OnDestroy {

  _item: any;
  hotZoneItemArrLeft: Array<Object> = [];
  questionsLeft;
  bgItemLeft: Object;

  hotZoneItemArrMiddle: Array<Object> = [];
  questionsMiddle;
  bgItemMiddle: Object;

  hotZoneItemArrRight: Array<Object> = [];
  questionsRight;
  bgItemRight: Object;

  title = {
    "NO": "C",
    "mainText": "",
    "mainTextAudio_url": ""
  };

  wordLeft_text;
  wordLeft_audio_url;
  wordMiddle_text;
  wordMiddle_audio_url;
  wordRight_text;
  wordRight_audio_url;

  longAudio_url;

  bgImages: Object = {leftTop:"", middleTop:"", rightTop:"", leftMiddle:"", rightMiddle:"", leftBottom:"", middleBottom:"", rightBottom:""};
  KEY = 'DataKey_YM4-13';

  set item(item) {
    this._item = item;
  }
  get item() {
    return this._item;
  }

  @Output()
  update = new EventEmitter();

  @ViewChild('hotZooLeftEL') hotZooLeftEL;
  @ViewChild('hotZooMiddleEL') hotZooMiddleEL;
  @ViewChild('hotZooRightEL') hotZooRightEL;

  constructor(private appRef: ApplicationRef) {

  }

  ngOnInit() {
    this.item = {};
    this.item.contentObj = {};
    const getData = (<any> window).courseware.getData;
    getData((data) => {
      // console.log("读取数据", data)
      if (data) {
        this.item = data;
      } else {
        this.item = {};
      }
      if ( !this.item.contentObj ) {
        this.item.contentObj = {};
      }
      this.init();
      this.refresh();
    }, this.KEY);
  }
  
  ngOnChanges() {

  }

  ngOnDestroy() {

  }

  addHotZoo(pos) {
    if(pos==1) {
      this.hotZooLeftEL.addHotZoo()
    } else if(pos==2) {
      this.hotZooMiddleEL.addHotZoo()
    } else if(pos==3) {
      this.hotZooRightEL.addHotZoo()
    }
  }

  backgroundImageChanged(e) {
    this.save()
  }

  handleTextChange(e, uid) {
    this.hotZooLeftEL.setTextByUID(e.target.value, uid)
    this.hotZooMiddleEL.setTextByUID(e.target.value, uid)
    this.hotZooRightEL.setTextByUID(e.target.value, uid)
    this.save()
  }

  deleteHotZoo(pos, index) {
    if(pos == 1) {
      this.hotZooLeftEL.deleteHotZoo(index)
    } else if(pos == 2) {
      this.hotZooMiddleEL.deleteHotZoo(index)
    } else if(pos == 3) {
      this.hotZooRightEL.deleteHotZoo(index)
    }
  }

  getQuestionWord(pos, combin) {
    let str = ""
    if(pos == 1) {
      combin.forEach(element => {
        if(element == -1) {
          str += this.wordLeft_text
        } else {
          str += this.hotZoneItemArrLeft[element] && this.hotZoneItemArrLeft[element]["media"] && this.hotZoneItemArrLeft[element]["media"]["text"]?this.hotZoneItemArrLeft[element]["media"]["text"]:"";
        }
      });
    } else if(pos == 2) {
      combin.forEach(element => {
        if(element == -1) {
          str += this.wordMiddle_text
        } else {
          str += this.hotZoneItemArrMiddle[element] && this.hotZoneItemArrMiddle[element]["media"] && this.hotZoneItemArrMiddle[element]["media"]["text"]?this.hotZoneItemArrMiddle[element]["media"]["text"]:"";
        }
      });
    } else if(pos == 3) {
      combin.forEach(element => {
        if(element == -1) {
          str += this.wordRight_text
        } else {
          str += this.hotZoneItemArrRight[element] && this.hotZoneItemArrRight[element]["media"] && this.hotZoneItemArrRight[element]["media"]["text"]?this.hotZoneItemArrRight[element]["media"]["text"]:"";
        }
      });
    }
    
    return str
  }

  saveData(e, pos){
    if(pos == 1) {
      this.bgItemLeft = e.bgItem;
      this.hotZoneItemArrLeft.length = 0;
      e.hotZoneItemArr.forEach(item => {
        this.hotZoneItemArrLeft.push(item)
      });
    } else if(pos == 2) {
      this.bgItemMiddle = e.bgItem;
      this.hotZoneItemArrMiddle.length = 0;
      e.hotZoneItemArr.forEach(item => {
        this.hotZoneItemArrMiddle.push(item)
      });
    } else if(pos == 3) {
      this.bgItemRight = e.bgItem;
      this.hotZoneItemArrRight.length = 0;
      e.hotZoneItemArr.forEach(item => {
        this.hotZoneItemArrRight.push(item)
      });
    }
    this.save();
  }

  init() {
    const fields = ["hotZoneItemArrLeft", "questionsLeft", "bgItemLeft", "hotZoneItemArrMiddle", "questionsMiddle", "bgItemMiddle", "hotZoneItemArrRight", "questionsRight", "bgItemRight", "bgImages", "title", "wordLeft_text", "wordLeft_audio_url", "wordMiddle_text", "wordMiddle_audio_url", "wordRight_text", "wordRight_audio_url","longAudio_url"]
    if(typeof(this.item.contentObj.hotZoneItemArrLeft) == undefined || typeof(this.item.contentObj.hotZoneItemArrRight) == undefined || typeof(this.item.contentObj.bgItem) == undefined || typeof(this.item.contentObj.bgImages) == undefined || this.item.contentObj.version != defaultData.version) {
      console.log("Init defalue data")
      this.item.contentObj = defaultData
      this.copyFieldsValue(fields, defaultData, this)
    } else {
      console.log("Data loaded")
      this.copyFieldsValue(fields, this.item.contentObj, this)
    }
  }

  addQustion(pos) {
    if(pos == 1) {
      this.questionsLeft.push({
        number: 2,
        combin: [0, 0],
        _combin: [0, 0]
      })
    } else if(pos == 2) {
      this.questionsMiddle.push({
        number: 2,
        combin: [0, 0],
        _combin: [0, 0]
      })
    } else if(pos == 3) {
      this.questionsRight.push({
        number: 2,
        combin: [0, 0],
        _combin: [0, 0]
      })
    }
    
    this.save()
  }

  handleMoveItemUp(pos, index) {
    if(pos==1) {
      if (index != 0) {
        this.questionsLeft[index] = this.questionsLeft.splice(index - 1, 1, this.questionsLeft[index])[0];
      } else {
        this.questionsLeft.push(this.questionsLeft.shift());
      }
    } else if(pos==2) {
      if (index != 0) {
        this.questionsMiddle[index] = this.questionsMiddle.splice(index - 1, 1, this.questionsMiddle[index])[0];
      } else {
        this.questionsMiddle.push(this.questionsMiddle.shift());
      }
    } else if(pos==3) {
      if (index != 0) {
        this.questionsRight[index] = this.questionsRight.splice(index - 1, 1, this.questionsRight[index])[0];
      } else {
        this.questionsRight.push(this.questionsRight.shift());
      }
    }
    
    this.save()
  }

  handleMoveItemDown(pos, index) {
    if(pos == 1) {
      if (index != this.questionsLeft.length - 1) {
        this.questionsLeft[index] = this.questionsLeft.splice(index + 1, 1, this.questionsLeft[index])[0];
      } else {
        this.questionsLeft.unshift(this.questionsLeft.splice(index, 1)[0]);
      }
    } else if(pos == 2) {
      if (index != this.questionsMiddle.length - 1) {
        this.questionsMiddle[index] = this.questionsMiddle.splice(index + 1, 1, this.questionsMiddle[index])[0];
      } else {
        this.questionsMiddle.unshift(this.questionsMiddle.splice(index, 1)[0]);
      }
    } else if(pos == 3) {
      if (index != this.questionsRight.length - 1) {
        this.questionsRight[index] = this.questionsRight.splice(index + 1, 1, this.questionsRight[index])[0];
      } else {
        this.questionsRight.unshift(this.questionsRight.splice(index, 1)[0]);
      }
    }
    this.save()
  }

  handleCombinLength(item) {
    if(Number(item.number)>5){
      return
    }

    if( Number(item.number) > item.combin.length ) {
      let num = Number(item.number) - item.combin.length
      for(var index=0; index<num; index++) {
        item.combin.push(0)
      }
    } else {
      item.combin = item.combin.splice(0, Number(item.number))
    }
    this.save()
  }

  deleteQuestionItem(pos, i) {
    if(pos == 1) {
      this.questionsLeft.splice(i, 1);
    } else if(pos == 2) {
      this.questionsMiddle.splice(i, 1);
    } else if(pos == 3) {
      this.questionsRight.splice(i, 1);
    }
    
    this.save()
  }

  handlePartChange(e, pos, QI, index) {
    if(pos == 1) {
      let a = JSON.parse(JSON.stringify(this.questionsLeft[QI].combin))
      a[index] = Number(e)
      this.questionsLeft[QI].combin = a
    } else if(pos == 2) {
      let a = JSON.parse(JSON.stringify(this.questionsMiddle[QI].combin))
      a[index] = Number(e)
      this.questionsMiddle[QI].combin = a
    } else if(pos == 3) {
      let a = JSON.parse(JSON.stringify(this.questionsRight[QI].combin))
      a[index] = Number(e)
      this.questionsRight[QI].combin = a
    }
    
    this.save()
  }

  onImageUploadSuccess(e, key, item?) {
    if(item) {
      item[key] = e.url; 
    } else {
      this[key] = e.url; 
    }
    this.save(); 
  }
 
  onAudioUploadSuccess(e, key, item?) {
    if(item) {
      item[key] = e.url; 
    } else {
      this[key] = e.url; 
    }
    this.save();
  }

  copyFieldsValue(fields: Array<String>, from: Object, to: Object) {
    fields.forEach((name: any)=>{
      to[name] = from[name]
    })
  }
  
  save() {
    (<any> window).courseware.setData(this.item, null, this.KEY);
    this.refresh();
    console.log("保存", this.item)
  }

  refresh() {
    setTimeout(() => {
      this.appRef.tick();
    }, 1);
  }
}

