import { Page, Locator } from '@playwright/test';
// import { selectRadixOption, selectProvinceCity } from '@d8d/e2e-test-utils';
import { TIMEOUTS } from '../../utils/timeouts';

// 注意：@d8d/e2e-test-utils 包已安装，将在后续 story (2.2, 2.3) 中实际使用
export class DisabilityPersonManagementPage {
  readonly page: Page;
  readonly pageTitle: Locator;
  readonly addPersonButton: Locator;
  readonly keywordSearchInput: Locator;
  readonly searchButton: Locator;
  readonly personTable: Locator;

  constructor(page: Page) {
    this.page = page;
    this.pageTitle = page.getByText('残疾人个人管理');
    this.addPersonButton = page.getByRole('button', { name: '新增残疾人' });
    this.keywordSearchInput = page.getByPlaceholder('搜索姓名或身份证号');
    this.searchButton = page.getByRole('button', { name: '搜索' });
    this.personTable = page.locator('table');
  }

  async goto() {
    await this.page.goto('/admin/disabilities');
    await this.page.waitForLoadState('domcontentloaded');
    // 等待页面标题出现
    await this.pageTitle.waitFor({ state: 'visible', timeout: TIMEOUTS.PAGE_LOAD });
    // 等待表格数据加载
    await this.page.waitForSelector('table tbody tr', { state: 'visible', timeout: TIMEOUTS.PAGE_LOAD_LONG });
    await this.expectToBeVisible();
  }

  async expectToBeVisible() {
    await this.pageTitle.waitFor({ state: 'visible', timeout: TIMEOUTS.PAGE_LOAD });
    await this.addPersonButton.waitFor({ state: 'visible', timeout: TIMEOUTS.TABLE_LOAD });
  }

  async openCreateDialog() {
    // 监听网络请求
    const responses: any[] = [];
    this.page.on('response', async (response) => {
      if (response.url().includes('disabled-person') || response.url().includes('aggregated')) {
        try {
          const responseData = await response.json().catch(() => ({ status: response.status() }));
          responses.push({
            url: response.url(),
            status: response.status(),
            data: responseData
          });
        } catch (e) {
          responses.push({
            url: response.url(),
            status: response.status(),
            error: e
          });
        }
      }
    });

    await this.addPersonButton.click();
    await this.page.waitForSelector('[data-testid="create-disabled-person-dialog-title"]', { state: 'visible', timeout: TIMEOUTS.DIALOG });

    return responses;
  }

  async fillBasicForm(data: {
    name: string;
    gender: string;
    idCard: string;
    disabilityId: string;
    disabilityType: string;
    disabilityLevel: string;
    phone: string;
    idAddress: string;
    province: string;
    city: string;
  }) {
    // 等待表单出现
    const form = this.page.locator('form#create-form');
    await form.waitFor({ state: 'visible', timeout: TIMEOUTS.DIALOG });

    console.debug('开始填写表单...');

    // 填写基本信息 - 使用 form locator 确保只在对话框内查找
    await form.getByLabel('姓名 *').fill(data.name);
    console.debug('✓ 姓名已填写:', data.name);

    // 性别 - 使用 data-testid
    const genderTrigger = this.page.locator('[data-testid="gender-select"]');
    await genderTrigger.click();
    await this.page.getByRole('option', { name: data.gender }).click();
    console.debug('✓ 性别已选择:', data.gender);

    await form.getByLabel('身份证号 *').fill(data.idCard);
    console.debug('✓ 身份证号已填写');

    await form.getByLabel('残疾证号 *').fill(data.disabilityId);
    console.debug('✓ 残疾证号已填写');

    // 残疾类型 - 使用 data-testid
    const disabilityTypeTrigger = this.page.locator('[data-testid="disability-type-select"]');
    await disabilityTypeTrigger.scrollIntoViewIfNeeded();
    await this.page.waitForTimeout(TIMEOUTS.VERY_SHORT);
    await disabilityTypeTrigger.click();
    await this.page.getByRole('option', { name: data.disabilityType }).click();
    console.debug('✓ 残疾类型已选择:', data.disabilityType);

    // 残疾等级 - 使用 data-testid
    const disabilityLevelTrigger = this.page.locator('[data-testid="disability-level-select"]');
    await disabilityLevelTrigger.scrollIntoViewIfNeeded();
    await this.page.waitForTimeout(TIMEOUTS.VERY_SHORT);
    await disabilityLevelTrigger.click();
    await this.page.getByRole('option', { name: data.disabilityLevel }).click();
    console.debug('✓ 残疾等级已选择:', data.disabilityLevel);

    await form.getByLabel('联系电话 *').fill(data.phone);
    console.debug('✓ 联系电话已填写');

    await form.getByLabel('身份证地址 *').fill(data.idAddress);
    console.debug('✓ 身份证地址已填写');

    // 居住地址 - 省市区级联选择
    // AreaSelectForm 使用 data-testid="area-select-province" 等属性
    const provinceTrigger = this.page.locator('[data-testid="area-select-province"]');
    await provinceTrigger.scrollIntoViewIfNeeded();
    await provinceTrigger.click();
    await this.page.getByRole('option', { name: data.province }).click();
    console.debug('✓ 省份已选择:', data.province);

    const cityTrigger = this.page.locator('[data-testid="area-select-city"]');
    await cityTrigger.click();
    await this.page.getByRole('option', { name: data.city }).click();
    console.debug('✓ 城市已选择:', data.city);

    console.debug('表单填写完成');
  }

