import { Component, EventEmitter, Input, OnDestroy, OnChanges, OnInit, Output, ApplicationRef, ChangeDetectorRef } from '@angular/core';
import { NzMessageService, UploadXHRArgs, UploadFile } from 'ng-zorro-antd';
// import { defauleFormData } from '../../assets/default/formData/defaultData_LST01'
const defauleFormData = require('../../assets/default/formData/LST01/default.json')

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


export class FormComponent implements OnInit, OnChanges, OnDestroy {

  _item: any;
  KEY = 'DataKey_Cocos_Test';
  checkOptionsOne = []
  Text = "Text"
  Image = "Image"
  uploadUrl
  uploadData
  fileList
  copyIndex
  pasteString

  set item(item) {
    this._item = item;
  }
  get item() {
    return this._item;
  }
  contentObj = {
    "version": "1.1",
    haveCover: false,
    bgm_url: "",
    dataArray: []
  }

  @Output()
  update = new EventEmitter();
  constructor(private appRef: ApplicationRef, private changeDetectorRef: ChangeDetectorRef) {
    this.uploadUrl = (<any>window).courseware.uploadUrl();
    this.uploadData = (<any>window).courseware.uploadData();
    window['air'].getUploadCallback = (url, data) => {
      this.uploadUrl = url;
      this.uploadData = data;
    };
  }

  handleQuestionTypeChange(key) {
    if (key == 'Spine') {
      this.fileList = [
        {
          uid: '-1',
          name: this.item['ske_json'],
          status: 'done',
          url: this.item['ske_json']
        }
      ]
    } else if (key == 'Image') {

    }
    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 == defauleFormData.version) {
      console.log("读取数据", this.item.contentObj)
      this.contentObj = this.item.contentObj;
    } else {
      this.contentObj = defauleFormData;
      console.log("使用演示数据", this.contentObj)
      this.item.contentObj = this.contentObj;
    }
  }

  cardItemData() {
    return { audio_url: "", type: "text", text: "", 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({ type: 'Image', text: "", image_url: "" })
    this.saveItem();
    setTimeout(() => {
      window.scrollTo(0, document.body.scrollHeight);
    }, 1)
  }

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


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

  onBgmUploadSuccess(e) {
    this.contentObj.bgm_url = e.url;
    this.save();
  }

  saveItem() {
    this.save();
  }

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

  handleChange(info: { type: string, file: UploadFile, event: any }, item, key) {
    console.log('info:', info);
    switch (info.type) {
      case 'success':
        this.uploadSuccess(info.file, item, key);
        break;
    }
  }

  uploadSuccess(file, item, key) {
    console.log(item);
    item[key] = file.response.url;
    item[key + '_name'] = file.name;
    this.save();
  }
  onCopyData(index) {
    this.contentObj.dataArray.push(JSON.parse(JSON.stringify(this.contentObj.dataArray[index])));
    this.save();
    setTimeout(() => {
      window.scrollTo(0, document.body.scrollHeight);
    }, 1)
  }

  onCoverSwitchChange() {
    console.log(this.contentObj.haveCover)
    this.save();
  }
}

