
import { Component, EventEmitter, Input, OnDestroy, OnChanges, OnInit, Output, ApplicationRef, ChangeDetectorRef } from '@angular/core';
import { JsonPipe } from '@angular/common';
import { NzMessageService } from 'ng-zorro-antd/message';


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

  // 储存数据用
  saveKey = "form_upload_folder";

  baseData;

  // 储存对象
  item;
  //临时储存对象
  tempItem;


  templateTypeArr = [
    { name: "选择题", value: "select" },
    { name: "拖拽题", value: "drag" },
    { name: "语音评测", value: "record" },
    // {name:"连线题", value: "line"},
    // {name:"翻翻卡", value: "flip"},
  ]

  isPreviewTemplate = false;




  customTypeGroupArr = [
    {
      name: '输入型文本',
      rect: true,
      isShowPos: true,
      labelArr: [
        { type: "inputText", key: "title", title: "标题" },
        { key: "key", title: "key" },
        { key: "fontName", title: "字体" },
        { key: "fontSize", title: "大小" },
        { key: "fontColor", title: "颜色" },
      ],
      checkbox: {
        title: '',
        list: [
          { label: '自动换行', value: 'warp' }
        ]
      }
    },


    {
      name: '固定型文本',
      text: true,
      audio: true,
      isShowPos: true,
      labelArr: [
        { key: "fontName", title: "字体" },
        { key: "fontSize", title: "大小" },
        { key: "fontColor", title: "颜色" },
      ]
    },


    {
      name: '输入型图片',
      rect: true,
      isShowPos: true,
      labelArr: [
        { type: "inputPic", key: "title", title: "标题" },
        { key: "key", title: "key", value: "" },
      ]
    },


    {
      name: '固定型图片',
      pic: true,
      audio: true,
      anchorGroup: true,
      isShowPos: true,
    },


    {
      name: '输入型动画',
      rect: true,
      isShowPos: true,
      labelArr: [
        { key: "title", title: "标题" },
      ]
    },


    {
      name: '固定型动画',
      rect: true,
      anima: true,
      audio: true,
      isShowPos: true,
    },


    {
      name: '输入型音频',
      rect: true,
      isShowPos: true,
      labelArr: [
        { type: "inputAudio", key: "title", title: "标题" },
        { key: "key", title: "key", value: "" },
      ]
    },


    {
      name: '固定型音频',
      rect: true,
      audio: true,
      pic: true,
      anim: true,
      isShowPos: true,
    },


    {
      name: '数据型文本',
      data: true,
      labelArr: [
        { type: "inputText", key: "title", title: "标题" },
        { key: "key", title: "key" },
      ]
    },


    {
      name: '数据型图片',
      // data: true,
      labelArr: [
        { type: "inputPic", key: "title", title: "标题", value: "" },
        { key: "key", title: "key", value: "" },
      ]
    },


    {
      name: '翻页按钮组',
      rect: true,
      audio: true,
      // radio: {
      //   title: "按钮",
      //   list: [
      //     {label: '上一页', key: 'prev'},
      //     {label: '下一页', key: 'next'},
      //     {label: '翻页文本', key: 'text'},
      //   ]
      // },
      isShowPos: true,
    },


    {
      name: '录音按钮组',
      rect: true,
      audio: true,
      isShowPos: true,
    },


    {
      name: '文字选项组',
      rect: true,
      picArr: [
        { title: '默认图' },
        { title: '正确图' },
        { title: '错误图' },
      ],
      labelArr: [
        { type: "inputText", key: "title", title: "标题" },
        { key: "key", title: "key" },

        { key: "fontSize", title: "字体大小" },
        { key: "fontName1", title: "普通字体" },
        { key: "fontColor1", title: "普通颜色" },
        { key: "fontName2", title: "正确字体" },
        { key: "fontColor2", title: "正确颜色" },
        { key: "fontName3", title: "错误字体" },
        { key: "fontColor3", title: "错误颜色" },
      ],
      checkbox: {
        title: '',
        list: [
          { label: '适配矩形', key: 'isScale' },
        ]
      },
      isOption: true,
      isShowPos: true,
      isCopy: true,
    },


    {
      name: '图片选项组',
      rect: true,
      picArr: [
        { title: '输入参考图' },
        { title: '默认背景图' },
        { title: '正确背景图' },
        { title: '错误背景图' },
      ],
      labelArr: [
        { type: "inputPic", key: "title", title: "标题" },
        { key: "key", title: "key" },
      ],
      checkbox: {
        title: '',
        list: [
          { label: '遮罩', key: 'isMask' },
          { label: '适配矩形', key: 'isScale' },
        ]
      },
      isOption: true,
      isShowPos: true,
      isCopy: true,
    },


    {
      name: '音频型动画',
      rect: true,
      anima: true,
      labelArr: [
        { type: "inputAudio", key: "title", title: "标题" },
        { key: "key", title: "key" },
      ],
      isShowPos: true,
      isCopy: true,
    },


    {
      name: '选项效果组',
      picArr: [
        { title: '正确效果' },
        { title: '错误效果' },
      ],
      audioArr: [
        { title: '正确音效' },
        { title: '错误音效' },
      ],
      anchorGroup: true,
      isCopy: true,
    },


    {
      name: '数组排列区',
      rect: true,
      checkbox: {
        title: '',
        list: [
          { label: '横向排列', key: 'hor' },
        ]
      },
      // select: {
      //   title: '类型',
      //   list:[
      //     {label: '拖拽开始区', value:'dragStart'},
      //     {label: '拖拽结束区', value:'dragEnd'},
      //   ]
      // },
      labelArr: [
        { key: "id", title: "id" },
        { key: "distanceX", title: "横向间距" },
        { key: "distanceY", title: "纵向间距" },
      ],
      isShowPos: true,
      isShowSize: true,
      isCopy: true,
    },

    {
      name: '文字排列物',
      rect: true,
      picArr: [
        { title: '默认图' },
        { title: '正确图' },
        { title: '错误图' },
      ],
      labelArr: [
        { type: "listInputText", key: "title", title: "标题" },
        { key: "key", title: "key" },
        { key: "id", title: "id" },

        { key: "fontSize", title: "字体大小" },
        { key: "fontName1", title: "普通字体" },
        { key: "fontColor1", title: "普通颜色" },
        { key: "fontName2", title: "正确字体" },
        { key: "fontColor2", title: "正确颜色" },
        { key: "fontName3", title: "错误字体" },
        { key: "fontColor3", title: "错误颜色" },
      ],

      radio: {
        title: "文字位置",
        list: [
          { label: '开头', key: 'start' },
          { label: '中间', key: 'middle' },
          { label: '结尾', key: 'end' },
        ]
      },


      // checkbox: {
      //   title: '',
      //   list: [
      //     {label: '结束块', key:'isEndRect'},
      //   ]
      // },

      isShowPos: true,
      isCopy: true,
    },

    {
      name: '图片排列物',
      rect: true,
      picArr: [
        { title: '输入参考图' },
        { title: '默认背景图' },
        { title: '正确背景图' },
        { title: '错误背景图' },
      ],
      labelArr: [
        { type: "listInputPic", key: "title", title: "标题" },
        { key: "key", title: "key" },
        { key: "id", title: "id" },
      ],
      checkbox: {
        title: '',
        list: [
          { label: '遮罩', key: 'isMask' },
          // {label: '结束块', key:'isEndRect'},
        ]
      },
      isShowPos: true,
      isCopy: true,
    },

    {
      name: '拖拽文字组',
      rect: true,
      picArr: [
        { title: '默认图' },
        { title: '正确图' },
        { title: '错误图' },
      ],
      labelArr: [
        { type: "listInputText", key: "title", title: "标题" },
        { key: "key", title: "key" },

        { key: "fontSize", title: "字体大小" },
        { key: "fontName1", title: "普通字体" },
        { key: "fontColor1", title: "普通颜色" },
        { key: "fontName2", title: "正确字体" },
        { key: "fontColor2", title: "正确颜色" },
        { key: "fontName3", title: "错误字体" },
        { key: "fontColor3", title: "错误颜色" },
      ],
      checkbox: {
        title: '',
        list: [
          { label: '结束块', key: 'isEndRect' },
        ]
      },
      isShowPos: true,
      isCopy: true,
    },


    {
      name: '拖拽图片组',
      rect: true,
      picArr: [
        { title: '输入参考图' },
        { title: '默认背景图' },
        { title: '正确背景图' },
        { title: '错误背景图' },
      ],
      labelArr: [
        { type: "listInputPic", key: "title", title: "标题" },
        { key: "key", title: "key" },
      ],
      checkbox: {
        title: '',
        list: [
          { label: '遮罩', key: 'isMask' },
          { label: '结束块', key: 'isEndRect' },
        ]
      },
      isShowPos: true,
      isCopy: true,
    },
  ];




  curSelectItem;
  isShowKK = false;
  curSelectKK;

  customTypeGroupArr2 = [
    {
      name: '星星区域',
      rect: true,
    },
    {
      name: '选择区域',
      rect: true,
    },
  ]

  stepArr = [
    { label: '视频时间', value: 'ques' },
  ];

  videoSizeArr = [
    { key: '1920_1080', value: '1920 x 1080' },
    { key: '1280_720', value: '1280 x 720' },
    { key: '940_600', value: '940 x 600' },
  ]

  audioTypeArr = [
    { key: 'begin', info: '第一遍开始音频' },
    { key: 'begin_2', info: '第二遍开始音频' },
    { key: 'finish', info: '第二遍结束音频' },
  ]


  posArr = [
    'n.',
    'adj.',
    'v.',
    'pron.',
    'adv.',
    'prep.',
    'conj.',
    'interj.',
    'art.',
    'num.',
    'verb phrase',
    'noun phrase',
    'prep phrase',
    'ordinal number',
  ];





  constructor(private appRef: ApplicationRef, private changeDetectorRef: ChangeDetectorRef,
    private message: NzMessageService) {

  }


  ngOnInit() {

    this.item = {};

    // 获取存储的数据
    (<any>window).courseware.getData((data) => {


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

      this.initItem();


      console.log("this.item: ", JSON.stringify(this.item));

      this.init();
      this.changeDetectorRef.markForCheck();
      this.changeDetectorRef.detectChanges();
      this.refresh();

    }, this.saveKey);
  }

  initItem() {

  }

  init() {

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

    // if (!this.item.group_arr) {
    //   this.item.group_arr = [];
    // }
    this.refreshQuesIndex();
  }




  refreshQuesIndex() {
    this.item.quesArr.forEach((element, index) => {
      element.quesIndex = index + 1;
    });
  }

  sortQues(baseId, targetId) {
    console.log(' baseIndex : '  + baseId );
    console.log(' targetIndex : ' + targetId );
    this.moveElement(this.item.quesArr, baseId - 1, targetId - 1);
    // this.refreshQuesIndex();
  }

  moveElement(arr, fromIndex, toIndex) {
    // 检查索引是否有效
    if (fromIndex < 0 || fromIndex >= arr.length || toIndex < 0 || toIndex >= arr.length) {
      throw new Error('Invalid index');
    }
  
    // 获取要移动的元素
    const element = arr[fromIndex];
  
    // 移除元素
    arr.splice(fromIndex, 1);
  
    // 插入元素到新位置
    arr.splice(toIndex, 0, element);

    this.save();
  
    return arr;
  }





  saveFormGroup(e) {
    this.item.group_arr = e;
    this.save();
  }

  wordDataArr = [];
  async uploadDirectorFinish(e) {

    const { fileList, textFileList } = e;
    console.log("in uploadDirectorFinish e: ", e);
    console.log("in uploadDirectorFinish fileList: ", fileList);
    console.log("in uploadDirectorFinish textFileList: ", textFileList);


    const textArr = this.getTextArr(fileList, '1');
    const imageArr = this.getImageArr(fileList, '1');
    const audioArr = this.getAudioArr(fileList, '1');

    const newTextArr = [];
    textArr.forEach((element, index) => {
      const file = textFileList.find(it => it.name == element.name);
      if (file) {
        newTextArr.push(file);
      }
    });

    this.wordDataArr = [];

    imageArr.forEach((element, index) => {
      this.wordDataArr.push({
        imageFile: element,
        textFile: newTextArr[index],
        audioFile: audioArr[index],
      })
    });

    // console.log('wordDataArr: ', this.wordDataArr);


    // if (this.wordDataArr.length < 20) {
    //   console.log("单词数量不足20个");
    //   return;
    // }

    this.item.quesArr = [];
    // 前20页
    for (let i = 0; i < this.wordDataArr.length; i++) {
      this.addOnePageBtnClick(false);
      const ques = this.item.quesArr[i];
      ques.type = 'dictionary';
      ques.title = 'Read the word.';

      const textFile = this.wordDataArr[i].textFile;
      const audioFile = this.wordDataArr[i].audioFile;
      const imageFile = this.wordDataArr[i].imageFile;

      ques.pic_url = imageFile?.response?.url || '';
      ques.audio_url = audioFile?.response?.url || '';

      const reader = new FileReader();
      reader.onload = e => {
        const fileContent = e.target.result;

        // console.log('File content:', fileContent.toString().split('\n')[1]);
        const targetRow = fileContent.toString().split('\n')[1].split(',');

        const word = targetRow[0].replace(/"/g, '');
        const ipa = targetRow[1].replace(/"/g, '');
        const zh_cn = targetRow[3].replace(/"/g, '');
        const pos = targetRow[4].replace(/"/g, '');


        ques.word = word;
        ques.ipa = ipa;
        ques.zh_cn = zh_cn;
        ques.pos = pos;

        console.log("word: ", word);
        console.log("ipa: ", ipa);
        console.log("zh_cn: ", zh_cn);
        console.log("pos: ", pos);

        console.log("targetRow: ", targetRow);
        this.refresh();

      };
      reader.readAsText(textFile);

    }

    let isEn = false;
    // 拖拽 + 选择
    for (let i = 0; i < this.wordDataArr.length; i++) {

      // 拖拽
      this.addOnePageBtnClick(false);
      const ques = this.item.quesArr[this.item.quesArr.length - 1];
      ques.type = 'drag';
      ques.title = 'Unscramble the word.';

      const textFile = this.wordDataArr[i].textFile;
      const audioFile = this.wordDataArr[i].audioFile;
      const imageFile = this.wordDataArr[i].imageFile;

      ques.pic_url = imageFile?.response?.url || '';
      ques.audio_url = audioFile?.response?.url || '';


      // 选择
      this.addOnePageBtnClick(false);
      const ques2 = this.item.quesArr[this.item.quesArr.length - 1];

      ques2.type = 'select';

      if (isEn) {
        ques2.audio_url = audioFile?.response?.url || '';
      }
      ques2.title = isEn ? 'Read the word. Choose the correct definition.' : 'Read the definition. Choose the correct word.';
      ques2.selectType = isEn ? 'en' : 'cn';
      
      
      isEn = !isEn;

      const reader = new FileReader();
      reader.onload = e => {
        const fileContent = e.target.result;

        // console.log('File content:', fileContent.toString().split('\n')[1]);
        const targetRow = fileContent.toString().split('\n')[1].split(',');

        const word = targetRow[0].replace(/"/g, '');
        const ipa = targetRow[1].replace(/"/g, '');
        const zh_cn = targetRow[3].replace(/"/g, '');
        const pos = targetRow[4].replace(/"/g, '');



        ques.word = word.split('').join(' ');

        ques.word = ques.word.replace(/   /g, '  ');


        ques2.word = word;
        // ques2.pos = pos;
        ques2.zh_cn = zh_cn;


        if (ques2.selectType == 'en') {
     
          ques2.pos = pos;
          // ques2.zh_cn = zh_cn;
        } else {
          // ques2.zh_cn = zh_cn;

        }


        // ques.ipa = ipa;
        // ques.zh_cn = zh_cn;
        // ques.pos = pos;

        // console.log("word: " , word);
        // console.log("ipa: " , ipa);
        // console.log("zh_cn: " , zh_cn);
        // console.log("pos: " , pos);

        // console.log("targetRow: " , targetRow);
        this.refresh();




      };
      reader.readAsText(textFile);


      this.setSelectOptionArr(ques2, i);

    }




    //  听写

    this.addOnePageBtnClick(false);
    var curQues = this.item.quesArr[this.item.quesArr.length - 1];

    curQues.type = 'dictation';
    curQues.title = 'Listen. Write down the word on your note book.';

    const optionArr = [];



    for (let i = 0; i < this.wordDataArr.length; i++) {

      const textFile = this.wordDataArr[i].textFile;
      const audioFile = this.wordDataArr[i].audioFile;
      const imageFile = this.wordDataArr[i].imageFile;

      const option = {};

      option['pic_url'] = imageFile?.response?.url || '';
      option['audio_url'] = audioFile?.response?.url || '';

      const reader = new FileReader();
      reader.onload = e => {
        const fileContent = e.target.result;
        const targetRow = fileContent.toString().split('\n')[1].split(',');

        const word = targetRow[0].replace(/"/g, '');
        // const ipa = targetRow[1].replace(/"/g, '');
        // const zh_cn = targetRow[3].replace(/"/g, '');
        // const pos = targetRow[4].replace(/"/g, '');

        option['text'] = word;

      };
      reader.readAsText(textFile);

      optionArr.push(option);
    }



    curQues.optionArr = optionArr;


    this.refresh();



    // // const group_arr = this.item.group_arr;

    // if (!this.item.group_arr || this.item.group_arr.length == 0) {
    //   this.addGroupBtnClick();
    // } 

    // //模板自定义读取
    // await this.setGroupByTextArr(textArr, this.item.group_arr);
    // await this.setGroupByImageArr(imageArr, this.item.group_arr);
    // await this.setGroupByAudioArr(audioArr, this.item.group_arr);

    // console.log('textArr: ', textArr);
    // console.log('imageArr: ', imageArr);
    // console.log('audioArr: ', audioArr);

    // this.save();

  }

  setSelectOptionArr(quesData, index) {
    const copyData = this.wordDataArr.concat([]);

    const optionArr = [];
    const setOneOption = (_rightData = null) => {

      let option;


      if (_rightData) {
        option = _rightData;
      } else {
        const randomIndex = Math.floor(Math.random() * copyData.length);
        option = copyData[randomIndex];
        copyData.splice(randomIndex, 1);
      }


      const textFile = option.textFile;
      const audioFile = option.audioFile;
      const imageFile = option.imageFile;

      const reader = new FileReader();
      reader.onload = e => {
        const fileContent = e.target.result;

        const targetRow = fileContent.toString().split('\n')[1].split(',');

        const word = targetRow[0].replace(/"/g, '');
        const ipa = targetRow[1].replace(/"/g, '');
        const zh_cn = targetRow[3].replace(/"/g, '');
        const pos = targetRow[4].replace(/"/g, '');

        const oneOption = {
          text: quesData.selectType == 'en' ? zh_cn : word,
          answer: _rightData ? 'isRight' : 'isWrong'
        };

        if (quesData.selectType != 'en') {
          oneOption['audio_url'] = audioFile?.response?.url || '';
        }

        optionArr.push(
          oneOption
        )


        for (let i = optionArr.length - 1; i > 0; i--) {
          const j = Math.floor(Math.random() * (i + 1));
          [optionArr[i], optionArr[j]] = [optionArr[j], optionArr[i]]; // 使用ES6的解构赋值进行交换
        }

        this.refresh();

      };
      reader.readAsText(textFile);

    }



    const rightData = copyData[index];

    copyData.splice(index, 1);

    setOneOption();
    setOneOption();
    setOneOption();
    setOneOption(rightData);

    quesData.optionArr = optionArr;





  }


  addGroupBtnClick() {
    this.item.group_arr.push({
      text_arr: [],
      anim_arr: [],
      image_arr: [],
      audio_arr: [],
      video_arr: [],
      sub_group_arr: [],
    })

    this.save();
  }

  getTextArr(fileList, part = null) {
    const targetArr = fileList.filter(it => {
      const { originFileObj } = it;
      const index = originFileObj.type.indexOf("text");
      return (index != -1);
    })
    return this.filterPartByName(targetArr, part);
  }

  getAudioArr(fileList, part = null) {
    const targetArr = fileList.filter(it => {
      const { originFileObj } = it;
      const index = originFileObj.type.indexOf("audio");
      return (index != -1);
    })
    return this.filterPartByName(targetArr, part);
  }

  getImageArr(fileList, part = null) {
    const targetArr = fileList.filter(it => {
      const { originFileObj } = it;
      const index = originFileObj.type.indexOf("image");
      return (index != -1);
    })
    return this.filterPartByName(targetArr, part);
  }

  getVideoArr(fileList, part = null) {
    const targetArr = fileList.filter(it => {
      const { originFileObj } = it;
      const index = originFileObj.type.indexOf("video");
      return (index != -1);
    })
    return this.filterPartByName(targetArr, part);
  }

  filterPartByName(subFileList, part = null) {
    if (part == null) {
      return subFileList;
    }

    return subFileList;

    const newArr = subFileList.filter(it => {
      const { originFileObj } = it;
      const nameArr = originFileObj.name.split("_");
      const partId = nameArr[0];
      it.nameId = nameArr[1];
      return (partId == part);
    })
    return this.sortByNameId(newArr);
  }

  sortByNameId(arr) {
    arr.sort(function (a, b) {
      return a.nameId - b.nameId;
    });
    return arr;
  }

  async setGroupByTextArr(subFileList, group_arr) {

    const text_arr = [];
    const len = 3;
    for (let i = 0; i < len; i++) {
      if (!subFileList[i]) {
        break;
      }
      const text = await this.getFileTextValue(subFileList[i]);
      text_arr[i] = { value: text };
    }
    group_arr[0].text_arr = text_arr;
  }

  setGroupByAudioArr(subFileList, group_arr) {
    const audio_arr = [];
    const len = 3;
    for (let i = 0; i < len; i++) {
      if (!subFileList[i]) {
        break;
      }
      const url = this.getFileAudioValue(subFileList[i]);
      audio_arr[i] = { value: url };
    }
    group_arr[0].audio_arr = audio_arr;
  }

  setGroupByImageArr(subFileList, group_arr) {
    const image_arr = [];
    const len = 1;
    for (let i = 0; i < len; i++) {
      if (!subFileList[i]) {
        break;
      }
      const url = this.getFileImageValue(subFileList[i]);
      image_arr[i] = { value: url };
    }
    group_arr[0].image_arr = image_arr;
  }

  setGroupByVideoArr(subFileList, group_arr) {

  }

  async getFileTextValue(oneData) {

    const file = oneData.originFileObj;

    return new Promise((resolve, rejects) => {
      if (file.type.startsWith('text')) {
        const reader = new FileReader();
        reader.onload = (e) => {
          const fileContent = e.target.result;
          // console.log(fileContent);
          resolve(fileContent);
        };
        reader.readAsText(file);
      } else {
        resolve("");
      }

    })
  }

  getFileImageValue(oneData) {
    return oneData?.response?.url || '';
  }

  getFileAudioValue(oneData) {
    return oneData?.response?.url || '';
  }









  templateTypeChange(e) {
    console.log("in templateTypeChange e: ", e);
    this.item.templateType = e;
    this.save();
  }






  createShell() {
    this.item.wordList.push({
      word: '',
      audio: '',
      backWord: '',
      backWordAudio: '',
    });
    this.save();
  }

  removeShell(idx) {
    this.item.wordList.splice(idx, 1);
    this.save();
  }


  ngOnChanges() {
  }

  ngOnDestroy() {
  }


  itemSplitTypeChange(e, it) {
    it.splitType = e;
    this.save();
  }
  videoTypeChange(e) {
    console.log('e: ', e);
    this.item.videoType = e;
    this.save();
  }

  addBtnClick() {
    this.item.quesArr.push({
      itemType: 'jump'
    });
    this.save();
  }



  deleteBtnClick(i) {
    this.item.quesArr.splice(i, 1);
    this.save();
  }



  radioChange(e, item, key) {
    console.log('e: ', e);
    item[key] = e;
    this.save();
  }

  onVideoUploadSuccess(e, item, key) {
    console.log('e: ', e);
    item[key] = e.url;
    this.save();
  }

  videoSeeked(e) {

  }

  videoError(e) {

  }

  videoLoaded(e, it) {

  }


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

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

    this.save();
  }

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

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

    this.save();
  }


  getLRC(evt) {
    this.item.lrcData = evt;
    this.save();

  }

  onVideoUploaded(res, key, item) {
    if (!item) {
      item = this.item;
    }
    console.log('onVideoUploaded: ', res);

    item[key] = res.url;
    this.save();
  }

  isTurnPageChange(e) {
    console.log("e: ", e);
  }


  onItemImgUploadSuccess(e, item, key = 'pic_url') {
    item[key] = e.url;
    // console.log('item: ', item);
    this.save();
  }

  onItemAudioUploadSuccess(e, item, key = 'audio_url') {
    item[key] = e.url;
    this.save();
    // console.log('item: ', item);
  }

  onDeletaImg(item, key) {
    delete item[key];
    this.save();
  }
  /**
   * 储存图片数据
   * @param e
   */
  onImageUploadSuccess(e, key, item) {

    if (!item) {
      item = this.item;
    }
    item[key] = e.url;
    this.save();
  }

  /**
   * 储存音频数据
   * @param e
   */
  onAudioUploadSuccess(e, key, it) {
    it[key] = e.url;
    this.save();
  }

  KKBtnClick(it) {
    this.curSelectItem = it;
    this.isShowKK = true
  }

  KKHandleCancel() {
    this.isShowKK = false;
    this.curSelectKK = null;
    this.curSelectItem = null;
  }

  KKHandleOk() {

    // if (!this.curSelectItem.KKText) {
    //   this.curSelectItem.KKText = '';
    // }
    this.curSelectItem.KKText = this.curSelectKK;

    this.KKHandleCancel();

    this.save();
  }

  saveItemText(it, key) {
    console.log('it: ', it);
    this.save();
  }

  getItemHasInputPic(it) {
    return it.labelArr && it.labelArr[0]?.type == 'inputPic';
  }

  getItemHasInputAudio(it) {
    return it.labelArr && it.labelArr[0]?.type == 'inputAudio';
  }

  getItemHasInputText(it) {
    return it.labelArr && it.labelArr[0]?.type == 'inputText';
  }

  getItemHasTargetType(it, targetType) {
    return it.labelArr && it.labelArr[0]?.type == targetType;
  }

  addListItem(it, key) {

    if (!it[key]) {
      it[key] = [];
    }
    it[key].push({});
  }

  deleteListItem(arr, i) {
    arr.splice(i, 1);
    // this.save();
  }


  showPreviewTemplate() {
    this.isPreviewTemplate = true;

    //正常模板显示 赋值数据
    if (this.baseData && this.item.tempItem) {

      this.tempItem = this.item.tempItem;
    } else {

      this.tempItem = {}
      this.tempItem.quesArr = [];
      // this.addOnePageBtnClick();
    }

  }

  hidePreviewTemplate() {
    this.isPreviewTemplate = false;
  }

  addOnePartBtnClick() {
    this.item.partArr.push(
      {
        type: "text"
      }
    );

    this.save();
  }

  addOnePageBtnClick(isSave = true) {

    this.item.quesArr.push(
      {
        type: "dictionary"
      }
    );

    if (isSave) {
      this.save();
    }
  }

  addOneOption(ques) {
    if (!ques.optionArr) {
      ques.optionArr = [];
    }
    ques.optionArr.push({
    });
    this.save();
  }

  deleteOptionBtnClick(arr, i) {
    arr.splice(i, 1);
    this.save();
  }

  deletePartBtnClick(i) {
    this.item.partArr.splice(i, 1);
    this.save();
  }

  deletePageBtnClick(i) {
    this.item.quesArr.splice(i, 1);
    this.save();
  }

  checkboxChange(e, it, key) {
    console.log('e: ', e);

    it[key] = e;
    this.save();
  }

  addSubOptArr(option) {
    if (!option.subOptArr) {
      option.subOptArr = [];
    }

    option.subOptArr.push({});
  }


  clickPosList(ques, pos) {
    ques.pos = pos;
    this.save();
  }

  deletePosBtnClick(ques) {
    ques.pos = '';
    this.save();
  }


  getNewSortItem() {
    const newItem = JSON.parse(JSON.stringify(this.item));
    newItem.quesArr.sort((item1, item2) => {
      if (item1.type === 'dictionary' && item2.type !== 'dictionary') {
        return -1; // item1 放前面
      } else if (item1.type !== 'dictionary' && item2.type === 'dictionary') {
        return 1; // item2 放前面
      } else if (item1.type === 'dictation' && item2.type !== 'dictation') {
        return 1; // item1 放后面
      } else if (item1.type !== 'dictation' && item2.type === 'dictation') {
        return -1; // item2 放后面
      } else {
        return 0; // 其他顺序不变
      }
    });

    return newItem;
  }

  /**
   * 储存数据
   */
  save() {

    this.refreshQuesIndex();

    // if (this.tempItem) {
    //   this.item.tempItem = this.tempItem;
    // }

    // if (this.customTypeGroupArr) {
    //   this.item.customTypeGroupArr = this.customTypeGroupArr;
    // }
    const newItem = this.getNewSortItem();

    (<any>window).courseware.setData(newItem, null, this.saveKey);

    this.refresh();
    console.log('this.item = ' + JSON.stringify(this.item));

    this.message.create('success', "保存成功");

  }

  /**
   * 刷新 渲染页面
   */
  refresh() {
    setTimeout(() => {
      this.appRef.tick();
    }, 1);
  }

}