  async submitForm() {
    // 收集网络响应
    const responses: any[] = [];

    // 监听所有网络请求
    this.page.on('response', async (response) => {
      const url = response.url();
      if (url.includes('disabled-person') || url.includes('aggregated')) {
        const requestBody = response.request()?.postData();
        const responseBody = await response.text().catch(() => '');
        let jsonBody = null;
        try {
          jsonBody = JSON.parse(responseBody);
        } catch {
          // 不是 JSON
        }

        responses.push({
          url,
          method: response.request()?.method(),
          status: response.status(),
          ok: response.ok(),
          requestHeaders: await response.allHeaders().catch(() => ({})),
          responseHeaders: await response.allHeaders().catch(() => ({})),
          requestBody: requestBody ? JSON.parse(requestBody) : null,
          responseBody: jsonBody || responseBody,
          statusText: response.statusText()
        });
      }
    });

    // 点击创建按钮
    const submitButton = this.page.getByRole('button', { name: '创建' });
    await submitButton.click();

    // 等待网络请求完成（增加超时并添加容错处理）
    try {
      await this.page.waitForLoadState('networkidle', { timeout: TIMEOUTS.UPLOAD_LONG });
    } catch {
      // networkidle 可能因为长轮询或后台请求而失败，使用 domcontentloaded 作为降级方案
      console.debug('  ⚠ networkidle 超时，使用 domcontentloaded 作为降级方案');
      await this.page.waitForLoadState('domcontentloaded', { timeout: TIMEOUTS.TABLE_LOAD });
    }

    // 等待一段时间让 Toast 消息显示
    await this.page.waitForTimeout(TIMEOUTS.VERY_LONG);

    // 检查是否有错误提示
    const errorToast = this.page.locator('[data-sonner-toast][data-type="error"]');
    const successToast = this.page.locator('[data-sonner-toast][data-type="success"]');

    const hasError = await errorToast.count() > 0;
    const hasSuccess = await successToast.count() > 0;

    let errorMessage = null;
    let successMessage = null;

    if (hasError) {
      errorMessage = await errorToast.first().textContent();
    }
    if (hasSuccess) {
      successMessage = await successToast.first().textContent();
    }

    return {
      responses,
      hasError,
      hasSuccess,
      errorMessage,
      successMessage
    };
  }

  async searchByName(name: string) {
    await this.keywordSearchInput.fill(name);
    await this.searchButton.click();
    await this.page.waitForLoadState('networkidle');
    await this.page.waitForTimeout(TIMEOUTS.LONG);
  }

  async personExists(name: string): Promise<boolean> {
    const personRow = this.personTable.locator('tbody tr').filter({ hasText: name }).first();
    return (await personRow.count()) > 0;
  }

  /**
   * 等待人员记录出现（带重试机制，用于修复数据持久化稳定性问题）
   * @param name 残疾人姓名
   * @param options 选项
   * @returns 是否找到记录
   */
  async waitForPersonExists(name: string, options?: { timeout?: number; retries?: number }): Promise<boolean> {
    const timeout = options?.timeout ?? TIMEOUTS.TABLE_LOAD; // 默认 10 秒
    const startTime = Date.now();

    while (Date.now() - startTime < timeout) {
      // 重新搜索
      await this.searchByName(name);
      await this.page.waitForTimeout(TIMEOUTS.LONG); // 等待后检查

      const exists = await this.personExists(name);
      if (exists) {
        console.debug(`  ✓ 记录已出现: ${name}`);
        return true;
      }

      console.debug(`  ⏳ 等待记录出现: ${name} (${Math.floor((Date.now() - startTime) / 1000)}s)`);
    }

    console.debug(`  ✗ 记录未出现: ${name} (超时 ${timeout}ms)`);
    return false;
  }

  /**
   * 等待人员记录消失（带重试机制）
   * @param name 残疾人姓名
   * @param options 选项
   * @returns 记录是否已消失
   */
  async waitForPersonNotExists(name: string, options?: { timeout?: number }): Promise<boolean> {
    const timeout = options?.timeout ?? TIMEOUTS.TABLE_LOAD; // 默认 10 秒
    const startTime = Date.now();

    while (Date.now() - startTime < timeout) {
      await this.searchByName(name);
      await this.page.waitForTimeout(TIMEOUTS.LONG);

      const exists = await this.personExists(name);
      if (!exists) {
        console.debug(`  ✓ 记录已消失: ${name}`);
        return true;
      }

      console.debug(`  ⏳ 等待记录消失: ${name} (${Math.floor((Date.now() - startTime) / 1000)}s)`);
    }

    console.debug(`  ✗ 记录仍存在: ${name} (超时 ${timeout}ms)`);
    return false;
  }

