import { TIMEOUTS } from '../../utils/timeouts';
import { test, expect } from '../../utils/test-setup';
import { readFileSync } from 'fs';
import { join, dirname } from 'path';
import { fileURLToPath } from 'url';
import { selectRadixOption } from '@d8d/e2e-test-utils';

const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
const testUsers = JSON.parse(readFileSync(join(__dirname, '../../fixtures/test-users.json'), 'utf-8'));

/**
 * 辅助函数：选择测试数据选项（用于状态筛选）
 * @param page Playwright Page 对象
 * @param selectTestId 选择器 testId
 * @param optionTestId 选项 testId
 */
async function selectTestOption(page: Parameters<typeof test>[0]['prototype'], selectTestId: string, optionTestId: string) {
  await page.getByTestId(selectTestId).click();
  await page.getByTestId(optionTestId).click();
}

/**
 * 辅助函数：应用筛选并等待结果
 * @param page Playwright Page 对象
 */
async function applyFilters(page: Parameters<typeof test>[0]['prototype']) {
  await page.getByTestId('search-button').click();
  // 使用合理的网络空闲等待，带超时处理
  await page.waitForLoadState('networkidle', { timeout: TIMEOUTS.DIALOG }).catch(() => {
    console.debug('筛选后没有网络请求或请求已完成');
  });
}

/**
 * 辅助函数：获取表格行数
 * @param page Playwright Page 对象
 * @returns 行数
 */
async function getTableRowCount(page: Parameters<typeof test>[0]['prototype']): Promise<number> {
  const tbody = page.locator('table tbody');
  const rows = tbody.locator('tr');
  return await rows.count();
}

/**
 * 辅助函数：格式化本地日期为 YYYY-MM-DD
 * @param date 日期对象
 * @returns 格式化的日期字符串
 */
function formatLocalDate(date: Date): string {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  return `${year}-${month}-${day}`;
}

