import { HttpClient } from '@angular/common/http';
import { Component, OnInit } from '@angular/core';
import { EColType, ICol, IRows, ISearchParams } from '@bixi/core/table';

interface IPerson {
  name: string;
  age: number;
  id: number;
}

@Component({
  selector: 'core-table-simple-table-search',
  template: `
    <bixi-table
      [rows]="rows"
      [cols]="cols"
      [loading]="loading"
      [(pagination)]="pagination"
      [(selectedKeys)]="selectedKeys"
      (search)="onSearch($event)"
    >
    </bixi-table>
    <ng-template #tipTpl>
      <span>支持 template</span>
    </ng-template>
  `
})
export class IdeTablePaginationComponent implements OnInit {

  loading = false;
  pagination = {
    page: 1,
    pageSize: 10,
    total: 0
  };
  rows: IPerson[] = [];

  cols: ICol[] = [
    {
      key: 'id',
      type: EColType.checkbox,
      selectable: (_, row) => {
        return row.id !== 2;
      },
      onSelected: (row, i, val) => {
        console.log(`onSelected`, row, i, val);
      },
      selectionList: [
        {
          text: 'EVENT_1',
          onSelect: () => {
            console.log(`EVENT_1`);
          }
        },
        {
          text: 'EVENT_2',
          onSelect: () => {
            console.log(`EVENT_2`);
          }
        }
      ]
    },
    {
      name: '姓名',
      key: 'name',
      sort: {
        key: 'sort'
      }
    },
    {
      name: '年龄',
      key: 'age',
      filter: {
        options: [{ text: '1', value: 1 }]
      }
    }
  ];

  selectedKeys: number[] = [];
  selectedRows: IRows[] = [];

  constructor(private http: HttpClient) {

  }

  ngOnInit() {
    this.getData();
  }

  onSearch(_: ISearchParams) {
    this.getData();
  }

  getData() {
    console.log('getData', this.pagination);
    this.loading = true;
    const offset = (this.pagination.page - 1) * this.pagination.pageSize;
    const limit = this.pagination.pageSize;
    this.http.get<{ items: IPerson[], total: number }>(`/table?offset=${offset}&limit=${limit}`).subscribe(res => {
      this.rows = res.items;
      this.pagination = {
        ...this.pagination,
        total: res.total
      };
      this.loading = false;
    });
  }
}