  /**
   * 上传照片
   * @param photoType 照片类型（身份证照片、残疾证照片、个人照片、其他照片）
   * @param fileName 文件名
   */
  async uploadPhoto(photoType: string, fileName: string) {
    // 找到对应照片类型的上传按钮区域
    const photoSection = this.page.locator('text=' + photoType).first();
    await photoSection.scrollIntoViewIfNeeded();

    // 查找该类型照片区域的"上传"按钮
    const uploadButton = photoSection.locator('xpath=ancestor::div[contains(@class, "space-y-")]').first()
      .getByRole('button', { name: /上传/ }).first();

    // 创建测试文件
    const fileInput = await uploadButton.evaluateHandle((el: any) => {
      const input = el.querySelector('input[type="file"]');
      return input;
    });

    // 使用临时文件上传（类型转换以修复 TypeScript 错误）
    const file = {
      name: fileName,
      mimeType: 'image/jpeg',
      buffer: Buffer.from('fake image content')
    };

    // ElementHandle.uploadFile 在 Playwright 中可用，需要类型断言
    await (fileInput as any).uploadFile(file as any);
    await this.page.waitForTimeout(TIMEOUTS.MEDIUM); // 等待上传处理
    console.debug(`  ✓ 上传照片: ${photoType} - ${fileName}`);
  }

  /**
   * 添加银行卡（内联表单模式）
   * @param bankCard 银行卡信息
   */
  async addBankCard(bankCard: {
    bankName: string;
    subBankName: string;
    cardNumber: string;
    cardholderName: string;
    cardType?: string;
    isDefault?: boolean;
  }) {
    // 滚动到银行卡管理区域
    const bankCardLabel = this.page.getByText('银行卡管理');
    await bankCardLabel.scrollIntoViewIfNeeded();
    await this.page.waitForTimeout(TIMEOUTS.SHORT);

    // 获取当前银行卡数量
    const currentCardCount = await this.page.locator('[data-testid^="remove-bank-card-"]').count();

    // 点击"添加银行卡"按钮
    const addButton = this.page.locator('[data-testid="add-bank-card-button"]');
    await addButton.click();
    await this.page.waitForTimeout(TIMEOUTS.MEDIUM);

    // 等待新的银行卡卡片出现
    const newCardCount = await this.page.locator('[data-testid^="remove-bank-card-"]').count();
    if (newCardCount !== currentCardCount + 1) {
      throw new Error(`添加银行卡失败：预期 ${currentCardCount + 1} 张，实际 ${newCardCount} 张`);
    }

    // 新添加的银行卡索引
    const cardIndex = currentCardCount;

    // 1. 选择银行名称
    const bankSelectTrigger = this.page.locator(`[data-testid="bank-select-${cardIndex}"]`);
    await bankSelectTrigger.click();
    await this.page.waitForTimeout(TIMEOUTS.SHORT);
    await this.page.getByRole('option', { name: bankCard.bankName }).click();

    // 2. 填写发卡支行
    const subBankInput = this.page.locator(`[data-testid="sub-bank-name-input-${cardIndex}"]`);
    await subBankInput.fill(bankCard.subBankName);

    // 3. 填写银行卡号
    const cardNumberInput = this.page.locator(`[data-testid="card-number-input-${cardIndex}"]`);
    await cardNumberInput.fill(bankCard.cardNumber);

    // 4. 填写持卡人姓名
    const cardholderInput = this.page.locator(`[data-testid="cardholder-name-input-${cardIndex}"]`);
    await cardholderInput.fill(bankCard.cardholderName);

    // 5. 选择银行卡类型（可选）
    if (bankCard.cardType) {
      const cardTypeTrigger = this.page.locator(`[data-testid="card-type-select-${cardIndex}"]`);
      await cardTypeTrigger.click();
      await this.page.waitForTimeout(TIMEOUTS.SHORT);
      // 修复稳定性问题：等待选项出现后再点击（异步加载场景）
      await this.page.getByRole('option', { name: bankCard.cardType }).waitFor({ state: 'visible', timeout: TIMEOUTS.DIALOG });
      await this.page.getByRole('option', { name: bankCard.cardType }).click();
    }

    // 6. 设置默认银行卡（可选）
    if (bankCard.isDefault) {
      const defaultSwitch = this.page.locator(`[data-testid="default-card-switch-${cardIndex}"]`);
      const isChecked = await defaultSwitch.isChecked();
      if (!isChecked) {
        await defaultSwitch.click();
      }
    }

    console.debug(`  ✓ 添加银行卡: ${bankCard.bankName} - ${bankCard.cardNumber}`);
    return cardIndex;
  }

