import {Component, EventEmitter, Input, OnChanges, OnDestroy, Output, OnInit, ViewChild, ElementRef} from '@angular/core';
import { NzMessageService, UploadXHRArgs, UploadFile } from 'ng-zorro-antd';
import TWEEN from '@tweenjs/tween.js';
import { MySprite, removeItemFromArr,  Label, ShapeRect, ShapeRectNew } from '../util/Unit';
// import { EventManager } from '@angular/platform-browser';
// import { Label, ShapeRect } from 'src/app/play/Unit';


@Component({
  selector: 'app-ai-class',
  templateUrl: './ai-class.component.html',
  styleUrls: ['./ai-class.component.scss']
})
export class AiClassComponent implements OnDestroy, OnChanges {

  @ViewChild('canvas', {static: true}) canvas: ElementRef;
  @ViewChild('wrap', {static: true}) wrap: ElementRef;



  @Output()
  save = new EventEmitter();


  @Input()
  userData;
  data: any = {time: 60, startTime:0, itemArr:[]};

  timeBarWidth;
  oneTimeLen = 80;
  timeArr = [];


  canvasWidth = 1280;
  canvasHeight = 720;
  canvasBaseW = 1280;
  // @HostListener('window:resize', ['$event'])
  canvasBaseH = 720;
  mapScale = 1;
  ctx;
  mx;
  my; // 点击坐标

  canvasLeft;
  canvasTop;
  renderArr;

  animationId: any;

  addPanelVisible = false;
  curAddType;
  addTypeNickName;
  isTouchTimeBar = false;
  curSelectItem;
  itemH = 90;
  itemArr;
  rowArr = [];
  isShowKeyData = false;
  isShowItemBase = false;
  curKeyItem;
  curShowKeyItem;
  pasteData;
  isShowPanelGroup = false;
  curShowPanelGroup;
  panelGroupPropList;

  commonProp = [
    'x',
    'y',
    'anchorX',
    'anchorY',
    'scaleX',
    'scaleY',
    'opacity',
    'zIndex',
    'active',
  ]

  picGroup = this.commonProp;
  animaGroup = this.commonProp.concat('animation', 'times');

  customTypeGroupArr = [

    {
      name: '镜头',
      camera: true,
      copy: true,
      color: '#84f466'
    },
    {
      name: '图片',
      pic: true,
      fill: true,
      commonProp: true,
      copy: true,
      color: '#ffde00'
    },

    {
      name: '龙骨',
      anima: true,
      commonProp: true,
      copy: true,
      // color: '#ba27ff'
      color: '#ffa4e6'
    },

    {
      name: '音频',
      audio: true,
      color: '#0beffd'
    },
    {
      name: '按钮',
      pic: true,
      commonProp: true,
    },
    {
      name: '重玩按钮',
      pic: true,
      commonProp: true,
    },

    // {
    //   name: '选择题',
    //   panelGroup: [
    //     {key: '问题', data: this.picGroup},
    //     {key: '选项1', data: this.picGroup},
    //     {key: '选项2', data: this.picGroup},
    //     {key: '提交', data: this.picGroup},
    //     {key: '重玩', data: this.picGroup},
    //     {key: '正确动画', data: this.animaGroup},
    //     {key: '错误动画', data: this.animaGroup},
    //     {key: '待机动画', data: this.animaGroup},
    //   ],
    //   audioArr: [
    //     {key: '选项音频1'},
    //     {key: '选项音频2'},
    //     {key: '正确音频'},
    //     {key: '错误音频'},
    //   ],
    //   picArr: [
    //     {key: '问题'},
    //     {key: '选项1'},
    //     {key: '选项2'},
    //     {key: '提交'},
    //     {key: '重玩'},
    //     {key: '选项1选中'},
    //     {key: '选项2选中'},
    //   ],
    //   animaArr: [
    //     {key: '正确动画'},
    //     {key: '错误动画'},
    //     {key: '待机动画（可选）'},
    //   ],
    //   checkBox: {
    //     key: '正确选项：',
    //     option: [
    //       {key: '选项1'},
    //       {key: '选项2'},
    //     ]
    //   }
    // },
    // {
    //   name: '语音评测',
    //   panelGroup: [
    //     {key: '正确动画', data: this.animaGroup},
    //     {key: '错误动画', data: this.animaGroup},
    //     {key: '待机动画', data: this.animaGroup},
    //   ],
    //   labelArr: [
    //     {key: '评测文本'},
    //     {key: '评测时间'},
    //     {key: '拼读发音'},
    //   ],
    //   audioArr: [
    //     {key: '正确音频'},
    //     {key: '错误音频'},
    //   ],
    //   animaArr: [
    //     {key: '正确动画'},
    //     {key: '错误动画'},
    //     {key: '待机动画（可选）'},
    //   ]
    // },
  ]



