import { ChangeDetectionStrategy, Component, Input, OnChanges, SimpleChanges } from '@angular/core';
import { IOperationsColBtn, IRow } from '../table.type';

@Component({
  selector: 'bixi-col-operations-template',
  template: `
    <ng-container *ngFor="let btn of _operations; let index = index">
      <ng-container *ngIf="btn.visible">
        <ng-container *ngIf="!btn.children || btn.children?.length === 0">
          <a
            class="bixi-col-operation"
            nz-tooltip
            [nzTooltipTitle]="btn.tooltip"
            [class.bixi-col-operation-disabled]="btn.disabled"
            (click)="onClick(btn)"
            >{{ btn.name }}
          </a>
        </ng-container>
        <ng-container *ngIf="btn.children?.length > 0">
          <a
            class="bixi-col-operation"
            nz-dropdown
            [nzDropdownMenu]="menu"
            [nzDisabled]="btn.disabled"
            [class.bixi-col-operation-disabled]="btn.disabled"
          >
            {{ btn.name }} <i *ngIf="!btn.name" nz-icon nzType="ellipsis" nzTheme="outline"></i>
          </a>
          <nz-dropdown-menu #menu="nzDropdownMenu">
            <ul nz-menu nzSelectable>
              <bixi-table-operations-group *ngFor="let item of btn.children" [operationGroup]="item" [row]="row" [rowIndex]="rowIndex">
              </bixi-table-operations-group>
            </ul>
          </nz-dropdown-menu>
        </ng-container>
      </ng-container>
    </ng-container>
  `,
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class ColOperationsTemplateComponent implements OnChanges {
  @Input() operations: IOperationsColBtn[];
  @Input() row: IRow;
  @Input() rowIndex: number;

  _operations: IOperationsColBtnWithDivider[];

  onClick(btn: IOperationsColBtn) {
    if (btn.disabled || !btn.onClick) return;
    btn.onClick(this.row, this.rowIndex);
  }

  ngOnChanges(changes: SimpleChanges) {
    const { operations } = changes;
    if (operations) {
      this._operations = this.mergeDividerVisible(operations.currentValue);
    }
  }

  mergeDividerVisible(originOperations: IOperationsColBtn[]): IOperationsColBtnWithDivider[] {
    return originOperations.map((e, i) => ({
      ...e,
      dividerVisible: this.isDividerVisible(originOperations, i)
    }));
  }

  isDividerVisible(originOperations: IOperationsColBtn[], index: number): boolean {
    let ret = false;
    originOperations.forEach((e, i) => {
      if (i > index) {
        if (e.visible) {
          ret = true;
        }
      }
    });
    return ret;
  }
}

interface IOperationsColBtnWithDivider extends IOperationsColBtn {
  dividerVisible: boolean;
}