  /**
   * 编辑指定索引的银行卡
   * @param cardIndex 银行卡索引（从0开始）
   * @param updatedData 更新的银行卡数据
   */
  async editBankCard(cardIndex: number, updatedData: {
    bankName?: string;
    subBankName?: string;
    cardNumber?: string;
    cardholderName?: string;
    cardType?: string;
    isDefault?: boolean;
  }) {
    console.debug(`  编辑银行卡 ${cardIndex}`);

    // 编辑银行名称
    if (updatedData.bankName !== undefined) {
      const bankSelectTrigger = this.page.locator(`[data-testid="bank-select-${cardIndex}"]`);
      await bankSelectTrigger.click();
      await this.page.waitForTimeout(TIMEOUTS.SHORT);
      await this.page.getByRole('option', { name: updatedData.bankName }).click();
      console.debug(`  ✓ 更新银行名称: ${updatedData.bankName}`);
    }

    // 编辑发卡支行
    if (updatedData.subBankName !== undefined) {
      const subBankInput = this.page.locator(`[data-testid="sub-bank-name-input-${cardIndex}"]`);
      await subBankInput.clear();
      await subBankInput.fill(updatedData.subBankName);
      console.debug(`  ✓ 更新发卡支行: ${updatedData.subBankName}`);
    }

    // 编辑银行卡号
    if (updatedData.cardNumber !== undefined) {
      const cardNumberInput = this.page.locator(`[data-testid="card-number-input-${cardIndex}"]`);
      await cardNumberInput.clear();
      await cardNumberInput.fill(updatedData.cardNumber);
      console.debug(`  ✓ 更新银行卡号: ${updatedData.cardNumber}`);
    }

    // 编辑持卡人姓名
    if (updatedData.cardholderName !== undefined) {
      const cardholderInput = this.page.locator(`[data-testid="cardholder-name-input-${cardIndex}"]`);
      await cardholderInput.clear();
      await cardholderInput.fill(updatedData.cardholderName);
      console.debug(`  ✓ 更新持卡人姓名: ${updatedData.cardholderName}`);
    }

    // 编辑银行卡类型
    if (updatedData.cardType !== undefined) {
      const cardTypeTrigger = this.page.locator(`[data-testid="card-type-select-${cardIndex}"]`);
      await cardTypeTrigger.click();
      await this.page.waitForTimeout(TIMEOUTS.SHORT);
      // 修复稳定性问题：等待选项出现后再点击（异步加载场景）
      await this.page.getByRole('option', { name: updatedData.cardType }).waitFor({ state: 'visible', timeout: TIMEOUTS.DIALOG });
      await this.page.getByRole('option', { name: updatedData.cardType }).click();
      console.debug(`  ✓ 更新银行卡类型: ${updatedData.cardType}`);
    }

    // 设置默认银行卡
    if (updatedData.isDefault !== undefined) {
      const defaultSwitch = this.page.locator(`[data-testid="default-card-switch-${cardIndex}"]`);
      const isChecked = await defaultSwitch.isChecked();
      if (isChecked !== updatedData.isDefault) {
        await defaultSwitch.click();
        console.debug(`  ✓ 设置默认银行卡: ${updatedData.isDefault}`);
      }
    }

    console.debug(`  ✓ 银行卡 ${cardIndex} 编辑完成`);
  }

  /**
   * 删除指定索引的银行卡
   * @param cardIndex 银行卡索引（从0开始）
   */
  async deleteBankCard(cardIndex: number) {
    console.debug(`  删除银行卡 ${cardIndex}`);

    const removeButton = this.page.locator(`[data-testid="remove-bank-card-${cardIndex}"]`);
    await removeButton.click();
    await this.page.waitForTimeout(TIMEOUTS.MEDIUM);

    console.debug(`  ✓ 银行卡 ${cardIndex} 已删除`);
  }

  /**
   * 获取银行卡列表
   * @returns 银行卡号数组
   */
  async getBankCardList(): Promise<string[]> {
    const cards: string[] = [];
    const cardCount = await this.page.locator('[data-testid^="remove-bank-card-"]').count();

    for (let i = 0; i < cardCount; i++) {
      const cardNumberInput = this.page.locator(`[data-testid="card-number-input-${i}"]`);
      const cardNumber = await cardNumberInput.inputValue();
      cards.push(cardNumber);
    }

    return cards;
  }

  /**
   * 获取默认银行卡的索引
   * @returns 默认银行卡的索引，如果没有则返回 null
   */
  async getDefaultBankCardIndex(): Promise<number | null> {
    const cardCount = await this.page.locator('[data-testid^="remove-bank-card-"]').count();

    for (let i = 0; i < cardCount; i++) {
      const defaultSwitch = this.page.locator(`[data-testid="default-card-switch-${i}"]`);
      const isChecked = await defaultSwitch.isChecked();
      if (isChecked) {
        return i;
      }
    }

    return null;
  }

  /**
   * 获取当前银行卡数量
   * @returns 银行卡数量
   */
  async getBankCardCount(): Promise<number> {
    return await this.page.locator('[data-testid^="remove-bank-card-"]').count();
  }

  /**
   * 检查添加银行卡按钮是否被禁用
   * @returns 是否禁用
   */
  async isAddBankCardButtonDisabled(): Promise<boolean> {
    const addButton = this.page.locator('[data-testid="add-bank-card-button"]');
    return await addButton.isDisabled();
  }