  uploadUrl;
  uploadData;

  constructor(private nzMessageService: NzMessageService) {

    this.uploadUrl = (<any> window).courseware.uploadUrl();
    this.uploadData = (<any> window).courseware.uploadData();

    window['air'].getUploadCallback = (url, data) => {
      this.uploadUrl = url;
      this.uploadData = data;
    };

  }
  ngOnChanges() {
    // if (!this.picItem) {
    //   return;
    // }
  }

  ngOnInit() {
    console.log(' in ngOnInit')
    // this.timeBarWidth = this.data.time * this.oneTimeLen + 'px'

    this.initMouseListener();
    this.initKeyboardListener();

    this.init();
    this.update();

    // let length = this.data.time, i=1;
    // for(;this.timeArr.push(i++)<length;){}
  }



  init() {

    this.initData();
    this.initCtx();
    this.initView();
  }

  initData() {

    console.log('this.itemArr: ', this.itemArr);

    if (this.userData) {
      console.log('this.userData: ', this.userData);
      this.data = this.userData;
      this.userData = null;
    }
    if (this.data.itemArr.length == 0) {
      this.initCamera();
    }

    this.wrap.nativeElement.style.width = (this.data.time + 1) * this.timeBarUnitW + 'px';
    this.wrap.nativeElement.style.height = ((this.data.itemArr?.length || 0) + 4) * this.itemH + (5) + 'px';


    this.canvasWidth = this.wrap.nativeElement.clientWidth;
    this.canvasHeight = this.wrap.nativeElement.clientHeight;
    this.mapScale = this.canvasWidth / this.canvasBaseW;
    this.renderArr = [];

  }

  initCtx() {
    this.ctx = this.canvas.nativeElement.getContext('2d');
    this.canvas.nativeElement.width = this.canvasWidth;
    this.canvas.nativeElement.height = this.canvasHeight;
    window['curCtx'] = this.ctx;
  }

  // getDataByUserData() {

  //   const data = JSON.parse(JSON.stringify(this.userData));
  //   const itemArr = data.itemArr;
  //   for (let i=0; i<itemArr.length; i++) {
      
  //   }
  //   return 
  // }
  

  initKeyboardListener() {

    // this.eventManager.addGlobalEventListener('window','keyup.esc',()=>{
    //   alert('你点击了ESC');
    // });

    document.onkeydown = ((event) => {
      const key = event.key.toLowerCase();
      if (key == 'k') {
        this.addKeys();
      }
      // console.log('event: ',event);
    });
  }

