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

export class RoleManagementPage {
  readonly page: Page;
  readonly table: Locator;
  readonly createRoleButton: Locator;
  readonly successMessage: Locator;
  readonly roleNameInput: Locator;
  readonly roleKeyInput: Locator;
  readonly roleSortInput: Locator;
  readonly statusSelect: Locator;
  readonly remarkInput: Locator;
  readonly permissionDialog: Locator;
  readonly savePermissionButton: Locator;
  readonly searchInput: Locator;
  readonly searchButton: Locator;
  readonly pagination: Locator;
  readonly nextPageButton: Locator;
  readonly prevPageButton: Locator;

  constructor(page: Page) {
    this.page = page;
    this.table = page.locator('.el-table').first();
    this.createRoleButton = page.getByRole('button', { name: '新增角色' }).or(page.locator('button:has-text("新增角色")'));
    this.successMessage = page.locator('.el-message--success').or(page.locator('.success-message'));
    this.roleNameInput = page.locator('input[placeholder*="角色名称"]').or(page.locator('input[name*="roleName"]'));
    this.roleKeyInput = page.locator('input[placeholder*="角色权限字符串"]').or(page.locator('input[name*="roleKey"]'));
    this.roleSortInput = page.locator('input[placeholder*="显示顺序"]').or(page.locator('input[name*="roleSort"]'));
    this.statusSelect = page.locator('select[name*="status"]').or(page.locator('.el-select'));
    this.remarkInput = page.locator('textarea[placeholder*="备注"]').or(page.locator('textarea[name*="remark"]'));
    this.permissionDialog = page.locator('.permission-dialog').or(page.locator('.el-dialog'));
    this.savePermissionButton = page.getByRole('button', { name: '保存' }).or(page.locator('.permission-dialog .save-button'));
    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.pagination = page.locator('.el-pagination').or(page.locator('.pagination'));
    this.nextPageButton = page.locator('.el-pagination .btn-next').or(page.locator('.pagination .next-page'));
    this.prevPageButton = page.locator('.el-pagination .btn-prev').or(page.locator('.pagination .prev-page'));
  }

  async goto() {
    try {
      console.log('导航到角色管理页面...');
      await this.page.goto('/roles');
      
      await this.page.waitForLoadState('networkidle');
      await this.table.waitFor({ state: 'visible', timeout: 10000 });
      await expect(this.page).toHaveURL(/.*roles/);
      
      console.log('角色管理页面加载完成');
    } catch (error) {
      await this.page.screenshot({ path: `test-results/role-management-error-${Date.now()}.png` });
      console.error('导航到角色管理页面失败:', error);
      throw new Error(`导航到角色管理页面失败: ${error instanceof Error ? error.message : String(error)}`);
    }
  }

  async waitForTableReady() {
    await this.table.waitFor({ state: 'visible', timeout: 10000 });
    
    await this.page.waitForFunction(
      () => {
        const rows = document.querySelectorAll('.el-table__body-wrapper tbody tr');
        return rows.length > 0;
      },
      { timeout: 5000 }
    ).catch(() => {
      console.log('表格没有数据，继续执行');
    });
  }

  async clickCreateRole() {
    await this.createRoleButton.click();
    await this.page.waitForTimeout(500);
  }

  async fillRoleForm(roleData: {
    roleName: string;
    roleKey: string;
    roleSort?: string;
    status?: string;
    remark?: string;
  }) {
    await this.page.locator('.el-dialog').locator('input').first().fill(roleData.roleName);
    await this.page.locator('.el-dialog').locator('input').nth(1).fill(roleData.roleKey);
    
    if (roleData.roleSort) {
      const sortInput = this.page.locator('.el-dialog').locator('.el-input-number');
      if (await sortInput.count() > 0) {
        const input = sortInput.locator('input');
        await input.fill(roleData.roleSort);
      }
    }
    
    if (roleData.status) {
      const statusSelect = this.page.locator('.el-dialog').locator('.el-form-item').filter({ hasText: '状态' }).locator('.el-select');
      if (await statusSelect.count() > 0) {
        await statusSelect.click();
        await this.page.waitForTimeout(500);
        
        const statusText = roleData.status === 'ACTIVE' ? '正常' : '禁用';
        const dropdown = this.page.locator('.el-select-dropdown');
        if (await dropdown.count() > 0) {
          const options = dropdown.locator('.el-select-dropdown__item');
          const optionCount = await options.count();
          
          for (let i = 0; i < optionCount; i++) {
            const optionText = await options.nth(i).textContent();
            if (optionText && optionText.includes(statusText)) {
              await options.nth(i).click();
              break;
            }
          }
        }
        
        await this.page.waitForTimeout(300);
      }
    }
    
    if (roleData.remark) {
      await this.page.locator('.el-dialog').locator('textarea').fill(roleData.remark);
    }
  }