  /**
   * 添加回访记录（内联表单模式）
   * @param visit 回访信息
   * @returns 添加的回访记录索引
   */
  async addVisit(visit: {
    visitDate: string;
    visitType: string;
    visitContent: string;
    visitResult?: string;
    nextVisitDate?: string;
  }): Promise<number> {
    // 获取当前回访数量
    const currentVisitCount = await this.getVisitCount();

    // 点击"添加回访"按钮
    const addButton = this.page.locator('[data-testid="add-visit-button"]');
    await addButton.click();
    await this.page.waitForTimeout(TIMEOUTS.SHORT);

    // 等待新的回访卡片出现
    const newVisitCount = await this.getVisitCount();
    if (newVisitCount !== currentVisitCount + 1) {
      throw new Error(`添加回访失败：预期 ${currentVisitCount + 1} 条，实际 ${newVisitCount} 条`);
    }

    // 新添加的回访索引
    const visitIndex = currentVisitCount;

    // 1. 填写回访日期
    const dateInput = this.page.locator(`[data-testid="visit-date-input-${visitIndex}"]`);
    await dateInput.fill(visit.visitDate);

    // 2. 选择回访类型
    const typeSelectTrigger = this.page.locator(`[data-testid="visit-type-select-${visitIndex}"]`);
    await typeSelectTrigger.click();
    await this.page.waitForTimeout(TIMEOUTS.VERY_SHORT);
    await this.page.getByRole('option', { name: visit.visitType }).click();

    // 3. 填写回访内容
    const contentTextarea = this.page.locator(`[data-testid="visit-content-textarea-${visitIndex}"]`);
    await contentTextarea.fill(visit.visitContent);

    // 4. 填写回访结果（可选）
    if (visit.visitResult !== undefined) {
      const resultInput = this.page.locator(`[data-testid="visit-result-input-${visitIndex}"]`);
      await resultInput.fill(visit.visitResult);
    }

    // 5. 填写下一次回访日期（可选）
    if (visit.nextVisitDate !== undefined) {
      const nextDateInput = this.page.locator(`[data-testid="next-visit-date-input-${visitIndex}"]`);
      await nextDateInput.fill(visit.nextVisitDate);
    }

    console.debug(`  ✓ 添加回访: ${visit.visitType} - ${visit.visitDate}`);
    return visitIndex;
  }

  /**
   * 编辑指定索引的回访记录
   * @param index 回访索引（从0开始）
   * @param updatedData 更新的回访数据
   */
  async editVisit(index: number, updatedData: {
    visitDate?: string;
    visitType?: string;
    visitContent?: string;
    visitResult?: string;
    nextVisitDate?: string;
  }): Promise<void> {
    console.debug(`  编辑回访 ${index}`);

    // 编辑回访日期
    if (updatedData.visitDate !== undefined) {
      const dateInput = this.page.locator(`[data-testid="visit-date-input-${index}"]`);
      await dateInput.clear();
      await dateInput.fill(updatedData.visitDate);
      console.debug(`  ✓ 更新回访日期: ${updatedData.visitDate}`);
    }

    // 编辑回访类型
    if (updatedData.visitType !== undefined) {
      const typeSelectTrigger = this.page.locator(`[data-testid="visit-type-select-${index}"]`);
      await typeSelectTrigger.click();
      await this.page.waitForTimeout(TIMEOUTS.VERY_SHORT);
      await this.page.getByRole('option', { name: updatedData.visitType }).click();
      console.debug(`  ✓ 更新回访类型: ${updatedData.visitType}`);
    }

    // 编辑回访内容
    if (updatedData.visitContent !== undefined) {
      const contentTextarea = this.page.locator(`[data-testid="visit-content-textarea-${index}"]`);
      await contentTextarea.clear();
      await contentTextarea.fill(updatedData.visitContent);
      console.debug(`  ✓ 更新回访内容`);
    }

    // 编辑回访结果
    if (updatedData.visitResult !== undefined) {
      const resultInput = this.page.locator(`[data-testid="visit-result-input-${index}"]`);
      await resultInput.clear();
      await resultInput.fill(updatedData.visitResult);
      console.debug(`  ✓ 更新回访结果`);
    }

    // 编辑下次回访日期
    if (updatedData.nextVisitDate !== undefined) {
      const nextDateInput = this.page.locator(`[data-testid="next-visit-date-input-${index}"]`);
      await nextDateInput.clear();
      await nextDateInput.fill(updatedData.nextVisitDate);
      console.debug(`  ✓ 更新下次回访日期`);
    }

    console.debug(`  ✓ 回访 ${index} 编辑完成`);
  }

  /**
   * 删除指定索引的回访记录
   * @param index 回访索引（从0开始）
   */
  async deleteVisit(index: number): Promise<void> {
    console.debug(`  删除回访 ${index}`);

    const removeButton = this.page.locator(`[data-testid="remove-visit-${index}"]`);
    await removeButton.click();
    await this.page.waitForTimeout(TIMEOUTS.SHORT);

    console.debug(`  ✓ 回访 ${index} 已删除`);
  }

