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 { JWTPayload } from '@d8d/shared-types';
import { UserEntity, Role } from '@d8d/user-module';
import { File } from '@d8d/file-module';
import { Platform } from '@d8d/allin-platform-module/entities';
import { EmploymentOrder, OrderPerson } from '@d8d/allin-order-module/entities';
import { DisabledPerson, DisabledBankCard, DisabledPhoto, DisabledRemark, DisabledVisit } from '@d8d/allin-disability-module/entities';
import { BankName } from '@d8d/bank-names-module';
import { OrderStatus, WorkStatus } from '@d8d/allin-enums';
import companyStatisticsRoutes from '../../src/routes/company-statistics.route';
import { Company } from '../../src/entities/company.entity';

// 设置集成测试钩子 - 需要包含所有相关实体
setupIntegrationDatabaseHooksWithEntities([
  UserEntity, File, Role, Platform, Company,
  EmploymentOrder, OrderPerson, DisabledPerson, BankName, DisabledBankCard, DisabledPhoto, DisabledRemark, DisabledVisit
])

describe('企业统计API集成测试', () => {
  let client: ReturnType<typeof testClient<typeof companyStatisticsRoutes>>;
  let testToken: string;
  let testUser: UserEntity;
  let testCompany: Company;
  let testPlatform: Platform;

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

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

    // 创建测试平台
    const platformRepository = dataSource.getRepository(Platform);
    testPlatform = platformRepository.create({
      platformName: `测试平台_${Date.now()}`,
      contactPerson: '平台管理员',
      contactPhone: '13800138000',
      contactEmail: 'admin@example.com',
      status: 1
    });
    await platformRepository.save(testPlatform);

    // 创建测试公司
    const companyRepository = dataSource.getRepository(Company);
    testCompany = companyRepository.create({
      companyName: `测试公司_${Date.now()}`,
      contactPerson: '公司联系人',
      contactPhone: '13900139000',
      contactEmail: 'company@example.com',
      address: '公司地址',
      platformId: testPlatform.id,
      status: 1
    });
    await companyRepository.save(testCompany);

    // 创建测试企业用户（有companyId）
    const userRepository = dataSource.getRepository(UserEntity);
    testUser = userRepository.create({
      username: `enterprise_user_${Date.now()}`,
      password: 'test_password',
      nickname: '企业测试用户',
      registrationSource: 'web',
      companyId: testCompany.id
    });
    await userRepository.save(testUser);

    // 生成测试用户的token
    testToken = JWTUtil.generateToken({
      id: testUser.id,
      username: testUser.username,
      roles: [{ name: 'enterprise_user' }]
    }, { companyId: testCompany.id } as Partial<JWTPayload & { companyId: number }>);
  });

  describe('GET /api/v1/yongren/company/overview', () => {
    it('应该返回企业概览统计', async () => {
      // 准备测试数据：创建订单和人员
      const dataSource = await IntegrationTestDatabase.getDataSource();

      // 创建残疾人
      const disabledPersonRepo = dataSource.getRepository(DisabledPerson);
      const disabledPerson = disabledPersonRepo.create({
        name: '测试残疾人',
        idCard: `110101${Date.now() % 100000000}`,
        gender: '男',
        birthDate: new Date('1990-01-01'),
        disabilityType: '视力残疾',
        disabilityLevel: '一级',
        disabilityId: `DIS${Date.now() % 100000000}`,
        idAddress: '身份证地址',
        phone: '13800138000',
        province: '北京市',
        city: '北京市'
      });
      await disabledPersonRepo.save(disabledPerson);

      // 创建订单
      const orderRepo = dataSource.getRepository(EmploymentOrder);
      const order = orderRepo.create({
        orderName: '测试订单',
        platformId: testPlatform.id,
        companyId: testCompany.id,
        orderStatus: OrderStatus.IN_PROGRESS,
        workStatus: WorkStatus.WORKING
      });
      await orderRepo.save(order);

      // 创建订单人员关联
      const orderPersonRepo = dataSource.getRepository(OrderPerson);
      const orderPerson = orderPersonRepo.create({
        orderId: order.id,
        personId: disabledPerson.id,
        joinDate: new Date('2024-01-01'),
        workStatus: WorkStatus.WORKING,
        salaryDetail: 5000.00
      });
      await orderPersonRepo.save(orderPerson);

      // 调用API
      const response = await client.overview.$get({},{
        headers: {
          Authorization: `Bearer ${testToken}`
        }
      });

      expect(response.status).toBe(200);
      const data = await response.json() as any;

      // 验证响应结构
      expect(data).toHaveProperty('在职人员数');
      expect(data).toHaveProperty('进行中订单数');
      expect(data).toHaveProperty('已完成订单数');
      expect(data).toHaveProperty('累计订单数');

      // 验证数据
      expect(data.在职人员数).toBe(1);
      expect(data.进行中订单数).toBe(1);
    });

    it('未认证用户应该返回401', async () => {
      const response = await client.overview.$get();
      expect(response.status).toBe(401);
    });

    it('非企业用户应该返回403', async () => {
      // 创建非企业用户
      const dataSource = await IntegrationTestDatabase.getDataSource();
      const userRepository = dataSource.getRepository(UserEntity);
      const nonEnterpriseUser = userRepository.create({
        username: `non_enterprise_${Date.now()}`,
        password: 'test_password',
        nickname: '非企业用户',
        registrationSource: 'web'
        // 没有companyId
      });
      await userRepository.save(nonEnterpriseUser);

      const nonEnterpriseToken = JWTUtil.generateToken({
        id: nonEnterpriseUser.id,
        username: nonEnterpriseUser.username,
        roles: [{ name: 'user' }]
      });

      const response = await client.overview.$get({},{
        headers: {
          Authorization: `Bearer ${nonEnterpriseToken}`
        }
      });

      expect(response.status).toBe(403);
    });
  });

  describe('GET /api/v1/yongren/company/{id}/talents', () => {
    it('应该返回企业维度人才统计', async () => {
      // 准备测试数据
      const dataSource = await IntegrationTestDatabase.getDataSource();

      // 创建多个残疾人
      const disabledPersonRepo = dataSource.getRepository(DisabledPerson);
      const disabledPersons = [];
      for (let i = 0; i < 3; i++) {
        const person = disabledPersonRepo.create({
          name: `测试残疾人${i}`,
          idCard: `110101${Date.now() % 100000000 + i}`,
          gender: i % 2 === 0 ? '男' : '女',
          birthDate: new Date('1990-01-01'),
          disabilityType: '视力残疾',
          disabilityLevel: '一级',
          disabilityId: `DIS${Date.now() % 100000000 + i}`,
          idAddress: '身份证地址',
          phone: `1380013800${i}`,
          province: '北京市',
          city: '北京市',
          });
        await disabledPersonRepo.save(person);
        disabledPersons.push(person);
      }

      // 创建订单
      const orderRepo = dataSource.getRepository(EmploymentOrder);
      const order = orderRepo.create({
        orderName: '测试订单',
        platformId: testPlatform.id,
        companyId: testCompany.id,
        orderStatus: OrderStatus.IN_PROGRESS,
        workStatus: WorkStatus.WORKING
      });
      await orderRepo.save(order);

      // 创建订单人员关联
      const orderPersonRepo = dataSource.getRepository(OrderPerson);
      for (let i = 0; i < disabledPersons.length; i++) {
        const person = disabledPersons[i];
        const orderPerson = orderPersonRepo.create({
          orderId: order.id,
          personId: person.id,
          joinDate: new Date('2024-01-01'),
          workStatus: i === 0 ? WorkStatus.WORKING : WorkStatus.RESIGNED, // 第一个在职，其他离职
          salaryDetail: 5000.00 + i * 1000
        });
        await orderPersonRepo.save(orderPerson);
      }

      // 调用API
      const response = await client[':id'].talents.$get({
        param: { id: testCompany.id }
      },{
        headers: {
          Authorization: `Bearer ${testToken}`
        }
      });

      console.debug('响应状态:', response.status);
      if (response.status !== 200) {
        const errorData = await response.json();
        console.debug('错误响应:', errorData);
      }

      expect(response.status).toBe(200);
      const data = await response.json() as any;

      // 验证响应结构
      expect(data).toHaveProperty('人才列表');
      expect(data).toHaveProperty('状态分布');
      expect(Array.isArray(data.人才列表)).toBe(true);

      // 验证状态分布
      expect(data.状态分布).toHaveProperty('working');
      expect(data.状态分布).toHaveProperty('on_leave');
      expect(data.状态分布).toHaveProperty('left');
    });

    it('访问其他企业数据应该返回403', async () => {
      // 创建另一个公司
      const dataSource = await IntegrationTestDatabase.getDataSource();
      const companyRepository = dataSource.getRepository(Company);
      const otherCompany = companyRepository.create({
        companyName: `其他公司_${Date.now()}`,
        contactPerson: '其他联系人',
        contactPhone: '13900139001',
        contactEmail: 'other@example.com',
        address: '其他地址',
        platformId: testPlatform.id,
        status: 1
      });
      await companyRepository.save(otherCompany);

      // 尝试访问其他公司数据
      const response = await client[':id'].talents.$get({
        param: { id: otherCompany.id }
      },{
        headers: {
          Authorization: `Bearer ${testToken}`
        }
      });

      expect(response.status).toBe(403);
    });
  });
});