  initMouseListener() {

    if (this.IsPC()) {

      this.canvas.nativeElement.addEventListener('mousedown', (event) => {
        setMxMyByMouse(event);
        this.mapDown(event);
      });

      this.canvas.nativeElement.addEventListener('mousemove', (event) => {
        setMxMyByMouse(event);
        this.mapMove(event);
      });

      this.canvas.nativeElement.addEventListener('mouseup', (event) => {
        setMxMyByMouse(event);
        this.mapUp(event);
      });

      const setMxMyByMouse = (event) => {
        this.mx = event.offsetX;
        this.my = event.offsetY;
      };

    } else {

      this.canvas.nativeElement.addEventListener('touchstart', (event) => {
        setMxMyByTouch(event);
        this.mapDown(event);
      });

      this.canvas.nativeElement.addEventListener('touchmove', (event) => {
        setMxMyByTouch(event);
        this.mapMove(event);
      });

      this.canvas.nativeElement.addEventListener('touchend', (event) => {
        setMxMyByTouch(event);
        this.mapUp(event);
      });

      this.canvas.nativeElement.addEventListener('touchcancel', (event) => {
        setMxMyByTouch(event);
        this.mapUp(event);
      });


      const setMxMyByTouch = (event) => {
        if (event.touches.length <= 0) {
          return;
        }

        if (this.canvasLeft == null) {
          setParentOffset();
        }

        this.mx = event.touches[0].pageX - this.canvasLeft;
        this.my = event.touches[0].pageY - this.canvasTop;
      };


      const setParentOffset = () => {

        const rect = this.canvas.nativeElement.getBoundingClientRect();
        this.canvasLeft = rect.left;
        this.canvasTop = rect.top;
      };
    }
  }

  IsPC() {
    if (window['ELECTRON']) {
      return false; // 封装客户端标记
    }
    if (document.body.ontouchstart !== undefined) {
      return false;
    } else {
      return true;
    }
  }



  initView() {
    this.initTimeBar();
    this.initItemArr();
  }

  timeBarUnitW = 80;
  timeBarHeight = 40;
  timeBar;
  timeBarBtn;
  initTimeBar() {

    const timeBar = new ShapeRectNew()
    timeBar.fillColor = '#84f466'
    timeBar.y = 5;
    timeBar.setSize(300, 40, 1);
    timeBar.stroke = true;
    // timeBar.fill = true;
    timeBar.lineWidth = 2;
    // this.renderArr.push(timeBar);

    this.timeBar = timeBar;
    this.refreshTimeBarSize();


    this.timeBarBtn = new MySprite(this.ctx);
    this.timeBarBtn.load('assets/common/time_bar_btn.png');
  
    this.timeBarBtn.setScaleXY(0.5)
    timeBar.addChild(this.timeBarBtn);

    const btnLine = new ShapeRect(this.ctx);
    btnLine.setSize(1, this.canvasHeight);
    btnLine.x = -0.5;
    btnLine.setScaleXY(1 / this.timeBarBtn.scaleY);
    this.timeBarBtn.addChild(btnLine);

  }

  initItemArr() {
    if (!this.itemArr) {
      this.itemArr = this.data.itemArr;
    }

    this.refreshItemArr();
  
  }


  refreshTimeBarSize() {

    const totalW = this.data.time * this.timeBarUnitW;
 

    this.timeBar.setSize(totalW, this.timeBarHeight, 1);


    for (let i=0; i<this.data.time; i++) {
      const bigLine = new ShapeRect();
      bigLine.fillColor = '#000000';
      bigLine.setSize(1, this.timeBarHeight);
      bigLine.x = i * this.timeBarUnitW;
      this.timeBar.addChild(bigLine);

      const smallLine = new ShapeRect();
      smallLine.fillColor = '#000000';
      smallLine.setSize(1, this.timeBarHeight/2);
      smallLine.x = i * this.timeBarUnitW + this.timeBarUnitW / 2;
      smallLine.y = this.timeBarHeight / 2;
      this.timeBar.addChild(smallLine);

      const timeLabel = new Label();
      timeLabel.x = this.timeBarUnitW;
      timeLabel.fontSize = 20;
      timeLabel.fontColor = '#ffffff'
      timeLabel.y = bigLine.height + timeLabel.fontSize / 2;

      timeLabel.text = (i + 1).toString();
      bigLine.addChild(timeLabel);
    }

  }

  addTimeLine(item) {
    for (let i=0; i<this.data.time + 1; i++) {

      const smallLine = new ShapeRect();
      smallLine.fillColor = '#000000';
      smallLine.setSize(1, this.timeBarHeight/2);
      smallLine.x = i * this.timeBarUnitW;
      item.addChild(smallLine);

      const timeLabel = new Label();
      timeLabel.x = this.timeBarUnitW;
      timeLabel.fontSize = 15;
      // timeLabel.fontColor = '#ffffff'
      timeLabel.y = timeLabel.fontSize / 2 + 2;

      timeLabel.text = (i + 1).toString();
      smallLine.addChild(timeLabel);
    }
  }