  /**
   * 获取回访记录列表
   * @returns 回访信息数组
   */
  async getVisitList(): Promise<Array<{
    visitDate: string;
    visitType: string;
    visitContent: string;
    visitResult?: string;
    nextVisitDate?: string;
  }>> {
    const visits: Array<{
      visitDate: string;
      visitType: string;
      visitContent: string;
      visitResult?: string;
      nextVisitDate?: string;
    }> = [];
    const visitCount = await this.getVisitCount();

    for (let i = 0; i < visitCount; i++) {
      // 获取回访日期
      const dateInput = this.page.locator(`[data-testid="visit-date-input-${i}"]`);
      const visitDate = await dateInput.inputValue();

      // 获取回访类型
      const typeSelectTrigger = this.page.locator(`[data-testid="visit-type-select-${i}"]`);
      const visitType = await typeSelectTrigger.textContent() || '';

      // 获取回访内容
      const contentTextarea = this.page.locator(`[data-testid="visit-content-textarea-${i}"]`);
      const visitContent = await contentTextarea.inputValue();

      // 获取回访结果
      const resultInput = this.page.locator(`[data-testid="visit-result-input-${i}"]`);
      const visitResult = await resultInput.inputValue().catch(() => '');

      // 获取下次回访日期
      const nextDateInput = this.page.locator(`[data-testid="next-visit-date-input-${i}"]`);
      const nextVisitDate = await nextDateInput.inputValue().catch(() => '');

      visits.push({
        visitDate,
        visitType: visitType.trim(),
        visitContent,
        visitResult: visitResult || undefined,
        nextVisitDate: nextVisitDate || undefined,
      });
    }

    return visits;
  }

  /**
   * 获取当前回访记录数量
   * @returns 回访数量
   */
  async getVisitCount(): Promise<number> {
    return await this.page.locator('[data-testid^="remove-visit-"]').count();
  }

  /**
   * 检查添加回访按钮是否被禁用
   * @returns 是否禁用
   */
  async isAddVisitButtonDisabled(): Promise<boolean> {
    const addButton = this.page.locator('[data-testid="add-visit-button"]');
    return await addButton.isDisabled();
  }

  /**
   * 滚动表单到指定区域
   * @param sectionName 区域名称
   */
  async scrollToSection(sectionName: string) {
    const section = this.page.locator(`text=${sectionName}`).first();
    await section.scrollIntoViewIfNeeded();
    await this.page.waitForTimeout(TIMEOUTS.SHORT);
  }

  /**
   * 等待对话框关闭
   */
  async waitForDialogClosed() {
    const dialog = this.page.locator('[role="dialog"]');
    await dialog.waitFor({ state: 'hidden', timeout: TIMEOUTS.DIALOG }).catch(() => {});
    await this.page.waitForTimeout(TIMEOUTS.MEDIUM);
  }

  /**
   * 取消对话框
   */
  async cancelDialog() {
    const cancelButton = this.page.getByRole('button', { name: '取消' });
    await cancelButton.click();
    await this.waitForDialogClosed();
  }

  /**
   * 添加备注（内联表单模式）
   * @param content 备注内容
   * @param options 选项
   */
  async addNote(content: string, options?: { isSpecialNeeds?: boolean }): Promise<number> {
    // 点击"添加备注"按钮
    const addButton = this.page.locator('[data-testid="add-remark-button"]');
    await addButton.click();
    await this.page.waitForTimeout(TIMEOUTS.SHORT);

    // 获取当前备注数量
    const noteCount = await this.getNoteCount();
    const noteIndex = noteCount > 0 ? noteCount - 1 : 0;

    // 填写备注内容
    const textarea = this.page.locator(`[data-testid="remark-content-textarea-${noteIndex}"]`);
    await textarea.fill(content);

    // 标记特殊需求（如果需要）
    if (options?.isSpecialNeeds) {
      const switchControl = this.page.locator(`[data-testid="special-needs-switch-${noteIndex}"]`);
      const isChecked = await switchControl.isChecked();
      if (!isChecked) {
        await switchControl.click();
      }
    }

    console.debug(`  ✓ 添加备注: ${content.substring(0, 30)}...`);
    return noteIndex;
  }

  /**
   * 编辑指定索引的备注
   * @param index 备注索引（从0开始）
   * @param content 更新的备注内容
   */
  async editNote(index: number, content: string): Promise<void> {
    console.debug(`  编辑备注 ${index}`);

    const textarea = this.page.locator(`[data-testid="remark-content-textarea-${index}"]`);
    await textarea.clear();
    await textarea.fill(content);

    console.debug(`  ✓ 备注 ${index} 编辑完成`);
  }

  /**
   * 删除指定索引的备注
   * @param index 备注索引（从0开始）
   */
  async deleteNote(index: number): Promise<void> {
    console.debug(`  删除备注 ${index}`);

    const removeButton = this.page.locator(`[data-testid="remove-remark-${index}"]`);
    await removeButton.click();
    await this.page.waitForTimeout(TIMEOUTS.SHORT);

    console.debug(`  ✓ 备注 ${index} 已删除`);
  }

