import {
  Component,
  EventEmitter,
  Input,
  OnDestroy,
  OnChanges,
  OnInit,
  Output,
  ApplicationRef,
  ChangeDetectorRef,
  ViewChildren, QueryList, ElementRef, ViewChild, AfterViewInit
} from '@angular/core';
import { CropperComponent } from 'angular-cropperjs';
import { NzMessageService } from 'ng-zorro-antd';
import * as _ from 'lodash';


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

  // 储存数据用
  saveKey = 'ww_reading';
  // 储存对象
  item;
  _tmpEditWord: string;
  _tmpEditData: any;
  imageUploader: any;

  uploading = false;

  progress = 0;
  // enableChangeImage = true;
  picId = '';
  @Output()
  imageUploaded = new EventEmitter();
  @Output()
  update = new EventEmitter();
  respipe: any;
  cropperParts: Array<{
    word: string,
    data: any,
    // imgData: any,
    previewCss: any,
    imgCss: any,

    // color: string
  }> = [];
  currentEditPartIndex = -1;
  colorIndex = 0;
  @ViewChildren('partConfigBoxes')
  partConfigBoxes: QueryList<ElementRef>;

  @ViewChild('angularCropper')
  angularCropper: CropperComponent;


  @ViewChild('partConfigBox')
  partConfigBox: ElementRef;
  @ViewChild('uploadImage')
  uploadImage: ElementRef;
  @ViewChild('img')
  img: ElementRef;


  colors = [
    '#4FC200',
    '#00C0FF',
    '#FFDC00',
    '#FF8F00',
    '#CF0000',
    '#8E33D4',
    '#FF0075'
  ];

  cropperConfig = {
    dragMode: 'move',
    movable: true,
    viewMode: 3,
    autoCrop: true,
    autoCropArea: .5,
    rotatable: false,
    zoomOnWheel: false,
    zoomable: false,
    toggleDragModeOnDblclick: false,
    ready: this.initCropper.bind(this),

    preview: '.crop-preview'
  };


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

  }


  ngOnInit() {

    this.item = {
      contentObj: {}
    };
    window['ff'] = this;

    // 获取存储的数据
    (window as any).courseware.getData((data) => {
      console.log(111, data)
      if (data) {
        this.item = data;
        // if (this.angularCropper) {
        //   this.angularCropper.cropper.reset();
        //   this.angularCropper.cropper.destroy();
        // }
        this.picId = this.item.contentObj.pic_id;
        this.currentEditPartIndex = -1;
        this.cropperParts.length = 0;
        setTimeout(() => {
          // console.log(this.item.id , this.item.contentObj.parts)
          const parts = _.get(this.item.contentObj, 'parts', []);
          this.cropperParts = parts.map(item => {
            const nitem = Object.assign({}, item);
            nitem.previewCss = {};
            nitem.imgCss = {};
            return nitem;
          });
          this.initWithDataAfterData();
          this.changeDetectorRef.markForCheck();
          this.changeDetectorRef.detectChanges();
          this.refresh();
        });
      }

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

    }, this.saveKey);

  }


  ngOnChanges() {
  }

  ngOnDestroy() {
  }



  init() {

  }






  /**
   * 储存数据
   */
  save() {
    const data = this.cropperParts.map(item => {
      const nitem = Object.assign({}, item);
      delete nitem.previewCss;
      delete nitem.imgCss;
      return nitem;
    });
    this.item.contentObj.parts = data;
    // this.item.contentObj['imgData'] = imgData;
    (window as any).courseware.setData(this.item, null, this.saveKey);
    this.changeDetectorRef.markForCheck();
    this.changeDetectorRef.detectChanges();
    this.refresh();
  }

  /**
   * 刷新 渲染页面
   */
  refresh() {
    setTimeout(() => {
      this.appRef.tick();
    }, 1);
  }
  changeImage() {
    // console.log(this.imageUploader);
    this.imageUploader = this.uploadImage.nativeElement.querySelector('input[type="file"]');
    // if (!this.imageUploader) {
    //   this.imageUploader = this.uploadImage.nativeElement.querySelector('input[type="file"]')
    //   if (!this.imageUploader.onclick) {
    //     const self = this;
    //     this.imageUploader.onclick = () => {
    //       document.body.addEventListener('focus', self.afterChangeImage.bind(self), true);
    //     };
    //   }
    // }

    this.imageUploader.click();
    // const self = this;

    // this.picId = 0;
  }


  onImageUploadSuccess(e) {
    this.item.contentObj.pic_id = e.url;
    this.picId = e.url;
    this.update.emit(this.item);
    if (this.angularCropper ) {
      this.item.contentObj.pic_id = this.picId = e.url;
      this.cropperParts.length = 0;
      if (this.angularCropper && this.angularCropper.cropper) {
        this.angularCropper.cropper.reset();
        this.angularCropper.cropper.destroy();
        this.colorIndex = 0;
      }
    }
  }



  getCss(data, target) {
    const imgData = this.item.contentObj.imgData;
    // const w = this.partConfigBox.nativeElement.offsetWidth;
    // const w = this.partBoxTpl.nativeElement.offsetWidth;
    // const part = this.partConfigBoxes.toArray()[this.currentEditPartIndex]

    const w = target.clientWidth;
    const h = target.clientHeight;
    // let scale = w / data.width;
    // if (data.height >= data.width) {
    //   scale = h / data.height;
    // }


    let scale = 1;
    const c_w = w / data.width;
    const c_h = h / data.height;
    scale = Math.min(c_w, c_h);


    const iw = scale * imgData.naturalWidth;
    const ih = scale * imgData.naturalHeight;
    const ix = scale * data.x;
    const iy = scale * data.y;

    const pw = scale * data.width;
    const ph = scale * data.height;

    return {iw, ih, ix, iy, pw, ph };
  }




  addPart() {
    // console.log('addPart');
    // const inv_idx = this.cropperParts.findIndex(item => {
    //   return !item.word || !item.word.trim();
    // });
    // if (inv_idx !== -1) {
    //   this.currentEditPartIndex = inv_idx;
    //   const el = this.partConfigBoxes.toArray()[inv_idx].nativeElement.querySelector('.part-word');
    //   if (!el.classList.contains('err')) {
    //     el.classList.add('err');
    //   }
    //   return;
    // }

    if (this.cropperParts.length === this.colors.length ) {
      this.nzMessageService.info('you can only add seven parts.');
      return;
    }
    // const last_color = this.cropperParts[this.cropperParts.length - 1].color;
    // this.colorIndex = this.colors.findIndex((c) => {
    //   return last_color === c;
    // });
    // this.colorIndex++;
    // const color = this.colors[this.colorIndex % this.colors.length];

    this.cropperParts.push({
      word: '',
      data: this.angularCropper.cropper.getData(),
      // imgData: imgData,
      previewCss: { },
      // `width:${pw}px;height:${ph}px;`,
      imgCss: {},
      // playerPmgCss: {},
      // color: color
    });
    this.currentEditPartIndex = this.cropperParts.length - 1;
    // this.angularCropper.cropper.reset();
    console.log(123123);
    this.focusUserInput();
    this.save();
    this.changeDetectorRef.markForCheck();
    this.changeDetectorRef.detectChanges();
    this.refresh();
  }
  focusUserInput() {
    setTimeout(() => {
      const ipt = this.partConfigBoxes.toArray()[this.currentEditPartIndex].nativeElement.querySelector('input')
        if (ipt) {
          ipt.focus();
        }
    }, 10);
  }

  editPart(evt, idx) {
    const img = evt.currentTarget.parentNode.parentNode.querySelector('img')
    console.log('editPart');
    this.currentEditPartIndex = idx;
    const obj = this.cropperParts[idx];
    this.angularCropper.cropper.setData(obj.data);
    obj.previewCss = { };
    obj.imgCss = { };
    this._tmpEditWord = obj.word;
    this._tmpEditData = Object.assign({}, obj.data);
    this.focusUserInput();
    this.initPart(img, idx);
  }
  confirmRemovePart(idx, evt) {
    this.removePart(idx, evt);
  }
  removePart(idx, evt) {
    this.cropperParts.splice(idx, 1);
    this.save();
    this.colorIndex -= 1;
    if (this.colorIndex < 0 ) {
      this.colorIndex = 0;
    }
  }
  exitEditPart(evt, idx) {

    console.log('exitEditPart')
    // if( !this.cropperParts[idx].word) {
    //   const el = this.partConfigBoxes.toArray()[idx].nativeElement.querySelector('.part-word');
    //   if (!el.classList.contains('err')) {
    //     el.classList.add('err');
    //   }
    //   return;
    // }
    // if (!this._tmpEditWord) {
    //   this._tmpEditWord = this.cropperParts[idx].word;
    // }

    this.currentEditPartIndex = -1;
    this.cropperParts[idx].word = this._tmpEditWord;
    if (this._tmpEditData) {
      this.cropperParts[idx].data = this._tmpEditData;
      this.angularCropper.cropper.setData(this._tmpEditData);
    }
    this._tmpEditWord = '';
    this._tmpEditData = {};

    const cropper: any = this.angularCropper.cropper;
    cropper.previews = [];
    this.changeDetectorRef.markForCheck();
    this.changeDetectorRef.detectChanges();
    this.refresh();

  }
    savePart(evt, idx) {

    // const el = this.partConfigBoxes.toArray()[idx].nativeElement.querySelector('.part-word');
    // if (!el.value) {
    //   if (!el.classList.contains('err')) {
    //     el.classList.add('err');
    //   }
    //   return;
    // }
    // if (el && el.classList.contains('err')) {
    //   return;
    // }
    console.log(evt);
    const img = evt.currentTarget.parentNode.parentNode.parentNode.querySelector('img')
    this.currentEditPartIndex = this.cropperParts.length - 1;
    this.currentEditPartIndex = -1;
    // const origin = this.cropperParts[idx];
    const data = this.angularCropper.cropper.getData();
    this.cropperParts[idx].data = {...data};

    const cropper: any = this.angularCropper.cropper;
    cropper.previews = [];
    this.initPart(img , idx);
    this.save();
    this.changeDetectorRef.markForCheck();
    this.changeDetectorRef.detectChanges();
    this.refresh();
  }
  previewUserSelectPart(idx) {
    const part = this.cropperParts[idx];
    this.angularCropper.cropper.setData(part.data);
  }
  initPart(evt, idx) {
    console.log('initPart', evt);
    const part = this.cropperParts[idx];
    const img = evt.target || evt;
    const preview = img.parentNode;
    if (!preview) {
      return;
    }
    const {iw, ih, ix, iy, pw, ph } = this.getCss(part.data, preview);
    part.previewCss = {
      'width.px': pw,
      'height.px': ph,
      'padding-bottom': 0
    };
    part.imgCss = {
      'width.px': iw,
      'height.px': ih,
      transform: `translateX(-${ix}px) translateY(-${iy}px)`
    };
    this.changeDetectorRef.markForCheck();
    this.changeDetectorRef.detectChanges();
    this.refresh();
  }
  onChangePartWord(val, idx ) {
    // const part = this.cropperParts[idx];
    const el: any  = this.partConfigBoxes.toArray()[idx].nativeElement.querySelector('.part-word');

    if (!val) {
      if (el && el.classList.contains('err')) {}
      el.classList.add('err');
    } else {
      if (el) {
        el.classList.remove('err');
      }
    }
  }


  ngAfterViewInit(){

  }
  initWithDataAfterData() {
    // console.log('ngAfterViewInit');

    this.partConfigBoxes.changes.subscribe(t => {
      const part = this.partConfigBoxes.toArray()[this.currentEditPartIndex];
      if (part) {
        const p = part.nativeElement.querySelector('.part-view');
        p.innerHTML = '';
        // debugger
        /*
        const img = <HTMLElement>this.angularCropper.imageElement.cloneNode();
        img.className = 'crop-part-preview';
        img.style.cssText = (
          `display: block;
          position: absolute;
          width: 100%;
          min-width: 0;
          min-height: 0;
          max-width: none;
          max-height: none;`
        );

        p.appendChild(img);
        */
        // const cfg = Object.assign({}, this.cropperConfig);
        // cfg['preview'] = p;
        const  cropper: any = this.angularCropper.cropper;
        if (!cropper.viewBox) {
          return;
        }
        cropper.viewBox.innerHTML = '';
        cropper.options.preview = p;
        cropper.initPreview();
        cropper.preview();
        p.style.padding = '0';

        // this.setPreviewImage();
      }
    });
    // this.enableChangeImage = true;



  }

  initCropper(evt) {

    // this.enableChangeImage = true;
    // this.angularCropper.cropper.setDragMode('move');
    // console.log('initCropper save imgData');
    this.item.contentObj.imgData = this.angularCropper.cropper.getImageData();
    // console.log(this.item.contentObj['imgData']);
    // this.item.contentObj['parts'] = [];
    // this.previewPart.nativeElement.style.padding = '0';

    // console.log('initCropper', pic, this.item.contentObj.pic_id);
    if (evt.target.src === this.item.contentObj.pic_id) {

    } else {
      // Ken 2018-09-29 14:54 不同时说明是重新上传的, 需要保存
      this.save();
    }
  }

}