test.describe.serial('订单搜索和筛选测试', () => {
  test.beforeEach(async ({ adminLoginPage, orderManagementPage }) => {
    // 以管理员身份登录后台
    await adminLoginPage.goto();
    await adminLoginPage.login(testUsers.admin.username, testUsers.admin.password);
    await adminLoginPage.expectLoginSuccess();
    await orderManagementPage.goto();
  });

  test.describe('订单名称搜索', () => {
    test('应该能按订单名称关键词搜索', async ({ orderManagementPage, page }) => {
      // 记录初始行数
      const initialCount = await getTableRowCount(page);
      console.debug(`初始订单列表有 ${initialCount} 行`);

      // 执行搜索
      await orderManagementPage.searchByName('测试');
      await applyFilters(page);

      // 验证搜索后表格仍然可见
      await expect(orderManagementPage.orderTable).toBeVisible();

      // 获取搜索后的行数并验证变化
      const searchCount = await getTableRowCount(page);
      console.debug(`搜索"测试"后订单列表有 ${searchCount} 行`);

      // 验证：搜索后行数应该小于或等于初始行数
      expect(searchCount).toBeLessThanOrEqual(initialCount);
    });

    test('应该能清空搜索条件', async ({ orderManagementPage, page }) => {
      // 记录初始行数
      const initialCount = await getTableRowCount(page);

      // 先执行搜索
      await orderManagementPage.searchByName('测试');
      await applyFilters(page);
      const searchCount = await getTableRowCount(page);

      // 清空搜索框
      await orderManagementPage.searchInput.clear();
      await orderManagementPage.searchButton.click();
      await applyFilters(page);

      // 验证表格仍然可见
      await expect(orderManagementPage.orderTable).toBeVisible();

      // 验证：清空后行数应该恢复到初始值（或接近）
      const clearedCount = await getTableRowCount(page);
      expect(clearedCount).toBeGreaterThanOrEqual(searchCount);
    });
  });

  test.describe('订单状态筛选', () => {
    test('应该能按草稿状态筛选', async ({ page }) => {
      const initialCount = await getTableRowCount(page);

      // 使用辅助函数选择选项
      await selectTestOption(page, 'filter-order-status-select', 'order-status-option-draft');
      await applyFilters(page);

      // 验证表格可见且行数变化
      await expect(page.locator('table')).toBeVisible();
      const filteredCount = await getTableRowCount(page);
      console.debug(`筛选草稿状态后订单列表有 ${filteredCount} 行`);
      expect(filteredCount).toBeLessThanOrEqual(initialCount);
    });

    test('应该能按已确认状态筛选', async ({ page }) => {
      const initialCount = await getTableRowCount(page);
      await selectTestOption(page, 'filter-order-status-select', 'order-status-option-confirmed');
      await applyFilters(page);

      await expect(page.locator('table')).toBeVisible();
      const filteredCount = await getTableRowCount(page);
      expect(filteredCount).toBeLessThanOrEqual(initialCount);
    });

    test('应该能按进行中状态筛选', async ({ page }) => {
      const initialCount = await getTableRowCount(page);
      await selectTestOption(page, 'filter-order-status-select', 'order-status-option-in-progress');
      await applyFilters(page);

      await expect(page.locator('table')).toBeVisible();
      const filteredCount = await getTableRowCount(page);
      expect(filteredCount).toBeLessThanOrEqual(initialCount);
    });

    test('应该能按已完成状态筛选', async ({ page }) => {
      const initialCount = await getTableRowCount(page);
      await selectTestOption(page, 'filter-order-status-select', 'order-status-option-completed');
      await applyFilters(page);

      await expect(page.locator('table')).toBeVisible();
      const filteredCount = await getTableRowCount(page);
      expect(filteredCount).toBeLessThanOrEqual(initialCount);
    });

    test('应该能选择全部状态', async ({ page }) => {
      const initialCount = await getTableRowCount(page);
      await selectTestOption(page, 'filter-order-status-select', 'order-status-option-all');
      await applyFilters(page);

      await expect(page.locator('table')).toBeVisible();
      // 选择全部状态应该显示所有订单
      const allCount = await getTableRowCount(page);
      expect(allCount).toBe(initialCount);
    });
  });

  test.describe('工作状态筛选', () => {
    test('应该能按未就业状态筛选', async ({ page }) => {
      const initialCount = await getTableRowCount(page);
      await selectTestOption(page, 'filter-work-status-select', 'work-status-option-not-working');
      await applyFilters(page);

      await expect(page.locator('table')).toBeVisible();
      const filteredCount = await getTableRowCount(page);
      expect(filteredCount).toBeLessThanOrEqual(initialCount);
    });

    test('应该能按待就业状态筛选', async ({ page }) => {
      const initialCount = await getTableRowCount(page);
      await selectTestOption(page, 'filter-work-status-select', 'work-status-option-pre-working');
      await applyFilters(page);

      await expect(page.locator('table')).toBeVisible();
      const filteredCount = await getTableRowCount(page);
      expect(filteredCount).toBeLessThanOrEqual(initialCount);
    });

    test('应该能按已就业状态筛选', async ({ page }) => {
      const initialCount = await getTableRowCount(page);
      await selectTestOption(page, 'filter-work-status-select', 'work-status-option-working');
      await applyFilters(page);

      await expect(page.locator('table')).toBeVisible();
      const filteredCount = await getTableRowCount(page);
      expect(filteredCount).toBeLessThanOrEqual(initialCount);
    });

    test('应该能按已离职状态筛选', async ({ page }) => {
      const initialCount = await getTableRowCount(page);
      await selectTestOption(page, 'filter-work-status-select', 'work-status-option-resigned');
      await applyFilters(page);

      await expect(page.locator('table')).toBeVisible();
      const filteredCount = await getTableRowCount(page);
      expect(filteredCount).toBeLessThanOrEqual(initialCount);
    });
  });

  test.describe('平台筛选', () => {
    test('应该能打开平台选择器', async ({ page }) => {
      const platformSelect = page.getByTestId('platform-search-select');
      await expect(platformSelect).toBeVisible();

      // 验证平台标签存在
      const platformLabel = page.locator('label').filter({ hasText: '平台' });
      await expect(platformLabel).toBeVisible();
    });

    test('应该能使用平台选择器筛选', async ({ page }) => {
      const initialCount = await getTableRowCount(page);
      const platformSelect = page.getByTestId('platform-search-select');
      await expect(platformSelect).toBeVisible();

      // 使用 selectRadixOption 工具（符合 AC 要求）
      try {
        await selectRadixOption(page, '平台', '58同城');
        await applyFilters(page);

        // 验证表格可见且行数变化
        await expect(page.locator('table')).toBeVisible();
        const filteredCount = await getTableRowCount(page);
        console.debug(`筛选平台后订单列表有 ${filteredCount} 行`);

        // 如果有该平台的数据，行数应该减少
        if (initialCount > 0) {
          expect(filteredCount).toBeLessThanOrEqual(initialCount);
        }
      } catch (error) {
        // 如果数据库中没有平台数据，记录并跳过验证
        console.debug('平台数据不存在或选择器无选项:', error);
      }
    });
  });

  test.describe('公司筛选', () => {
    test('应该能打开公司选择器', async ({ page }) => {
      const companySelect = page.getByTestId('company-search-select');
      await expect(companySelect).toBeVisible();

      const companyLabel = page.locator('label').filter({ hasText: '公司' });
      await expect(companyLabel).toBeVisible();
    });

    test('应该能使用公司选择器筛选', async ({ page }) => {
      const initialCount = await getTableRowCount(page);
      const companySelect = page.getByTestId('company-search-select');
      await expect(companySelect).toBeVisible();

      // 使用 selectRadixOption 工具
      try {
        await selectRadixOption(page, '公司', '测试公司');
        await applyFilters(page);

        await expect(page.locator('table')).toBeVisible();
        const filteredCount = await getTableRowCount(page);
        console.debug(`筛选公司后订单列表有 ${filteredCount} 行`);

        if (initialCount > 0) {
          expect(filteredCount).toBeLessThanOrEqual(initialCount);
        }
      } catch (error) {
        console.debug('公司数据不存在或选择器无选项:', error);
      }
    });
  });

  test.describe('渠道筛选', () => {
    test('应该能打开渠道选择器', async ({ page }) => {
      const channelSelect = page.getByTestId('channel-search-select');
      await expect(channelSelect).toBeVisible();

      const channelLabel = page.locator('label').filter({ hasText: '渠道' });
      await expect(channelLabel).toBeVisible();
    });

    test('应该能使用渠道选择器筛选', async ({ page }) => {
      const initialCount = await getTableRowCount(page);
      const channelSelect = page.getByTestId('channel-search-select');
      await expect(channelSelect).toBeVisible();

      // 使用 selectRadixOption 工具
      try {
        await selectRadixOption(page, '渠道', '网络招聘');
        await applyFilters(page);

        await expect(page.locator('table')).toBeVisible();
        const filteredCount = await getTableRowCount(page);
        console.debug(`筛选渠道后订单列表有 ${filteredCount} 行`);

        if (initialCount > 0) {
          expect(filteredCount).toBeLessThanOrEqual(initialCount);
        }
      } catch (error) {
        console.debug('渠道数据不存在或选择器无选项:', error);
      }
    });
  });

  test.describe('日期范围筛选', () => {
    test('应该能选择开始日期', async ({ page }) => {
      const startDateInput = page.getByTestId('start-date-input');
      await expect(startDateInput).toBeVisible();

      // 使用本地日期格式（修复 UTC 时区问题）
      const today = new Date();
      const startDate = formatLocalDate(today);
      await startDateInput.fill(startDate);

      await applyFilters(page);
      await expect(page.locator('table')).toBeVisible();
    });

    test('应该能选择结束日期', async ({ page }) => {
      const endDateInput = page.getByTestId('end-date-input');
      await expect(endDateInput).toBeVisible();

      const today = new Date();
      const endDate = formatLocalDate(today);
      await endDateInput.fill(endDate);

      await applyFilters(page);
      await expect(page.locator('table')).toBeVisible();
    });

    test('应该能选择日期范围进行筛选', async ({ page }) => {
      const initialCount = await getTableRowCount(page);
      const startDateInput = page.getByTestId('start-date-input');
      const endDateInput = page.getByTestId('end-date-input');

      // 设置日期范围（使用本地日期格式）
      const today = new Date();
      const startDate = new Date(today);
      startDate.setMonth(today.getMonth() - 1);
      const startDateStr = formatLocalDate(startDate);
      const endDateStr = formatLocalDate(today);

      await startDateInput.fill(startDateStr);
      await endDateInput.fill(endDateStr);
      await applyFilters(page);

      await expect(page.locator('table')).toBeVisible();
      const filteredCount = await getTableRowCount(page);
      console.debug(`日期范围筛选后订单列表有 ${filteredCount} 行`);

      // 验证筛选生效
      expect(filteredCount).toBeLessThanOrEqual(initialCount);
    });
  });

  test.describe('重置筛选', () => {
    test('应该能重置所有筛选条件', async ({ page }) => {
      // 先设置筛选条件
      await selectTestOption(page, 'filter-order-status-select', 'order-status-option-draft');
      await applyFilters(page);
      const filteredCount = await getTableRowCount(page);
      console.debug(`筛选后订单列表有 ${filteredCount} 行`);

      // 点击重置按钮
      const resetButton = page.getByTestId('reset-button');
      await expect(resetButton).toBeVisible();
      await resetButton.click();
      await applyFilters(page);

      // 验证表格可见
      await expect(page.locator('table')).toBeVisible();

      // 订单状态应该重置为"全部状态"
      const orderStatusValue = page.getByTestId('filter-order-status-select');
      await expect(orderStatusValue).toContainText('全部状态', { timeout: TIMEOUTS.DIALOG });
    });

    test('重置后应该显示全部订单', async ({ page }) => {
      // 记录初始状态
      const initialCount = await getTableRowCount(page);
      console.debug(`初始订单列表有 ${initialCount} 行`);

      // 先设置筛选条件
      await selectTestOption(page, 'filter-order-status-select', 'order-status-option-draft');
      await applyFilters(page);
      const filteredCount = await getTableRowCount(page);
      console.debug(`筛选后订单列表有 ${filteredCount} 行`);

      // 点击重置按钮
      const resetButton = page.getByTestId('reset-button');
      await resetButton.click();
      await applyFilters(page);

      // 验证列表可见且行数恢复
      await expect(page.locator('table')).toBeVisible();
      const resetCount = await getTableRowCount(page);
      console.debug(`重置后订单列表有 ${resetCount} 行`);

      // 重置后行数应该等于初始行数
      expect(resetCount).toBe(initialCount);
    });
  });

  test.describe('组合筛选测试', () => {
    test('应该能使用多个筛选条件组合', async ({ page }) => {
      const initialCount = await getTableRowCount(page);

      // 组合订单状态和工作状态筛选
      await selectTestOption(page, 'filter-order-status-select', 'order-status-option-draft');
      await selectTestOption(page, 'filter-work-status-select', 'work-status-option-not-working');
      await applyFilters(page);

      // 验证筛选结果
      await expect(page.locator('table')).toBeVisible();
      const filteredCount = await getTableRowCount(page);
      console.debug(`组合筛选后订单列表有 ${filteredCount} 行`);

      // 组合筛选应该进一步减少结果
      expect(filteredCount).toBeLessThanOrEqual(initialCount);
    });

    test('应该能使用日期范围和状态组合筛选', async ({ page }) => {
      const initialCount = await getTableRowCount(page);

      // 组合日期和状态筛选
      await selectTestOption(page, 'filter-order-status-select', 'order-status-option-confirmed');
      const startDateInput = page.getByTestId('start-date-input');
      const today = new Date();
      const startDate = new Date(today);
      startDate.setMonth(today.getMonth() - 1);
      await startDateInput.fill(formatLocalDate(startDate));
      await applyFilters(page);

      await expect(page.locator('table')).toBeVisible();
      const filteredCount = await getTableRowCount(page);
      console.debug(`日期+状态组合筛选后订单列表有 ${filteredCount} 行`);

      // 验证组合筛选生效
      expect(filteredCount).toBeLessThanOrEqual(initialCount);
    });
  });

  test.describe('搜索和筛选组合', () => {
    test('应该能同时使用搜索和筛选', async ({ orderManagementPage, page }) => {
      const initialCount = await getTableRowCount(page);

      // 先执行搜索
      await orderManagementPage.searchByName('测试');
      await applyFilters(page);
      const searchCount = await getTableRowCount(page);

      // 再添加筛选条件
      await selectTestOption(page, 'filter-order-status-select', 'order-status-option-draft');
      await applyFilters(page);

      // 验证组合结果
      await expect(page.locator('table')).toBeVisible();
      const combinedCount = await getTableRowCount(page);
      console.debug(`搜索+筛选后订单列表有 ${combinedCount} 行`);

      // 组合筛选应该进一步减少结果
      expect(combinedCount).toBeLessThanOrEqual(searchCount);
    });
  });

  test.describe('筛选条件可见性验证', () => {
    test('应该显示所有筛选条件', async ({ page }) => {
      // 验证所有筛选输入框都存在
      await expect(page.getByTestId('search-order-name-input')).toBeVisible();
      await expect(page.getByTestId('filter-order-status-select')).toBeVisible();
      await expect(page.getByTestId('filter-work-status-select')).toBeVisible();
      await expect(page.getByTestId('search-button')).toBeVisible();
      await expect(page.getByTestId('reset-button')).toBeVisible();
      await expect(page.getByTestId('platform-search-select')).toBeVisible();
      await expect(page.getByTestId('company-search-select')).toBeVisible();
      await expect(page.getByTestId('channel-search-select')).toBeVisible();
      await expect(page.getByTestId('start-date-input')).toBeVisible();
      await expect(page.getByTestId('end-date-input')).toBeVisible();
    });

    test('应该显示正确的筛选标签', async ({ page }) => {
      // 验证筛选标签正确显示（使用 locator 定位 label 元素避免与表头冲突）
      await expect(page.locator('label').filter({ hasText: '订单名称' })).toBeVisible();
      await expect(page.locator('label').filter({ hasText: '订单状态' })).toBeVisible();
      await expect(page.locator('label').filter({ hasText: '工作状态' })).toBeVisible();
      await expect(page.locator('label').filter({ hasText: '平台' })).toBeVisible();
      await expect(page.locator('label').filter({ hasText: '公司' })).toBeVisible();
      await expect(page.locator('label').filter({ hasText: '渠道' })).toBeVisible();
      await expect(page.locator('label').filter({ hasText: '开始日期' })).toBeVisible();
      await expect(page.locator('label').filter({ hasText: '结束日期' })).toBeVisible();
    });
  });
});