  /**
   * 获取备注列表
   * @returns 备注内容数组
   */
  async getNoteList(): Promise<string[]> {
    const notes: string[] = [];
    const noteCount = await this.page.locator('[data-testid^="remark-content-textarea-"]').count();

    for (let i = 0; i < noteCount; i++) {
      const textarea = this.page.locator(`[data-testid="remark-content-textarea-${i}"]`);
      const content = await textarea.inputValue();
      notes.push(content);
    }

    return notes;
  }

  /**
   * 获取备注数量
   * @returns 备注数量
   */
  async getNoteCount(): Promise<number> {
    return await this.page.locator('[data-testid^="remark-content-textarea-"]').count();
  }

  /**
   * 获取指定备注的特殊需求状态
   * @param index 备注索引（从0开始）
   * @returns 是否标记为特殊需求
   */
  async getNoteSpecialNeedsStatus(index: number): Promise<boolean> {
    const switchControl = this.page.locator(`[data-testid="special-needs-switch-${index}"]`);
    return await switchControl.isChecked();
  }

  /**
   * 检查添加备注按钮是否被禁用
   * @returns 是否禁用
   */
  async isAddNoteButtonDisabled(): Promise<boolean> {
    const addButton = this.page.locator('[data-testid="add-remark-button"]');
    return await addButton.isDisabled();
  }

  /**
   * 打开编辑对话框（通过姓名查找残疾人记录并点击编辑按钮）
   * @param name 残疾人姓名
   */
  async openEditDialog(name: string): Promise<void> {
    // 在列表中找到包含该姓名的行
    const row = this.personTable.locator('tbody tr').filter({ hasText: name }).first();

    // 等待行可见
    await row.waitFor({ state: 'visible', timeout: TIMEOUTS.DIALOG });

    // 点击该行的编辑按钮（使用 data-testid）
    // 需要先获取该行的 ID，因为 edit-person-{id} 按钮使用 ID
    const editButton = row.locator('[data-testid^="edit-person-"]').first();
    await editButton.click();

    // 等待编辑对话框出现
    await this.page.waitForSelector('[data-testid="edit-disabled-person-dialog-title"]', { state: 'visible', timeout: TIMEOUTS.DIALOG });

    console.debug(`✓ 打开编辑对话框: ${name}`);
  }

  /**
   * 打开详情对话框（通过姓名查找残疾人记录并点击查看按钮）
   * @param name 残疾人姓名
   */
  async openDetailDialog(name: string): Promise<void> {
    // 在列表中找到包含该姓名的行
    const row = this.personTable.locator('tbody tr').filter({ hasText: name }).first();

    // 等待行可见
    await row.waitFor({ state: 'visible', timeout: TIMEOUTS.DIALOG });

    // 点击该行的查看按钮（使用 data-testid）
    const viewButton = row.locator('[data-testid^="view-person-"]').first();
    await viewButton.click();

    // 等待详情对话框出现
    await this.page.waitForSelector('text=残疾人详情', { state: 'visible', timeout: TIMEOUTS.DIALOG });

    console.debug(`✓ 打开详情对话框: ${name}`);
  }

  /**
   * 删除残疾人记录（通过姓名查找并删除）
   * @param name 残疾人姓名
   */
  async deleteDisabilityPerson(name: string): Promise<void> {
    // 在列表中找到包含该姓名的行
    const row = this.personTable.locator('tbody tr').filter({ hasText: name }).first();

    // 等待行可见
    await row.waitFor({ state: 'visible', timeout: TIMEOUTS.DIALOG });

    // 点击该行的删除按钮
    const deleteButton = row.locator('[data-testid^="delete-person-"]').first();
    await deleteButton.click();

    // 等待删除确认对话框出现
    await this.page.waitForSelector('[data-testid="delete-confirmation-dialog-title"]', { state: 'visible', timeout: TIMEOUTS.ELEMENT_VISIBLE_SHORT });

    // 点击确认删除按钮
    const confirmButton = this.page.getByRole('button', { name: '确认删除' });
    await confirmButton.click();

    // 等待网络请求完成
    await this.page.waitForLoadState('networkidle', { timeout: TIMEOUTS.TABLE_LOAD });

    // 等待 Toast 提示
    await this.page.waitForTimeout(TIMEOUTS.VERY_LONG);

    console.debug(`✓ 删除残疾人记录: ${name}`);
  }

  /**
   * 获取列表中所有残疾人记录的数据
   * @returns 残疾人信息数组
   */
  async getListData(): Promise<Array<{
    name: string;
    idCard: string;
    disabilityType: string;
    disabilityLevel: string;
    phone: string;
    address: string;
  }>> {
    const rows = await this.personTable.locator('tbody tr').all();
    const data: Array<{
      name: string;
      idCard: string;
      disabilityType: string;
      disabilityLevel: string;
      phone: string;
      address: string;
    }> = [];

    for (const row of rows) {
      const cells = await row.locator('td').all();
      if (cells.length >= 6) {
        data.push({
          name: await cells[0].textContent() || '',
          idCard: await cells[2].textContent() || '',
          disabilityType: await cells[4].textContent() || '',
          disabilityLevel: await cells[5].textContent() || '',
          phone: await cells[6].textContent() || '',
          address: '',
        });
      }
    }

    return data;
  }