  refreshTimeBarBtnPos() {
    this.timeBarBtn.x = this.mx;
    if (this.timeBarBtn.x > this.timeBarBtn.parent.width) {
      this.timeBarBtn.x = this.timeBarBtn.parent.width;
    }
  }

  refreshCurKeyItemPos() {
    this.curKeyItem.x = this.mx - this.curKeyItem.width / 2;
    if (this.curKeyItem.x > this.curKeyItem.parent.width) {
      this.curKeyItem.x = this.curKeyItem.parent.width - this.curKeyItem.width / 2;
    }
  }

  checkIsClickKeyItem() {
    const curTime = new Date().getTime();
    const subTime = curTime - this.curKeyItem.touchTime;
    console.log('subTime: ', subTime);
    if (subTime <= 200) {
      this.keyItemClicked(this.curKeyItem);
    }
  }

  keyItemClicked(keyItem) {
    console.log('this.curKeyItem: ', this.curKeyItem)

    this.curShowKeyItem = keyItem;
    this.isShowKeyData = true;
  }

  keyDataClose() {
    this.isShowKeyData = false;
    this.refreshKeyPos(this.curShowKeyItem);
  }

  keyDataOk() {
    this.isShowKeyData = false;
    this.refreshKeyPos(this.curShowKeyItem);
    this.refreshKeyArrData(this.curShowKeyItem.baseItem);
  }

  keyDataCancel() {
    this.isShowKeyData = false;

  }

  editBtnClick() {
    this.isShowItemBase = true;
  }

  itemBaseOk() {
    this.isShowItemBase = false;

  }

  itemBaseCancel() {
    this.isShowItemBase = false;

  }






