import { Page, Locator } from '@playwright/test';

export class ExceptionLogPage {
  readonly page: Page;
  readonly table: Locator;
  readonly searchInput: Locator;
  readonly searchButton: Locator;
  readonly exportButton: Locator;
  readonly refreshButton: Locator;
  readonly detailButton: Locator;
  readonly successMessage: Locator;

  constructor(page: Page) {
    this.page = page;
    this.table = page.locator('.el-table').or(page.locator('.exception-log-table'));
    this.searchInput = page.locator('input[placeholder*="搜索"]').or(page.locator('input[name*="keyword"]'));
    this.searchButton = page.getByRole('button', { name: '搜索' }).or(page.locator('button:has-text("搜索")'));
    this.exportButton = page.getByRole('button', { name: '导出' }).or(page.locator('button:has-text("导出")'));
    this.refreshButton = page.getByRole('button', { name: '刷新' }).or(page.locator('button:has-text("刷新")'));
    this.detailButton = page.getByRole('button', { name: '详情' }).or(page.locator('.detail-button'));
    this.successMessage = page.locator('.el-message--success').or(page.locator('.success-message'));
  }

  async goto() {
    await this.page.goto('/exceptionlog');
    await this.page.waitForLoadState('networkidle');
  }

  async search(keyword: string) {
    await this.searchInput.fill(keyword);
    await this.searchButton.click();
    await this.page.waitForTimeout(1000);
  }

  async clearSearch() {
    await this.searchInput.fill('');
    await this.searchButton.click();
    await this.page.waitForTimeout(1000);
  }

  async exportData() {
    await this.exportButton.click();
  }

  async refresh() {
    await this.refreshButton.click();
    await this.page.waitForLoadState('networkidle');
  }

  async viewDetail(exceptionId: string) {
    const exceptionRow = this.table.locator('tbody tr').filter({ hasText: exceptionId });
    await exceptionRow.locator('.detail-button').or(this.page.getByRole('button', { name: '详情' })).click();
  }

  async closeDetailDialog() {
    await this.page.getByRole('button', { name: '关闭' }).or(this.page.locator('.el-dialog .close-button')).click();
  }

  async containsText(text: string): Promise<boolean> {
    return await this.table.getByText(text).count() > 0;
  }

  async getTableRowCount(): Promise<number> {
    return await this.table.locator('tbody tr').count();
  }

  async isSuccessMessageVisible(): Promise<boolean> {
    try {
      return await this.successMessage.isVisible({ timeout: 3000 });
    } catch {
      return false;
    }
  }

  async reload() {
    await this.page.reload();
  }

  async verifyTableContains(text: string): Promise<void> {
    const contains = await this.containsText(text);
    if (!contains) {
      throw new Error(`Table does not contain text: ${text}`);
    }
  }

  async getLogCount(): Promise<number> {
    return await this.table.locator('tbody tr').count();
  }
}
