import { Component, EventEmitter, Input, OnDestroy, OnChanges, OnInit, Output, ApplicationRef } from '@angular/core';

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

  picArr = {
    cat: {
      start: "",
      record: "",
      wait: "",
      finish: "",
    },
    tryagain: {
      one: "",
      two: "",
      three: "",
    },
    list: [],
  };
  _item: any;
  KEY = 'hw_006';
  errs = [];

  // @Input()
  set item(item) {
    this._item = item;
    // this.init();
  }
  get item() {
    return this._item;
  }

  @Output()
  update = new EventEmitter();



  constructor(private appRef: ApplicationRef) {

  }


  ngOnInit() {

    this.item = {};
    this.item.contentObj = {};

    const getData = (<any>window).courseware.getData;
    getData((data) => {

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

      if (!this.item.contentObj) {
        this.item.contentObj = {};
      }

      console.log('~data:', data);
      this.init();
      this.refresh();

    }, this.KEY);

    // this.initData();
  }
  ngOnChanges() {

  }

  ngOnDestroy() {
  }


  classItem() {
    function AniAssets() {
      this.ske = {};
      this.tex = {};
      this.png = {};
      this.setData = function (obj) {
        this.ske = obj.ske;
        this.tex = obj.tex;
        this.png = obj.png;
      }
    }

    function Item() {
      this.title = "";
      this.titleRed = [];
      this.titleGroupUseWord = [];//这里需要处理，动态设定，1.渲染每个组可以有的内容。 [1, 0, 0, 0, 0, 0]
      this.titleGroup = [];
      this.titleObj = {};
      this.bgImg = "";
      this.wordAudio = "";
      this.imgAni = new AniAssets();
    }

    return new Item();
  }
  onChoseRed(arr, i, val, item) {
    console.log(arr);
    arr[i] = val;
    this.save();
  }


  init() {
    //在卡片组之上需要增加 两个组 0根->picArr  1题组->testlet  2页面->page  3卡片对->itemData
    if (this.item.contentObj.picArr) {
      this.picArr = this.item.contentObj.picArr;
      this.check();
    } else {
      this.picArr = this.getDefaultPicArr();
      this.item.contentObj.picArr = this.picArr;
    }
    console.log('item:', this.item);
  }

  cardItemData() {
    return this.classItem()
  }

  getDefaultPicArr() {
    let cat = {
      start: "",
      record: "",
      wait: "",
      finish: "",
    }
    let tryagain = {
      one: "",
      two: "",
      three: "",
    }
    let list = [this.classItem()]
    return { cat: cat, tryagain: tryagain, list: list };
  }

  initData() {


  }

  onDragonBoneSave(e, item) {
    console.log(e);
    this.save();
  }

  onImageUploadSuccessByItem(e, item) {
    item.bgImg = e.url;
    this.save();
  }

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

  //添加一对
  addItem() {
    //最多4个 
    let item = this.cardItemData();
    this.picArr.list.push(item)
    this.saveItem();
  }
  deleteItem(i) {
    this.picArr.list.splice(i, 1);
    this.save();
  }

  addGroup(i) {
    let item = this.picArr.list[i];
    item.titleGroup.push({ index: [], audio: "", })
    this.save();
  }
  deleteGroup(i, n) {
    let item = this.picArr.list[i];
    item.titleGroup.splice(n, 1);
    let delArr = item.titleGroupUseWord[n];
    item.titleGroupUseWord.forEach((arr, index) => {
      if (index == n) return;
      for (let m = 0; m < delArr.length; m++) {
        if (delArr[m] == 0) arr[m] = 0;
      }
    })
    item.titleGroupUseWord.splice(n, 1);
    let lastArr = [];
    item.titleGroupUseWord.forEach((arr, index) => {
      for (let m = 0; m < arr.length; m++) {
        if (arr[m] == 1) {
          lastArr[m] = 1;
        } else {
          if (lastArr[m] != 1) {
            lastArr[m] = 0;
          }
        }
      }
    })
    item.titleGroupUseWord.push(lastArr);

    if (item.titleGroup.length == 0) item.titleGroupUseWord.length = 0;

    this.save();
  }
  onChoseGroup(arr, i, val, item, n) {
    console.log(arr);
    arr[i] = val;
    for (let index = 0; index < item.title.split("").length; index++) {
      if (n == index) {
        if (!item.titleGroupUseWord[index]) item.titleGroupUseWord[index] = [];
        item.titleGroupUseWord[index][i] = 0;
        console.log(item.titleGroupUseWord[index])
        continue;
      }
      if (!item.titleGroupUseWord[index]) item.titleGroupUseWord[index] = [];
      item.titleGroupUseWord[index][i] = val;
    }
    this.save();
  }

  // refreshUserWord(item) {
  //   let tg = item.titleGroup;
  //   tg.forEach((t, n) => {
  //     let inx = t.index;
  //     if (inx.length < item.title.split("").length) inx.length = item.title.split("").length;
  //     for (let i = 0; i < inx.length; i++) {
  //       let u = inx[i];
  //       this.updateUserWord(u, i, item)
  //     }
  //   })
  // }
  // updateUserWord(num, pos, item) {
  //   let uw = item.titleGroupUseWord;
  //   for (let i = 0; i < uw.length; i++) {
  //     let u = uw[i];
  //     if (!u) u = [];
  //     for (let j = 0; j < u.length; j++) {
  //       if (j == pos) {
  //         u[j] = num || 0;
  //         break;
  //       }
  //     }
  //   }
  // }



  //选择圆圈
  radioClick(it, radioValue) {
    it.radioValue = radioValue;
    this.saveItem();
  }


  saveItem() {

    console.log(' in saveItem');
    // this.update.emit(this.item);
    this.save();
  }

  check() {
    if (!this.picArr) return;
    this.errs.length = 0;
    console.log("this.errs");
    console.log(this.errs);
    console.log("-------------------------");
  }


  save() {
    //触发一次检测
    this.check();
    //在这里进行数据拼接
    this.item.contentObj.picArr.list = this.item.contentObj.picArr.list.map(item => {
      let groupIds = [];
      item.orderAudio = [];
      item.titleGroup.forEach((tg, m) => {
        item.orderAudio[m] = tg.audio;
        tg.index.forEach((v, i) => {
          if (v == 1) groupIds[m] = i;
        })
      });

      item.titleObj = item.title.split("").map((s, idx) => {
        //判定idx在第几个梯队里面
        let count = -1;
        groupIds.forEach((v, i) => {
          if (idx <= v && count == -1) count = i;
        })
        return {
          card: s,
          color: item.titleRed[idx] == 1 ? 0 : 1,
          order: count, //待处理
        }
      })
      return item;
    });

    // let m = {
    //   contentObj: {
    //     picArr: {
    //       list: []
    //     }
    //   }



    (<any>window).courseware.setData(this.item, null, this.KEY);
    console.log('this.item = ' + JSON.stringify(this.item));
    this.refresh();
  }

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

