import { AfterViewInit, Component, ElementRef, EventEmitter, Input, OnInit, Output, Pipe, PipeTransform, TemplateRef, ViewChild } from '@angular/core';
import { format } from 'date-fns';
import { Header } from './pager.component';

@Component({
  selector: 'cg-pager-table',
  template: `


<!--
<p *ngIf="ready">isOverflowX:  {{isOverflowX}}</p>
<p *ngIf="ready">isOverflowY:  {{isOverflowY}}</p>

<p *ngIf="ready">scrollLeft:{{container?.scrollLeft}}</p>
<p *ngIf="ready">clientWidth:{{container?.clientWidth}}</p>
<p *ngIf="ready">scrollWidth:{{container?.scrollWidth}}</p>
<p *ngIf="ready">isScrollBegin:{{isScrollBegin}}</p>
<p *ngIf="ready">isScrollToEnd:{{isScrollToEnd}}</p>
-->


<div #container class="table-responsive"  >
  <table class="table table-hover"  >
  <thead>
    <tr>
      <th cg-sort-header *ngFor="let header of headersFiltered; let i=index" [enabled]="enableSort && header.orderable" [order]="header.order" (onSortChange)="sort(header, $event)" >{{header.title}}</th>
      <th *ngIf="cellRenders && cellRenders['tableOperations']" class="text-center" [ngClass]="{'right-col-shadow' : isOverflowX &&  !isScrollToEnd, 'right' : isOverflowX}" i18n>操作</th>
    </tr>
  </thead>
  <tbody>
    <tr *ngFor="let item of list">

      <ng-container *ngFor="let header of headersFiltered; let i=index">
        <td *ngIf="!cellRenders || !cellRenders[header.data]; else defaultCellRender" 
          [innerHTML]="item[header.data] | cellRender:header" >
        </td>
        <ng-template #defaultCellRender>
          <td>
            <ng-container *ngIf="cellRenders && cellRenders[header.data]"> 
              <ng-container *ngTemplateOutlet="cellRenders[header.data]; context:{item, header}"></ng-container>
            </ng-container>
          </td>
        </ng-template>
      </ng-container>

      <td *ngIf="cellRenders && cellRenders['tableOperations']" class="text-center" [ngClass]="{'right-col-shadow' : isOverflowX && !isScrollToEnd, 'right' : isOverflowX}" >
        <ng-container *ngTemplateOutlet="cellRenders['tableOperations']; context:{item, headers}"></ng-container>
      </td>

    </tr>
  </tbody>
  </table>
</div>




  `,

  styles: [
    `
  :host{
  }

  .table-responsive {
  }
    
  table {
    width:100%;
    overflow: auto;
    max-height:500px;
  }

  .left, .right {
    position : sticky !important;
    display:block;
    right : 0;
    z-index: 101;
    min-width:200px;
  }

  .left { 
    left: 0;
  }

  .left-col-shadow, .right-col-shadow{
    background-color:#fefefe;
  }

  .left-col-shadow:after{
    box-shadow: inset 10px 0 8px -8px #00000026;
    position: absolute;
    top: 0;
    right: 0;
    bottom: -1px;
    width: 30px;
    transform: translate(100%);
    transition: box-shadow .3s;
    content: "";
    pointer-events: none;
  }

  .right-col-shadow:after{
    box-shadow: inset -10px 0 8px -8px #00000026;
    position: absolute;
    top: 0;
    bottom: -1px;
    left: 0;
    width: 30px;
    transform: translate(-100%);
    transition: box-shadow .3s;
    content: "";
    pointer-events: none;
  }

  th,td {
    white-space:nowrap;
  }

  th {
    position: sticky !important;
    z-index:100;
    top: 0;
  }
    
    `
  ]
})
export class PagerTableComponent implements OnInit, AfterViewInit {
  @Input() headers: Header[];
  @Input() list: any[];
  @Input() cellRenders: CellRender;
  @Input() enableSort: boolean = true;
  @Output() onSort = new EventEmitter<any>();

  ready: boolean = false;

  @ViewChild('container') containerRef: ElementRef<HTMLElement>;

  sort(header: Header, order: string) {
    if (order == null) {
      this.onSort.emit([null, null])
    } else {
      this.onSort.emit([header.data, order]);
    }
  }

  sortStatus(header: Header) {
    return undefined;
  }

  get headersFiltered(): Header[] {
    if (this.headers) {
      return this.headers;
    }
    return [];
  }

  ticking = false;
  scrollLeft: number = 0;

  get isScrollBegin() { return this.ready && this.containerRef?.nativeElement.scrollLeft > 10 }
  get isScrollToEnd() { return this.ready && (this.containerRef?.nativeElement.scrollWidth - this.containerRef?.nativeElement.scrollLeft - this.containerRef?.nativeElement.clientWidth) <= 0 }

  get isOverflowX(): boolean { return this.ready && this.containerRef?.nativeElement.scrollWidth > this.containerRef?.nativeElement.clientWidth }
  get isOverflowY(): boolean { return this.ready && this.containerRef?.nativeElement.scrollHeight > this.containerRef?.nativeElement.clientHeight }



  constructor() { }

  ngAfterViewInit(): void {
    setTimeout(() => {
      this.ready = true;
    }, 100)
  }

  ngOnInit(): void {
    //setTimeout(() => {
    //  this.ready = true;
    //}, 1000)
  }

}


@Pipe({ name: 'cellRender' })
export class TableCellRenderPipe implements PipeTransform {
  transform(value: any, header: Header = null): any {
    //console.log('transform', value);
    if (value === null || value === undefined) {
      return '';
    } else if (header.type == 'date') {
      return format(new Date(value), 'yy/M/d H:m');
    } else if (header.type == 'boolean') {
      return value ? '是' : '否';
    } else if (header.type == 'other') {
      return JSON.stringify(value)
    }
    else return value;
  }
}



export interface CellRender {
  [key: string]: TemplateRef<any>;
}