import { ComponentFixture, TestBed } from '@angular/core/testing';
import { Component, DebugElement } from '@angular/core';
import { BixiTableModule, EColType, ICols } from '@bixi/core/table';
import { BrowserAnimationsModule, NoopAnimationsModule } from '@angular/platform-browser/animations';
import { NzToolTipModule } from 'ng-zorro-antd/tooltip';
import { By } from '@angular/platform-browser';


describe('col link', () => {
  let fixture: ComponentFixture<TestComponent>;
  let context: TestComponent;
  let debugEle: DebugElement;

  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [BixiTableModule, BrowserAnimationsModule, NzToolTipModule, NoopAnimationsModule],
      declarations: [TestComponent]
    });

    fixture = TestBed.createComponent(TestComponent);
    context = fixture.componentInstance;
    debugEle = fixture.debugElement;
  });

  it('should init', () => {
    // given
    context.cols = [{
      name: '基本显示',
      key: 'blog',
      type: EColType.link
    }];

    // when
    fixture.detectChanges();

    // then
    const anchorEle = debugEle.query(By.css('.bixi-table-col-link')).nativeElement.querySelector('a') as HTMLAnchorElement;
    expect(anchorEle.textContent).toEqual(links[0].blog);
    expect(anchorEle.href).toContain(links[0].blog);
  });

  it('should render custom value & href', () => {
    // given
    context.cols = [
      {
        name: '修改显示和链接',
        key: 'blog',
        type: EColType.link,
        value(val: string) {
          return `我的网址是：${ val }`;
        },
        href(val: string, row) {
          return `https://www.${ row.blog }?val=${ val }`;
        }
      }
    ];

    // when
    fixture.detectChanges();

    // then
    const anchorEle = debugEle.query(By.css('.bixi-table-col-link')).nativeElement.querySelector('a') as HTMLAnchorElement;
    expect(anchorEle.textContent).toContain(`我的网址是：${ links[0].blog }`);
    expect(decodeURI(anchorEle.href)).toEqual(`https://www.${ links[0].blog }?val=我的网址是：${ links[0].blog }`);
  });

  it('should render custom target', () => {
    // given
    context.cols = [
      {
        name: '新窗口打开',
        key: 'blog',
        type: EColType.link,
        target: '_blank',
        href(val: string) {
          return `https://www.${ val }`;
        }
      }
    ];

    // when
    fixture.detectChanges();

    // then
    const anchorEle = debugEle.query(By.css('.bixi-table-col-link')).nativeElement.querySelector('a') as HTMLAnchorElement;
    expect(anchorEle.target).toEqual('_blank');
  });
});

const links = [{
  blog: 'baidu.com/'
}];

@Component({
  template: `
    <bixi-table
      [rows]="rows"
      [cols]="cols"
    ></bixi-table>`
})
class TestComponent {
  rows = links;
  cols: ICols = [];
}
