import { Directive, ElementRef, EventEmitter, HostListener, Output, Input, Renderer2 } from '@angular/core';
import { element } from 'protractor';

@Directive({
  selector: '[appDraggable]'
})
export class DraggableDirective {
  private offsetX: number = 0;
  private offsetY: number = 0;
  private isDragging: boolean = false;

  constructor(private el: ElementRef, private renderer: Renderer2) { }

  @Input() dragEnable: boolean;

  @Output() dragEvent = new EventEmitter<any>();

  @HostListener('mousedown', ['$event'])
  onMouseDown(event: MouseEvent) {
    if (!this.dragEnable || this.isDragging) {
      return;
    }
    this.isDragging = true;
    this.offsetX = event.clientX - this.el.nativeElement.getBoundingClientRect().left;
    this.offsetY = event.clientY - this.el.nativeElement.getBoundingClientRect().top;

    // this.renderer.setStyle(this.el.nativeElement, 'poniter', 'move');

    this.dragEvent.emit({
      type: 'mousedown',
      left: this.el.nativeElement.getBoundingClientRect().left + 'px',
      top: this.el.nativeElement.getBoundingClientRect().top + 'px',
      height: this.el.nativeElement.clientHeight + 'px',
      width: this.el.nativeElement.clientWidth + 'px',
      id: this.el.nativeElement.getAttribute('id')
    });
  }

  @HostListener('mousemove', ['$event'])
  onMouseMove(event: MouseEvent) {
    if (this.isDragging) {
      const x = event.clientX - this.offsetX;
      const y = event.clientY - this.offsetY;
      this.renderer.setStyle(this.el.nativeElement, 'left', x + 'px');
      this.renderer.setStyle(this.el.nativeElement, 'top', y + 'px');

      // this.dragEvent.emit({
      //   type: 'mousemove',
      //   left: this.el.nativeElement.style.left,
      //   top: this.el.nativeElement.style.top,
      //   height: this.el.nativeElement.clientHeight + 'px',
      //   width: this.el.nativeElement.clientWidth + 'px',
      //   id: this.el.nativeElement.getAttribute('id')
      // });
    }
  }

  @HostListener('mouseup')
  onMouseUp() {
    if (!this.dragEnable) {
      return;
    }
    this.isDragging = false;
    // 记录div位置
    // console.log('Left: ' + this.el.nativeElement.style.left + ', Top: ' + this.el.nativeElement.style.top);
    this.dragEvent.emit({
      type: 'mouseup',
      left: this.el.nativeElement.style.left,
      top: this.el.nativeElement.style.top,
      height: this.el.nativeElement.clientHeight + 'px',
      width: this.el.nativeElement.clientWidth + 'px',
      id: this.el.nativeElement.getAttribute('id')
    });
    // this.renderer.removeStyle(this.el.nativeElement, 'poniter');
  }
}