  async submitForm() {
    const dialog = this.page.locator('.el-dialog');
    const submitButton = dialog.getByRole('button', { name: '确定' }).or(dialog.locator('button:has-text("确定")'));
    
    await submitButton.click();
    
    await this.page.waitForTimeout(1000);
  }

  async waitForSuccessMessage(timeout: number = 10000): Promise<boolean> {
    try {
      const message = this.page.locator('.el-message--success').or(this.page.locator('.el-message'));
      await message.waitFor({ state: 'visible', timeout });
      return true;
    } catch (error) {
      console.log('等待成功消息超时，检查是否有错误消息');
      
      try {
        const errorMessage = this.page.locator('.el-message--error').or(this.page.locator('.el-message--warning'));
        if (await errorMessage.count() > 0) {
          const errorText = await errorMessage.first().textContent();
          console.log('发现错误消息:', errorText);
        }
      } catch (e) {
        console.log('没有发现错误消息');
      }
      
      return false;
    }
  }

  async editRole(rowNumber: number) {
    await this.table.locator(`tbody tr:nth-child(${rowNumber})`).getByRole('button', { name: '编辑' }).or(this.page.locator(`tbody tr:nth-child(${rowNumber}) .edit-button`)).click();
  }

  async deleteRole(rowNumber: number) {
    await this.table.locator(`tbody tr:nth-child(${rowNumber})`).getByRole('button', { name: '删除' }).or(this.page.locator(`tbody tr:nth-child(${rowNumber}) .delete-button`)).click();
  }

  async confirmDelete() {
    await this.page.getByRole('button', { name: '确定' }).or(this.page.locator('.confirm-dialog .confirm-button')).click();
  }

  async openPermissionDialog(rowNumber: number) {
    await this.table.locator(`tbody tr:nth-child(${rowNumber})`).getByRole('button', { name: '权限' }).or(this.page.locator(`tbody tr:nth-child(${rowNumber}) .permission-button`)).click();
  }

  async selectPermission(permissionValue: string) {
    await this.page.click(`input[type="checkbox"][value="${permissionValue}"]`);
  }

  async savePermissions() {
    await this.savePermissionButton.click();
  }

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

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

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

  async getRoleName(rowNumber: number): Promise<string | null> {
    return await this.table.locator(`tbody tr:nth-child(${rowNumber}) td:first-child`).textContent();
  }

  async clickPermissionButton(rowNumber: number) {
    await this.table.locator(`tbody tr:nth-child(${rowNumber})`).getByRole('button', { name: '权限' }).or(this.page.locator(`tbody tr:nth-child(${rowNumber}) .permission-button`)).click();
  }

  async deselectPermission(permissionValue: string) {
    const checkbox = this.page.locator(`input[type="checkbox"][value="${permissionValue}"]`);
    if (await checkbox.isChecked()) {
      await checkbox.click();
    }
  }

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

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

  async clickStatusButton(rowNumber: number) {
    const row = this.table.locator(`tbody tr:nth-child(${rowNumber})`);
    await row.locator('.el-button--text').filter({ hasText: /状态|启用|禁用/ }).first().click();
  }

  async getCurrentPage(): Promise<string> {
    try {
      const activePage = this.page.locator('.el-pager li.is-active');
      if (await activePage.count() > 0) {
        return await activePage.textContent() || '1';
      }
      
      const currentPage = this.page.locator('.el-pagination__current');
      if (await currentPage.count() > 0) {
        return await currentPage.textContent() || '1';
      }
      
      return '1';
    } catch (error) {
      console.log('获取当前页码失败，返回默认值');
      return '1';
    }
  }

  async nextPage() {
    await this.nextPageButton.click();
  }

  async prevPage() {
    await this.prevPageButton.click();
  }
}
