import { describe, it, expect, beforeEach } from 'vitest';
import { testClient } from 'hono/testing';
import { IntegrationTestDatabase, setupIntegrationDatabaseHooksWithEntities } from '@d8d/shared-test-util';
import { JWTUtil } from '@d8d/shared-utils';
import { UserEntity, Role } from '@d8d/user-module';
import { File } from '@d8d/file-module';
import { DisabledPerson, DisabledBankCard, DisabledPhoto, DisabledRemark, DisabledVisit } from '@d8d/allin-disability-module';
import { BankName } from '@d8d/bank-names-module';
import { Company } from '@d8d/allin-company-module/entities';
import { Platform } from '@d8d/allin-platform-module';
import { DataSource } from 'typeorm';
import statisticsRoutes from '../../src/routes/statistics.routes';
import { EmploymentOrder, OrderPerson, OrderPersonAsset } from '@d8d/allin-order-module/entities';
import { AssetType, AssetFileType } from '@d8d/allin-order-module/schemas';
import { WorkStatus, OrderStatus } from '@d8d/allin-enums';

// 设置集成测试钩子
setupIntegrationDatabaseHooksWithEntities([
  UserEntity,
  File,
  Role,
  Platform,
  Company,
  DisabledPerson,
  DisabledBankCard,
  DisabledPhoto,
  DisabledRemark,
  DisabledVisit,
  BankName,
  EmploymentOrder,
  OrderPerson,
  OrderPersonAsset
])

describe('数据统计API集成测试', () => {
  let client: ReturnType<typeof testClient<typeof statisticsRoutes>>;
  let testToken: string;
  let testUser: UserEntity;
  let testCompany: Company;
  let testDisabledPerson: DisabledPerson;
  let testOrder: EmploymentOrder;
  let testOrderPerson: OrderPerson;
  let dataSource: DataSource;

  beforeEach(async () => {
    // 创建测试客户端
    client = testClient(statisticsRoutes);

    // 获取数据源
    dataSource = await IntegrationTestDatabase.getDataSource();

    // 创建测试用户
    const userRepository = dataSource.getRepository(UserEntity);
    testUser = userRepository.create({
      username: `test_user_${Date.now()}`,
      password: 'test_password',
      nickname: '测试用户',
      registrationSource: 'web'
    });
    await userRepository.save(testUser);

    // 生成测试用户的token
    testToken = JWTUtil.generateToken({
      id: testUser.id,
      username: testUser.username,
      roles: [{name:'user'}]
    });

    // 创建测试公司
    const companyRepository = dataSource.getRepository(Company);
    testCompany = companyRepository.create({
      companyName: '测试公司',
      contactPerson: '测试联系人',
      contactPhone: '13800138000',
      status: 1
    });
    await companyRepository.save(testCompany);

    // 创建测试文件
    const fileRepository = dataSource.getRepository(File);
    const testFile = fileRepository.create({
      name: 'test_file.pdf',
      type: 'application/pdf',
      size: 1024,
      path: `test/${Date.now()}_test_file.pdf`,
      uploadUserId: testUser.id,
      uploadTime: new Date(),
      createdAt: new Date(),
      updatedAt: new Date()
    });
    await fileRepository.save(testFile);

    // 创建测试银行名称记录
    const bankNameRepository = dataSource.getRepository(BankName);
    const testBankName = bankNameRepository.create({
      name: '测试银行',
      code: 'TEST001',
      remark: '测试银行',
      createdBy: testUser.id,
      updatedBy: testUser.id,
      status: 1
    });
    await bankNameRepository.save(testBankName);

    // 创建测试残疾人记录
    const disabledPersonRepository = dataSource.getRepository(DisabledPerson);
    testDisabledPerson = disabledPersonRepository.create({
      name: '测试残疾人',
      gender: '男',
      idCard: `tid_${Date.now() % 1000000}`,
      disabilityType: '视力残疾',
      disabilityLevel: '三级',
      province: '北京市',
      city: '北京市',
      jobStatus: 1,
      birthDate: new Date('1990-01-01'),
      idAddress: '测试地址',
      phone: '13800138000',
      canDirectContact: 1,
      disabilityId: `CJZ${Date.now() % 1000000}`
    });
    await disabledPersonRepository.save(testDisabledPerson);

    // 创建测试平台
    const platformRepository = dataSource.getRepository(Platform);
    const testPlatform = platformRepository.create({
      platformName: '测试平台',
      contactPerson: '测试联系人',
      contactPhone: '13800138000',
      status: 1
    });
    await platformRepository.save(testPlatform);

    // 创建测试订单
    const orderRepository = dataSource.getRepository(EmploymentOrder);
    testOrder = orderRepository.create({
      orderName: '测试订单',
      platformId: testPlatform.id,
      companyId: testCompany.id,
      channelId: 1,
      expectedStartDate: new Date(),
      orderStatus: OrderStatus.CONFIRMED,
      workStatus: WorkStatus.WORKING
    });
    await orderRepository.save(testOrder);

    // 创建测试订单人员
    const orderPersonRepository = dataSource.getRepository(OrderPerson);
    testOrderPerson = orderPersonRepository.create({
      orderId: testOrder.id,
      personId: testDisabledPerson.id,
      joinDate: new Date(),
      salaryDetail: 5000,
      workStatus: WorkStatus.WORKING
    });
    await orderPersonRepository.save(testOrderPerson);

    // 创建测试订单人员资产（打卡视频）
    const orderPersonAssetRepository = dataSource.getRepository(OrderPersonAsset);
    const testAsset = orderPersonAssetRepository.create({
      orderId: testOrder.id,
      personId: testDisabledPerson.id,
      assetType: AssetType.CHECKIN_VIDEO,
      assetFileType: AssetFileType.VIDEO,
      fileId: testFile.id,
      relatedTime: new Date()
    });
    await orderPersonAssetRepository.save(testAsset);
  });

  describe('GET /statistics/disability-type-distribution', () => {
    it('应该返回正确的残疾类型分布统计', async () => {
      // 测试实现待补充
      expect(true).toBe(true);
    });
  });

  describe('GET /statistics/gender-distribution', () => {
    it('应该返回正确的性别分布统计', async () => {
      // 测试实现待补充
      expect(true).toBe(true);
    });
  });

  describe('GET /statistics/age-distribution', () => {
    it('应该基于birth_date字段返回正确的年龄分布统计', async () => {
      // 测试实现待补充
      expect(true).toBe(true);
    });
  });

  describe('GET /statistics/household-distribution', () => {
    it('应该返回正确的户籍分布统计', async () => {
      // 测试实现待补充
      expect(true).toBe(true);
    });
  });

  describe('GET /statistics/job-status-distribution', () => {
    it('应该返回正确的在职状态分布统计', async () => {
      // 测试实现待补充
      expect(true).toBe(true);
    });
  });

  describe('GET /statistics/salary-distribution', () => {
    it('应该基于salary_detail字段返回正确的薪资分布统计', async () => {
      // 测试实现待补充
      expect(true).toBe(true);
    });
  });

  describe('企业数据隔离', () => {
    it('不同企业用户只能看到自己企业的统计', async () => {
      // 测试实现待补充
      expect(true).toBe(true);
    });
  });
});