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


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

  // 储存数据用
  saveKey = "OP72";
  // 储存对象
  item;
  // 公式键盘
  fboard = null;

  partArr = [
    {
      name: '连线部分'
    },
    {
      name: '书写部分'
    }
  ]

  customTypeGroupArr = [
    {
      name: '连接点',
      rect: true,
      // isShowPos: true,
      isCopy: true,
      isShowPos: true,
      centerDot: true,

      // label: '答案',
    },

    {
      name: '书写区',
      rect: true,
      isShowPos: true,
      isCopy: true,
      anima: true,
    },

    {
      name: '画圈区',
      rect: true,
      isShowPos: true,
      isCopy: true,
      // anima: true,
    },
    
    {
      name: '音频区',
      rect: true,
      audio: true,
      isCopy: true,
    },

    {
      name: '标记区',
      rect: true,
      isShowPos: true,
      isCopy: true,
      anima: true,
    },

    {
      name: '涂色区',
      anima: true,
      // pic: true,
      // isShowPos: true,
      isCopy: true,
    },

    {
      name: '书写图片',
      pic: true,
      // isShowPos: true,
      isCopy: true,
    },

    {
      name: '装饰图片',
      pic: true,
      // isShowPos: true,
      isCopy: true,
    },

    // {
    //   name: '图片',
    //   // audio: true,
    //   pic: true,
    //   // rect: true,
    //   isShowPos: true,
    //   isCopy: true,
    //   // isShowPos: true,

    //   // label: '答案',
    // },
  ];

  customTypeGroupArr2 = [
    {
      name: '连线Point',
      rect: true,
      isCopy: true,
      isShowPos: true,
      centerDot: true,
      checkbox: {
        title: '答案',
        list: [
          {label: '正确', key: 'isRight'},
        ]
      },
    },
    {
      name: '书写Rect-废弃',
      rect: true,
      label: '答案',
      isCopy: true,
      isShowPos: true,
    },

    {
      name: 'part区域',
      rect: true,
    },

    {
      name: '参照物1(标题)-废弃',
      rect: true,
      label: '参照文本',
    },

    {
      name: '参照物2(标题)-废弃',
      rect: true,  
      label: '参照文本',
    },

    {
      name: '参照物2(字母)-废弃',
      rect: true,  
      label: '参照文本',
    },

    {
      name: '书写区(新)',
      rect: true,  
      label: '字母',
      isCopy: true,
    },


    {
      name: '画圈区域',
      rect: true,  
      isCopy: true,
      multRect : true
    },

    {
      name: '标记区域',
      rect: true,  
      isCopy: true,
      dropdown: {
        title: '标记样式',
        list: [
          {label: 'circle', key: '0'},
          {label: 'rect', key: '1'},
          {label: 'cry', key: '2'},
          {label: 'right', key: '3'},
          {label: 'smile', key: '4'},
        ]
      }
    },

    {
      name: '涂色区域',
      rect: true,  
      isCopy: true
      // multRect : true
    },

    {
      name: '数字区',
      rect: true,  
      label: '字母',
      isCopy: true,
    },
  ]

  audioTypeArr = [
    {key: 'begin', info: '开始音频'},
    {key: 'idle', info: '待机音频'},
    {key: 'finish_right', info: '结束音频'},
    // {key: 'finish_wrong', info: '结束有错音频'},
    // {key: 'error_link', info: '连线错误音频'},
    // {key: 'error_write', info: '手写错误音频'},

  ]

  audioTypeArr2 = [
    {key: 'change_step', info: '转阶段'},
    {key: 'idle_2', info: '待机音频2'},
   
  ]

  typeArr = [];
  hasCombineGroup = false;

  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.lineType) {
      this.item.lineType = '1';
    }

    if (!this.item.circleSize) {
      this.item.circleSize = '1';
    }

    if (this.item.helpTime == null) {
      this.item.helpTime = 10;
    }
    this.checkHasCombineGroup();
  }

  getAllGroupType() {

    console.log(' in getAllGroupType')
    const typeObj = {
      '0' : {gIdx: '0', name: '连线'},
      '1' : {gIdx: '1', name: '手写'},
      '2' : {gIdx: '2', name: '画圈'},
      '4' : {gIdx: '4', name: '符号'},
      '5' : {gIdx: '5', name: '涂色'},
      '6' : {gIdx: '6', name: '书写'},
    }

    const typeArr = [];
    const typeTempObj = {}

    const arr = this.item.hotZoneItemArr;

    console.log(' arr: ', arr);

    for (let i=0; i<arr.length; i++) {
      const {gIdx} = arr[i];
      const key = gIdx.toString();
      if (typeObj[key] && !typeTempObj[key]) {
        typeArr.push(typeObj[key]);
        typeTempObj[key] = true;
        console.log('aaaa');
      }
      
    }

    this.item.typeArr = typeArr;
  }


  addItemCombineGroup() {
    if(this.item.itemCombineGroup == undefined || this.item.itemCombineGroup == null) {
      this.item.itemCombineGroup = [];
    }

    this.item.itemCombineGroup.push([])
    this.save();
  }

  deleteItemCombineGroup(index) {
    this.item.itemCombineGroup.splice(index, 1);
    this.save();
  }

  checkHasCombineGroup() {

    console.log(" this.hasCombineGroup : " +  this.hasCombineGroup );
    this.hasCombineGroup = false;

    if (!this.item?.hotZoneItemArr) {
      return ;
    }

    let count = 0;
    this.item.hotZoneItemArr.forEach(item => {
      if (item.gIdx == '4') {
        count++;
      }
      
    });

    if (count >= 1) {
      this.hasCombineGroup = true;
    }

    console.log("2 this.hasCombineGroup : " +  this.hasCombineGroup );

  }

  onItemCombineGroupChange() {
    this.save();
  }

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

    this.item.foregroundArr.push({})
  }


  saveLinkItem(hzItem, linkItemId) {
    hzItem.linkItem = linkItemId;
    this.save();
  }

  savePointItem(hzItem, pointItemId) {
    hzItem.pointItem = pointItemId;
    this.save();
  }

  saveRectItem(hzItem, rectItemId) {
    this.cleanOldRect(hzItem);
    hzItem.rectItem = rectItemId;
    this.save();
  }
  saveRectNew(hzItem, rectItemId) {
    this.cleanOldRect(hzItem);
    hzItem.rectNew = rectItemId;
    this.save();
  }
  saveRectNum(hzItem, rectItemId) {
    this.cleanOldRect(hzItem);
    hzItem.rectNum = rectItemId;
    this.save();
  }
  cleanOldRect(hzItem) {
    hzItem.rectItem = null;
    hzItem.rectNew = null;
    hzItem.rectNum = null;
  }

  saveCircleItem(hzItem, rectItemId) {
    hzItem.circleItem = rectItemId;
    this.save();
  }
  
  saveSignItem(hzItem, signItemId) {
    hzItem.signItem = signItemId;
    this.save();
  }
  
  saveDrawItem(hzItem, itemId) {
    hzItem.drawItem = itemId;
    this.save();
  }


  addWrongAnswer() {

    console.log(' in addWrongAnswer');

    this.item.choiceQuesArr.push({
      optionArr: [
        {id: 'A'},
        {id: 'B'},
        {id: 'C'},
        {id: 'D'},
      ]
    })

    this.save();
  }

  deleteWrongAnswer(choiceQues) {
    removeItemFromArr( this.item.choiceQuesArr, choiceQues );
    this.save();
  }




  onSaveCustomAction(e) {
    console.log('e:', e);
    this.item.customAction = e;
    this.save();
  }


  saveHotZone(group, e) {
    console.log('e: ', e);
    const {bgItem, hotZoneItemArr} = e;

    group.bgItem = bgItem;
    group.hotZoneItemArr = hotZoneItemArr;

    this.item.itemCombineGroup = [];

    this.getAllGroupType();

    this.checkHasCombineGroup();
    
    this.save();


  }

  saveHotZone2(group, e) {
    console.log('e: ', e);
    const {bgItem, hotZoneItemArr} = e;

    group.bgItem2 = bgItem;
    group.hotZoneItemArr2 = hotZoneItemArr;

    this.item.itemCombineGroup = [];
    
    this.save();
  }


  onRadioChange(e) {
    this.item.firstGIdx = e;
    this.save();
  }

  onRadioChangeLine(e) {
    console.log("e:" ,e);
    this.item.lineType = e;
    this.save();
  }

  onRadioChangeCircle(e) {
    console.log("e:" ,e);
    this.item.circleSize = e;
    this.save();
  }
  /**
   * 储存图片数据
   * @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();
  }

  /**
   * 储存数据
   */
  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);
  }

}
