import {Component, EventEmitter, Input, OnDestroy, OnChanges, OnInit, Output, ApplicationRef, ChangeDetectorRef} from '@angular/core';
// import { defauleFormData } from '../../assets/default/formData/defaultData_LST01'
const defauleFormData = {
  "version": "1.0",
  key: "DataKey_Sbox_FT_08",
  bgMusic: "",
  titleText: "",
  dataArray: []
}

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


export class FormComponent implements OnInit, OnChanges, OnDestroy {

  _item: any;
  KEY = 'DataKey_Sbox_FT_08';
  checkOptionsOne = []
  Text = "Text"
  Image = "Image"



  set item(item) {
    this._item = item;
  }
  get item() {
    return this._item;
  }
  contentObj =  {
    "version": "1.0",
    key: "DataKey_Sbox_FT_08",
    bgMusic: "",
    titleText: "",
    questionAudio_url: "",
    birdDragonBones_1: {},
    birdDragonBones_2: {},
    birdDragonBones_audio: {},
    dataArray: []
  }

  @Output()
  update = new EventEmitter();
  constructor(private appRef: ApplicationRef, private changeDetectorRef: ChangeDetectorRef) {

  }

  handleQuestionTypeChange(){
    // if(this.contentObj.question.type != 'LongAudio'){
    //   this.contentObj.answerType='Text'
    // }
    this.saveItem()
    this.changeDetectorRef.markForCheck();
    this.changeDetectorRef.detectChanges();
  }

  handleAnswerTypeChange(){
    // console.log("Change")
    // let len = this.contentObj.dataArray.length
    // this.contentObj.dataArray = Array(len).fill("")
    this.saveItem()
  }

  handleTextChange(e, index){
    // console.log(e.target.value, index)
    this.contentObj.dataArray[index].text = e.target.value
    this.saveItem()
    this.refresh();
  }

  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();
      setTimeout(() => {
        this.changeDetectorRef.markForCheck();
        this.changeDetectorRef.detectChanges();
      }, 100);
      // this.save()
    }, this.KEY);
  }

  ngOnChanges() {}
  ngOnDestroy() {}

  init() {
    if (Object.keys(this.item.contentObj).length != 0 && this.item.contentObj.version && this.item.contentObj.version==this.contentObj.version) {
      console.log("读取数据", this.item.contentObj)
      this.contentObj = this.item.contentObj;
    } else {
      console.log("使用演示数据", this.contentObj)
      this.item.contentObj = this.contentObj;
    }
  }

  cardItemData(){
    return {audio_url:"", image_url:""}
  }

  cardChoiceData(){
    return { isText: true, text: "", image_url: "" }
  }

  initData() {

  }

  handleMoveItemUp(items, index){
    if(index!=0){
      items[index] = items.splice(index-1, 1, items[index])[0];
    }else{
      items.push(items.shift());
    }
    this.save()
  }

  handleMoveItemDown(items, index){
    if(index!=items.length-1){
      items[index] = items.splice(index+1, 1, items[index])[0];
    }else{
      items.unshift( items.splice(index,1)[0]);
    }
    this.save()
  }

  deleteItem(item, index){
    item.splice(index,1)
    this.save()
  }

  addItem(item?, type?) { 
    item.push({text: "", image_url: "", dragonBones: {}})
    this.saveItem();
  }

  onImageUploadSuccessByItem(e, item, key) {
    item[key] = e.url
    this,this.refresh()
    this.save(); 
  }

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

  updateDragonBones(e, key, item) {
    item[key] = e;
    this.saveItem()
  }

  saveItem() {
    this.save();
  }

  save() {
    (<any> window).courseware.setData(this.item, null, this.KEY);
    this.refresh();
    console.log(JSON.stringify(this.item))
    console.log("保存", this.item)
  }

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

  updateCheckbox(){
    let check = []

    this.item.contentObj.textDown.forEach((item, index) => {
      check.push({label:index+1, value:index, checked:false})
    });

    let length = check.length
    this.item.contentObj.textUp.forEach((item, index) => {
      let _check = JSON.parse(JSON.stringify(check))
      item.lineTo.forEach(option=> {
        if(option<length){
          _check[Number(option)].checked = true
        }
      });
      item.checkOptions = _check
    });
  }
}

