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

export class UserManagementPage {
  readonly page: Page;
  readonly table: Locator;
  readonly createUserButton: Locator;
  readonly searchInput: Locator;
  readonly searchButton: Locator;
  readonly successMessage: Locator;
  readonly pagination: Locator;
  readonly nextPageButton: Locator;
  readonly prevPageButton: Locator;

  constructor(page: Page) {
    this.page = page;
    this.table = page.locator('.el-table').first();
    this.createUserButton = page.getByRole('button', { name: '新增用户' }).or(page.locator('button:has-text("新增用户")'));
    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.successMessage = page.locator('.el-message--success').or(page.locator('.success-message'));
    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() {
    await this.page.goto('/users');
    await this.page.waitForLoadState('networkidle');
  }

  async clickCreateUser() {
    await this.createUserButton.click();
    await this.page.waitForTimeout(500);
  }

  async fillUserForm(userData: {
    username: string;
    nickname?: string;
    email: string;
    phone?: string;
    password: string;
    confirmPassword?: string;
    status?: string;
  }) {
    const dialog = this.page.locator('.el-dialog');
    const isCreateMode = !userData.hasOwnProperty('id');
    
    // 表单字段顺序：
    // 创建模式：用户名(0), 密码(1), 昵称(2), 邮箱(3), 手机号(4)
    // 编辑模式：用户名(0), 昵称(1), 邮箱(2), 手机号(3)
    
    await dialog.locator('input').first().fill(userData.username);
    
    if (isCreateMode && userData.password) {
      await dialog.locator('input[type="password"]').fill(userData.password);
    }
    
    if (userData.nickname) {
      const nicknameIndex = isCreateMode ? 2 : 1;
      await dialog.locator('input').nth(nicknameIndex).fill(userData.nickname);
    }
    
    if (userData.email) {
      const emailIndex = isCreateMode ? 3 : 2;
      await dialog.locator('input').nth(emailIndex).fill(userData.email);
    }
    
    if (userData.phone) {
      const phoneIndex = isCreateMode ? 4 : 3;
      await dialog.locator('input').nth(phoneIndex).fill(userData.phone);
    }
    
    if (userData.status) {
      const statusSelect = 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 = userData.status === '1' || userData.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);
      }
    }
  }

  async submitForm() {
    await this.page.getByRole('button', { name: '确定' }).or(this.page.locator('button:has-text("确定")')).click();
  }

  async editUser(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 deleteUser(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 search(keyword: string) {
    await this.searchInput.fill(keyword);
    await this.searchButton.click();
  }

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

  async prevPage() {
    await this.prevPageButton.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 getUserCount(): Promise<number> {
    return await this.table.locator('tbody tr').count();
  }

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

  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 clickStatusButton(rowNumber: number) {
    const row = this.table.locator(`tbody tr:nth-child(${rowNumber})`);
    await row.locator('.el-tag').first().click();
    await this.page.waitForTimeout(500);
    
    const dropdown = this.page.locator('.el-dropdown');
    if (await dropdown.count() > 0) {
      const options = dropdown.locator('.el-dropdown-menu__item');
      const optionCount = await options.count();
      
      for (let i = 0; i < optionCount; i++) {
        const optionText = await options.nth(i).textContent();
        if (optionText && (optionText.includes('启用') || optionText.includes('禁用'))) {
          await options.nth(i).click();
          break;
        }
      }
    }
    
    await this.page.waitForTimeout(300);
  }

  async clickEditButton(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 clickDeleteButton(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 fillNickname(nickname: string) {
    const dialog = this.page.locator('.el-dialog');
    await dialog.locator('input').nth(1).fill(nickname);
  }

  async selectRole(roleName: string) {
    const dialog = this.page.locator('.el-dialog');
    const roleSelect = dialog.locator('.el-select');
    if (await roleSelect.count() > 0) {
      await roleSelect.first().click();
      await this.page.waitForTimeout(500);
      
      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(roleName)) {
            await options.nth(i).click();
            break;
          }
        }
      }
      
      await this.page.waitForTimeout(300);
    }
  }

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

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