  /**
   * 获取当前列表记录数量
   * @returns 记录数量
   */
  async getListCount(): Promise<number> {
    return await this.personTable.locator('tbody tr').count();
  }

  /**
   * 按残疾类型筛选
   * @param disabilityType 残疾类型
   */
  async filterByDisabilityType(disabilityType: string): Promise<void> {
    const filterSelect = this.page.locator('[data-testid="disability-type-filter"]');
    await filterSelect.click();
    await this.page.getByRole('option', { name: disabilityType }).click();
    await this.page.waitForLoadState('networkidle');
    await this.page.waitForTimeout(TIMEOUTS.LONG);

    console.debug(`✓ 按残疾类型筛选: ${disabilityType}`);
  }

  /**
   * 重置筛选条件
   */
  async resetFilters(): Promise<void> {
    const resetButton = this.page.getByRole('button', { name: '重置筛选' });
    await resetButton.click();
    await this.page.waitForLoadState('networkidle');
    await this.page.waitForTimeout(TIMEOUTS.LONG);

    console.debug('✓ 已重置筛选条件');
  }

  /**
   * 等待详情对话框关闭
   */
  async waitForDetailDialogClosed(): Promise<void> {
    const dialog = this.page.locator('[role="dialog"]').filter({ hasText: '残疾人详情' });
    await dialog.waitFor({ state: 'hidden', timeout: TIMEOUTS.DIALOG }).catch(() => {});
    await this.page.waitForTimeout(TIMEOUTS.MEDIUM);
  }

  /**
   * 提交表单并保存（编辑模式通用方法）
   * @returns 提交结果
   */
  async submitAndSave(): Promise<{
    hasSuccess: boolean;
    hasError: boolean;
    errorMessage?: string;
    successMessage?: string;
  }> {
    // 点击更新按钮（编辑模式）
    const submitButton = this.page.getByRole('button', { name: '更新' });
    await submitButton.click();

    // 等待网络请求完成
    await this.page.waitForLoadState('networkidle', { timeout: TIMEOUTS.TABLE_LOAD }).catch(() => {});
    await this.page.waitForTimeout(TIMEOUTS.VERY_LONG);

    // 检查 Toast 消息
    const errorToast = this.page.locator('[data-sonner-toast][data-type="error"]');
    const successToast = this.page.locator('[data-sonner-toast][data-type="success"]');

    const hasError = await errorToast.count() > 0;
    const hasSuccess = await successToast.count() > 0;

    let errorMessage: string | null = null;
    let successMessage: string | null = null;

    if (hasError) {
      errorMessage = await errorToast.first().textContent();
    }
    if (hasSuccess) {
      successMessage = await successToast.first().textContent();
    }

    return {
      hasSuccess: hasSuccess || (!hasError && !hasSuccess),
      hasError,
      errorMessage: errorMessage ?? undefined,
      successMessage: successMessage ?? undefined,
    };
  }

  /**
   * 修改人员工作状态 (跨系统数据一致性验证)
   * @param isEmployed 是否在职 (true=已在职, false=未在职)
   * @returns 提交结果
   *
   * 注意：此方法需要在编辑对话框打开后调用
   */
  async updateWorkStatus(isEmployed: boolean): Promise<{
    hasSuccess: boolean;
    hasError: boolean;
    errorMessage?: string;
    successMessage?: string;
  }> {
    // 工作状态选择器：编辑表单使用原生 select 元素
    const jobStatusSelect = this.page.locator('select[name="jobStatus"]');
    await jobStatusSelect.waitFor({ state: 'visible', timeout: TIMEOUTS.ELEMENT_VISIBLE_SHORT });

    // 设置值：1=已在职, 0=未在职
    const value = isEmployed ? '1' : '0';
    await jobStatusSelect.selectOption(value);

    console.debug(`  ✓ 设置工作状态: ${isEmployed ? '已在职' : '未在职'}`);

    // 提交修改
    return await this.submitAndSave();
  }

  /**
   * 导出残疾人列表数据
   * @returns 下载事件（可用于验证下载）
   */
  async exportData(): Promise<{
    success: boolean;
    fileName?: string;
  }> {
    // 监听下载事件
    const downloadPromise = this.page.waitForEvent('download', { timeout: TIMEOUTS.TABLE_LOAD }).catch(() => null);

    // 点击导出按钮
    const exportButton = this.page.getByRole('button', { name: /导出|下载|Export/i }).first();
    const buttonExists = await exportButton.count() > 0;

    if (!buttonExists) {
      console.debug('⚠️ exportData: 未找到导出按钮');
      return { success: false };
    }

    await exportButton.click();

    // 等待下载开始
    const download = await downloadPromise;

    if (download) {
      const fileName = download.suggestedFilename();
      console.debug(`✓ exportData: 文件下载开始: ${fileName}`);
      return { success: true, fileName };
    }

    return { success: false };
  }
}