  mapDown(event) {

    for (let i=0; i<this.itemArr.length; i++) {
      const keyArr = this.itemArr[i].keyArr;
      if (keyArr) {
        for (let j=0; j<keyArr.length; j++) {
          if (this.checkClickTarget(keyArr[j])) {
            this.curKeyItem = keyArr[j];
            this.curKeyItem.touchTime = new Date().getTime();

            this.isTouchTimeBar = true;
            return;
          }
        }
      }
    }

    if (this.checkClickTarget(this.timeBar)) {
      this.isTouchTimeBar = true;
      this.refreshTimeBarBtnPos();
      return;
    }


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

      if (this.checkClickTarget(this.itemArr[i].colorLine)) {
        if (this.curSelectItem) {
          this.hideItemSelect(this.curSelectItem);
        }

        this.curSelectItem = this.itemArr[i];
        this.selectItem();

        this.isTouchTimeBar = true;
        this.refreshTimeBarBtnPos();
        return;
      }
    }
    // if (this.curSelectItem && this.checkClickTarget(this.curSelectItem.colorLine)) {
    //   this.isTouchTimeBar = true;
    //   this.refreshTimeBarBtnPos();
    //   return;
    // }
    

  }


  mapMove(event) {
   
    if (this.curKeyItem) {
      this.refreshCurKeyItemPos();
      // return;
    }

    if (this.isTouchTimeBar) {
      this.refreshTimeBarBtnPos();
    }
  }

  mapUp(event) {

    if (this.curKeyItem) {
      this.checkIsClickKeyItem();
      this.refreshKeyTime(this.curKeyItem);
    }
    this.curKeyItem = null;
    this.isTouchTimeBar = false;
  }
  

  checkClickTarget(target) {
    if (!target || !target.visible) {
      return;
    }
    const rect = target.getBoundingBox();
    if (this.checkPointInRect(this.mx, this.my, rect)) {
      return true;
    }
    return false;
  }

  checkPointInRect(x, y, rect) {
    if (x >= rect.x && x <= rect.x + rect.width) {
      if (y >= rect.y && y <= rect.y + rect.height) {
        return true;
      }
    }
    return false;
  }




  update() {
    if (!this.ctx) {
      return;
    }


    this.animationId = window.requestAnimationFrame(this.update.bind(this));
    // 清除画布内容
    this.ctx.clearRect(0, 0, this.canvasWidth, this.canvasHeight);

    for (let i = 0; i < this.renderArr.length; i++) {
      this.renderArr[i].update(this);
    }

    this.updateArr(this.rowArr);
    this.updateItem(this.timeBar);

    TWEEN.update();
  }

  updateArr(arr) {
    if (arr) {
      for (let i = 0; i < arr.length; i++) {
        arr[i].update();
      }
    }
  }

  updateItem(item) {
    if (item) {
      item.update();
    }
  }

  addBtnClick() {
   this.addPanelVisible = true;

   this.refreshItemArr();
  }

  initCamera() {
    const item = {
      gId: '0',
      data: this.customTypeGroupArr[0],
      nickName: this.addTypeNickName || this.customTypeGroupArr[0].name
    }

    this.data.itemArr.push(item)
  }

  addItem() {

    const item = {
      gId: this.curAddType,
      data: this.customTypeGroupArr[this.curAddType],
      nickName: this.addTypeNickName || this.customTypeGroupArr[this.curAddType].name
    }

    this.data.itemArr.push(item)

    const isCanvasResize = this.checkCanvasResize();
    if (isCanvasResize) {
      return;
    } else {
      this.refreshItemArr();
    }

  }

  checkCanvasResize() {

    const totalH = this.canvasHeight;
    const curH = (this.itemArr.length + 1) * this.itemH;

    console.log('curH: ', curH);
    console.log('totalH: ', totalH);

    if (curH > totalH) {
      this.init();
      return true;
    }

    return false;
  }

  refreshItemArr() {

    this.curSelectItem = null;

    const baseY = this.itemH;
    this.rowArr = [];
    for (let i=0; i<this.itemArr.length; i++) {

      // if (!this.itemArr[i].colorLine) {
        this.itemArr[i].colorLine = this.getColorLine(this.itemArr[i].data);
        this.itemArr[i].keyArr = [];

        if (this.itemArr[i].keyArrData) {
          this.addItemKeyByData(this.itemArr[i]);
        }
      // } 

      const colorLine = this.itemArr[i].colorLine
      colorLine.y = baseY + i * this.itemH;
      this.rowArr.push(colorLine);
      this.hideItemSelect(this.itemArr[i]);

    }
  }

  addItemKeyByData(item) {
    const keyArrData = item.keyArrData;
    for (let i=0; i<keyArrData.length; i++) {
      this.addItemKey(item, keyArrData[i]);
    }
  }

  getColorLine(data) {
    const colorLine = new ShapeRectNew(this.ctx);
    colorLine.fill = false;
    colorLine.stroke = true;
    colorLine.setOutLine('#000000', 1);
    colorLine.fillColor = '#9ab9ff';
    // row.setOutLine('#9ab9ff', 2);
    colorLine.setSize(this.canvasWidth, this.itemH, 0)

    const centerLine = new ShapeRect(this.ctx);
    centerLine.setSize(this.canvasWidth, 2);
    centerLine.fillColor = data.color || '#ffffff';
    colorLine.addChild(centerLine);
    centerLine.y = this.itemH / 2;


    this.addTimeLine(colorLine);

    return colorLine;
  }

  deleteBtnClick(index) {
    const item = this.data.itemArr.splice(index, 1)[0];
    this.refreshItemArr();
    // removeItemFromArr(this.renderArr, item.pic);
    // removeItemFromArr(this.renderArr, item.textLabel);
  }

  onItemImgUploadSuccess(e, item) {
    item.pic_url = e.url;

  }

  onItemAudioUploadSuccess(e, item) {
    item.audio_url = e.url;
  }

  onDragonBoneUploadSuccess(e, item=null) {

    console.log('aabb');
    if (!item) {
      item = this.curSelectItem;
    }
    console.log('in onDragonBoneUploadSuccess e:', e);
    item.skeJsonData = e.skeJsonData;
    item.texJsonData = e.texJsonData;
    item.texPngData = e.texPngData;
  }
  

  saveText(item) {
    item.textLabel.text = item.text;
  }



  saveTime() {
    this.data.time = Math.floor(this.data.time);
    this.init();
  }

  customRadioChange(e) {

    console.log('in customRadioChange', e);
    this.curAddType = e;
    // item.gIdx = -1;
    // setTimeout(() => {
    //   item.gIdx = e;
    //   // this.refreshCustomItem(item);
    //   // this.refresh();
    // }, 1);

  }

  addPanelCloseAfter() {

  }

  addPanelCancel() {
    this.addPanelVisible = false;

  }

  addPanelOk() {

    if (!this.curAddType) {
      return;
    }

    console.log('addTypeNickName: ', this.addTypeNickName);

    this.addItem();
    this.addPanelVisible = false;
    this.addTypeNickName = null;

  }


  clickedItem(item) {
    console.log('in clickedItem');

    if (this.curSelectItem == item) {
      return;
      // this.curSelectItem = null;
    } else {
      this.curSelectItem = item
    }
    this.selectItem();
  }

  selectItem() {

    this.cleanSelect();
    if (this.curSelectItem) {
      this.showItemSelect(this.curSelectItem);
    }
  }

  cleanSelect() {
    for (let i=0; i<this.itemArr.length; i++) {
      this.hideItemSelect( this.itemArr[i]);
    }
  }

  showItemSelect(item) {
    item.colorLine.fill = true;
  }

  hideItemSelect(item) {
    item.colorLine.fill = false;
  }

  addKeys() {
    if (!this.curSelectItem) {
      return;
    }

    this.addItemKey(this.curSelectItem) 
  }

  addItemKey(item, data=null) {

    const colorRect = this.getColorRect(item.data);
    colorRect.y = this.itemH / 2 - colorRect.height / 2;
    item.colorLine.addChild(colorRect);

    colorRect['baseItem'] = item;

    if (!item.keyArr) {
      item.keyArr = [];
    }
    item.keyArr.push(colorRect);

    if (data) {
      colorRect['data'] = data;
      this.refreshKeyPos(colorRect);
    } else {

      colorRect['data'] = {};
      colorRect['data']['panelGroup'] = this.initItemPanelGroupData(item);

      // console.log('colorRect.panelGroup: ', colorRect['panelGroup'] )
      colorRect.x = this.timeBarBtn.x - colorRect.width / 2;
      this.refreshKeyTime(colorRect);

      this.refreshKeyArrData(item);
    }
    

    console.log('item.keyArr: ', item.keyArr);


  }

  initItemPanelGroupData(item) {

    // console.log(' in initItemPanelGroupData item: ', item);
    if (!item.data.panelGroup) {
      return [];
    }

    const arr = [];
    for (let i=0; i<item.data.panelGroup.length; i++) {
      const {key} = item.data.panelGroup[i];
      arr.push({key, data: {}});
    
    }
    console.log('arr: ', arr);
    return arr
  }


  refreshKeyTime(keyItem) {

    const time = Math.floor( (keyItem.x + keyItem.width / 2) / this.timeBarUnitW  * 1000) / 1000;
    keyItem.data.time = time;
  }

  refreshKeyPos(item) {
    
    const itemData = item.data;
    const posX = itemData.time * this.timeBarUnitW - item.width / 2;
    item.x = posX;
  }




  getColorRect(data) {

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

    const rect = new ShapeRectNew(this.ctx);
    rect.fillColor = data.color || '#ffffff';
    rect.stroke = true;
    rect.lineWidth = 1;
    rect.setSize(this.itemH * 0.1, this.itemH * 0.3, 2);
    return rect;

  }

  copyKeyItemData() {
   
    const jsonData = this.curShowKeyItem.data;

    const oInput = document.createElement('input');
    oInput.value = JSON.stringify(jsonData);
    document.body.appendChild(oInput);
    oInput.select(); // 选择对象
    document.execCommand('Copy'); // 执行浏览器复制命令

    document.body.removeChild(oInput);
    this.nzMessageService.success('复制成功');
  }

  importData() {
    if (!this.pasteData) {
      return;
    }

    if (!this.curShowKeyItem) {
      return;
    }

    try {
      const data = JSON.parse(this.pasteData);
      data.time = this.curShowKeyItem.data.time;
      console.log('data:', data);
      this.curShowKeyItem.data = data;

      this.pasteData = '';
    } catch (e) {
      console.log('err: ', e);
      this.nzMessageService.error('导入失败');
    }
  }

  copyPanelGroup() {
    const jsonData = this.curShowPanelGroup.data;

    const oInput = document.createElement('input');
    oInput.value = JSON.stringify(jsonData);
    document.body.appendChild(oInput);
    oInput.select(); // 选择对象
    document.execCommand('Copy'); // 执行浏览器复制命令

    document.body.removeChild(oInput);
    this.nzMessageService.success('复制成功');
  }

  importPanelGroup() {
    if (!this.pasteData) {
      return;
    }

    if (!this.curShowPanelGroup) {
      return;
    }

    try {
      const data = JSON.parse(this.pasteData);
      data.time = null;
      console.log('data:', data);
      this.curShowPanelGroup.data = data;

      this.pasteData = '';
    } catch (e) {
      console.log('err: ', e);
      this.nzMessageService.error('导入失败');
    }
  }


  deleteKeyItem() {

    this.curShowKeyItem.parent.removeChild(this.curShowKeyItem);
    removeItemFromArr(this.curShowKeyItem.baseItem.keyArr, this.curShowKeyItem)
    this.refreshKeyArrData(this.curShowKeyItem.baseItem);

    this.isShowKeyData = false;
    this.curShowKeyItem = null;
  }










  saveBtnClick() {
    const sendData = this.getSendData();
    this.save.emit(sendData)
  }

  getSendData() {
    console.log('this.data: ', this.data);

    const userData: any = {}

    for(let key in this.data) {

      if (key == 'itemArr') {
        userData.itemArr = [];
        const itemArr = this.data.itemArr;
        for (let i=0; i<itemArr.length; i++) {
          const itemData = this.getItemData(itemArr[i]);
          userData.itemArr.push(itemData);
        }

      } else {
        userData[key] = this.data[key];
      }
    }


    return userData;
  }

  getItemData(item) {

    const itemData: any = {}
    for (let key in item) {

      switch(key) {

        case "colorLine": 
          // itemData[key] = this.getColorLineData(item[key]);
          break;
        
        case "keyArr":
        //   itemData['keyArrData'] = this.getKeyArrData(item[key]);
          break;
        case "keyArrData":
          itemData[key] = this.sortKeyArrData(item[key]);
          break;

        default:
          itemData[key] = item[key]
          break;
      }
    }

    return itemData;
  }

  sortKeyArrData(keyArrData) {
    const arr = keyArrData.sort((a, b) => {
      return a.time - b.time;
    })
    return arr;
  }

  getColorLineData(colorLine) {
    return null;
  }

  getKeyArrData(keyArr) {
    const keyArrData = [];
    for (let i=0; i<keyArr.length; i++) {
    
      keyArrData.push(keyArr[i].data)
    }
    return keyArrData;
  }

  refreshKeyArrData(item) {
    item.keyArrData = this.getKeyArrData(item.keyArr);
  }

  panelGroupBtnClick(index) {
    // const {key, data} = panelData;
    this.curShowPanelGroup = this.curShowKeyItem.data.panelGroup[index];
    this.panelGroupPropList = this.curShowKeyItem.baseItem.data.panelGroup[index].data;
    this.isShowPanelGroup = true;
  }

  panelGroupOk() {
    this.isShowPanelGroup = false;
    this.curShowPanelGroup = null;
    this.panelGroupPropList = null;
  }

  panelGroupCancel() {
    this.isShowPanelGroup = false;
    this.curShowPanelGroup = null;
    this.panelGroupPropList = null;
  }



  ngOnDestroy() {
  }

}
