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';

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

test.describe.serial('区域列表查看测试', () => {
  test.beforeEach(async ({ adminLoginPage, regionManagementPage }) => {
    // 以管理员身份登录后台
    await adminLoginPage.goto();
    await adminLoginPage.login(testUsers.admin.username, testUsers.admin.password);
    await adminLoginPage.expectLoginSuccess();
    await regionManagementPage.goto();
  });

  test.describe('页面加载验证', () => {
    test('应该显示区域列表页面标题', async ({ regionManagementPage }) => {
      await expect(regionManagementPage.pageTitle).toBeVisible();
      await expect(regionManagementPage.pageTitle).toContainText('省市区树形管理');
    });

    test('应该显示新增省按钮', async ({ regionManagementPage }) => {
      await expect(regionManagementPage.addProvinceButton).toBeVisible();
      await expect(regionManagementPage.addProvinceButton).toContainText('新增省');
    });

    test('应该等待树结构加载完成', async ({ regionManagementPage }) => {
      await regionManagementPage.waitForTreeLoaded();
      await expect(regionManagementPage.treeContainer).toBeVisible();
    });
  });

  test.describe('区域数据展示验证', () => {
    test('应该显示默认省份数据', async ({ regionManagementPage }) => {
      await regionManagementPage.waitForTreeLoaded();

      // 验证树形容器可见
      await expect(regionManagementPage.treeContainer).toBeVisible();

      // 验证树结构中包含至少一个省份
      const provinces = regionManagementPage.treeContainer.getByText(/^[\u4e00-\u9fa5]+省$/);
      const count = await provinces.count();
      expect(count).toBeGreaterThan(0);

      // 验证第一个省份名称存在
      const firstProvince = await provinces.first().textContent();
      expect(firstProvince).toBeTruthy();
      expect(firstProvince!.trim()).toMatch(/^[\u4e00-\u9fa5]+省$/);
    });

    test('应该能获取区域状态', async ({ regionManagementPage, page }) => {
      await regionManagementPage.waitForTreeLoaded();

      // 获取树中的第一个区域节点
      const firstRegion = regionManagementPage.treeContainer.getByText(/^[\u4e00-\u9fa5]+省$/).first();

      const count = await firstRegion.count();
      if (count > 0) {
        const regionName = await firstRegion.textContent();
        if (regionName) {
          const status = await regionManagementPage.getRegionStatus(regionName.trim());
          // 验证状态是有效的值（启用、禁用或null）
          expect(status === null || status === '启用' || status === '禁用').toBe(true);
        }
      }
    });

    test('应该能展开和收起区域节点', async ({ regionManagementPage }) => {
      await regionManagementPage.waitForTreeLoaded();

      // 查找一个有子节点的省份
      const province = regionManagementPage.treeContainer.getByText(/^[\u4e00-\u9fa5]+省$/).first();

      const count = await province.count();
      if (count > 0) {
        const provinceName = await province.textContent();
        if (provinceName) {
          const name = provinceName.trim();

          // 尝试展开节点
          await regionManagementPage.expandNode(name);
          console.debug(`已展开节点: ${name}`);

          // 等待一下让展开动画完成
          await regionManagementPage.page.waitForTimeout(TIMEOUTS.MEDIUM);

          // 尝试收起节点
          await regionManagementPage.collapseNode(name);
          console.debug(`已收起节点: ${name}`);
        }
      }
    });

    test('应该能检查区域是否存在', async ({ regionManagementPage }) => {
      await regionManagementPage.waitForTreeLoaded();

      // 测试检查不存在的区域
      const notExists = await regionManagementPage.regionExists('不存在的测试区域XYZ123');
      expect(notExists).toBe(false);

      // 获取树中的实际区域名称进行测试
      const firstRegion = regionManagementPage.treeContainer.getByText(/^[\u4e00-\u9fa5]+省$/).first();
      const count = await firstRegion.count();
      if (count > 0) {
        const regionName = await firstRegion.textContent();
        if (regionName) {
          // 测试检查存在的区域
          const exists = await regionManagementPage.regionExists(regionName.trim());
          expect(exists).toBe(true);
        }
      }
    });
  });

  test.describe('树形结构交互', () => {
    test('应该能连续展开多个省份', async ({ regionManagementPage }) => {
      await regionManagementPage.waitForTreeLoaded();

      // 获取所有省份
      const provinces = regionManagementPage.treeContainer.getByText(/^[\u4e00-\u9fa5]+省$/);
      const count = await provinces.count();

      if (count > 0) {
        // 最多展开前3个省份
        const maxExpand = Math.min(count, 3);
        for (let i = 0; i < maxExpand; i++) {
          const province = provinces.nth(i);
          const provinceName = await province.textContent();
          if (provinceName) {
            await regionManagementPage.expandNode(provinceName.trim());
            console.debug(`展开省份 ${i + 1}: ${provinceName}`);
            await regionManagementPage.page.waitForTimeout(TIMEOUTS.SHORT);
          }
        }
      }
    });

    test('页面刷新后树结构应该正常显示', async ({ regionManagementPage, page }) => {
      await regionManagementPage.waitForTreeLoaded();

      // 刷新页面
      await page.reload();
      await page.waitForLoadState('domcontentloaded');

      // 重新导航到区域管理页面
      await regionManagementPage.goto();

      // 验证树结构再次加载
      await regionManagementPage.waitForTreeLoaded();
      await expect(regionManagementPage.treeContainer).toBeVisible();
    });
  });

  test.describe('导航功能', () => {
    test('应该能从其他页面导航到区域管理', async ({ adminLoginPage, regionManagementPage, page }) => {
      // 先访问其他页面
      await page.goto('/admin/dashboard');
      await page.waitForLoadState('domcontentloaded');

      // 然后导航到区域管理页面
      await regionManagementPage.goto();

      // 验证页面正常加载
      await expect(regionManagementPage.pageTitle).toBeVisible();
      await expect(regionManagementPage.treeContainer).toBeVisible();
    });
  });

  test.describe('区域层级标识验证', () => {
    test('应该能验证省份层级标识', async ({ regionManagementPage }) => {
      await regionManagementPage.waitForTreeLoaded();

      // 验证省份存在（以"省"结尾）
      const provinces = regionManagementPage.treeContainer.getByText(/^[\u4e00-\u9fa5]+省$/);
      const count = await provinces.count();
      expect(count).toBeGreaterThan(0);
      console.debug(`找到 ${count} 个省份`);
    });

    test('应该能展开省份并验证市级子节点', async ({ regionManagementPage }) => {
      await regionManagementPage.waitForTreeLoaded();

      // 查找第一个省份
      const province = regionManagementPage.treeContainer.getByText(/^[\u4e00-\u9fa5]+省$/).first();
      const provinceCount = await province.count();

      if (provinceCount > 0) {
        const provinceName = await province.textContent();
        if (provinceName) {
          // 展开省份
          await regionManagementPage.expandNode(provinceName.trim());
          await regionManagementPage.page.waitForTimeout(TIMEOUTS.MEDIUM);

          // 验证市级子节点存在（以"市"结尾）
          const cities = regionManagementPage.treeContainer.getByText(/^[\u4e00-\u9fa5]+市$/);
          const cityCount = await cities.count();
          console.debug(`展开 ${provinceName.trim()} 后找到 ${cityCount} 个市`);

          // 验证至少有一个市（如果省份有子节点）
          if (cityCount > 0) {
            const firstCity = await cities.first().textContent();
            expect(firstCity).toBeTruthy();
            expect(firstCity!.trim()).toMatch(/^[\u4e00-\u9fa5]+市$/);
          }
        }
      }
    });

    test('应该能展开市并验证区级子节点', async ({ regionManagementPage }) => {
      await regionManagementPage.waitForTreeLoaded();

      // 查找第一个省份并展开
      const province = regionManagementPage.treeContainer.getByText(/^[\u4e00-\u9fa5]+省$/).first();
      const provinceCount = await province.count();

      if (provinceCount > 0) {
        const provinceName = await province.textContent();
        if (provinceName) {
          await regionManagementPage.expandNode(provinceName.trim());
          await regionManagementPage.page.waitForTimeout(TIMEOUTS.MEDIUM);

          // 查找第一个市并展开
          const city = regionManagementPage.treeContainer.getByText(/^[\u4e00-\u9fa5]+市$/).first();
          const cityCount = await city.count();

          if (cityCount > 0) {
            const cityName = await city.textContent();
            if (cityName) {
              await regionManagementPage.expandNode(cityName.trim());
              await regionManagementPage.page.waitForTimeout(TIMEOUTS.MEDIUM);

              // 验证区级子节点存在（以"区"或"县"结尾）
              const districts = regionManagementPage.treeContainer.getByText(/^[\u4e00-\u9fa5]+(区|县)$/);
              const districtCount = await districts.count();
              console.debug(`展开 ${cityName.trim()} 后找到 ${districtCount} 个区/县`);

              if (districtCount > 0) {
                const firstDistrict = await districts.first().textContent();
                expect(firstDistrict).toBeTruthy();
              }
            }
          }
        }
      }
    });
  });
});
