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 companyRecentAllocationsRoutes from '../../src/routes/company-recent-allocations.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 companyRecentAllocationsRoutes>>;
  let testToken: string;
  let testUser: UserEntity;
  let testCompany: Company;
  let testPlatform: Platform;

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

    // 获取数据源
    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/allocations/recent', () => {
    it('应该返回近期分配人才列表（最近30天入职的在职人员）', 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);

      // 创建订单人员关联（近期入职：7天前）
      const orderPersonRepo = dataSource.getRepository(OrderPerson);
      const recentJoinDate = new Date();
      recentJoinDate.setDate(recentJoinDate.getDate() - 7);
      recentJoinDate.setHours(0, 0, 0, 0);

      const orderPerson = orderPersonRepo.create({
        orderId: order.id,
        personId: disabledPerson.id,
        joinDate: recentJoinDate,
        workStatus: WorkStatus.WORKING,
        salaryDetail: 5000.00
      });
      await orderPersonRepo.save(orderPerson);

      // 调用API
      const response = await client['allocations']['recent'].$get({
        query: {}
      },{
        headers: {
          Authorization: `Bearer ${testToken}`
        }
      });

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

      // 验证响应结构
      expect(data).toHaveProperty('人才列表');
      expect(Array.isArray(data.人才列表)).toBe(true);
      expect(data.人才列表.length).toBe(1);

      // 验证数据内容
      const talent = data.人才列表[0];
      expect(talent).toHaveProperty('personId', disabledPerson.id);
      expect(talent).toHaveProperty('personName', '测试残疾人');
      expect(talent).toHaveProperty('workStatus', 'working');
      expect(talent).toHaveProperty('orderName', '测试订单');
      expect(new Date(talent.joinDate).toISOString().split('T')[0]).toBe(recentJoinDate.toISOString().split('T')[0]);
    });

    it('应该支持limit参数控制返回记录数', async () => {
      // 准备测试数据：创建多个近期入职人员
      const dataSource = await IntegrationTestDatabase.getDataSource();
      const orderPersonRepo = dataSource.getRepository(OrderPerson);
      const disabledPersonRepo = dataSource.getRepository(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);

      // 创建5个近期入职的残疾人
      for (let i = 0; i < 5; i++) {
        const disabledPerson = 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(disabledPerson);

        const recentJoinDate = new Date();
        recentJoinDate.setDate(recentJoinDate.getDate() - i); // 不同的入职日期
        recentJoinDate.setHours(0, 0, 0, 0);

        const orderPerson = orderPersonRepo.create({
          orderId: order.id,
          personId: disabledPerson.id,
          joinDate: recentJoinDate,
          workStatus: WorkStatus.WORKING,
          salaryDetail: 5000.00 + i * 1000
        });
        await orderPersonRepo.save(orderPerson);
      }

      // 测试默认limit=5
      const response1 = await client['allocations']['recent'].$get({
        query: {}
      },{
        headers: {
          Authorization: `Bearer ${testToken}`
        }
      });
      expect(response1.status).toBe(200);
      const data1 = await response1.json() as any;
      expect(data1.人才列表.length).toBe(5);

      // 测试limit=2
      const response2 = await client['allocations']['recent'].$get({
        query: { limit: 2 }
      },{
        headers: {
          Authorization: `Bearer ${testToken}`
        }
      });
      expect(response2.status).toBe(200);
      const data2 = await response2.json() as any;
      expect(data2.人才列表.length).toBe(2);

      // 验证按join_date降序排列（最近入职的在前）
      expect(new Date(data2.人才列表[0].joinDate).getTime()).toBeGreaterThanOrEqual(new Date(data2.人才列表[1].joinDate).getTime());
    });

    it('应该只返回最近30天的数据', async () => {
      const dataSource = await IntegrationTestDatabase.getDataSource();
      const orderPersonRepo = dataSource.getRepository(OrderPerson);
      const disabledPersonRepo = dataSource.getRepository(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 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);

      // 创建近期入职记录（7天前）
      const recentJoinDate = new Date();
      recentJoinDate.setDate(recentJoinDate.getDate() - 7);
      const recentOrderPerson = orderPersonRepo.create({
        orderId: order.id,
        personId: disabledPerson.id,
        joinDate: recentJoinDate,
        workStatus: WorkStatus.WORKING,
        salaryDetail: 5000.00
      });
      await orderPersonRepo.save(recentOrderPerson);

      // 创建超过30天的入职记录（40天前）
      const oldJoinDate = new Date();
      oldJoinDate.setDate(oldJoinDate.getDate() - 40);
      const oldOrderPerson = orderPersonRepo.create({
        orderId: order.id,
        personId: disabledPerson.id,
        joinDate: oldJoinDate,
        workStatus: WorkStatus.WORKING,
        salaryDetail: 6000.00
      });
      await orderPersonRepo.save(oldOrderPerson);

      // 调用API
      const response = await client['allocations']['recent'].$get({
        query: {}
      },{
        headers: {
          Authorization: `Bearer ${testToken}`
        }
      });

      expect(response.status).toBe(200);
      const data = await response.json() as any;
      // 应该只返回1条记录（近期入职的）
      expect(data.人才列表.length).toBe(1);
      expect(new Date(data.人才列表[0].joinDate).toISOString().split('T')[0]).toBe(recentJoinDate.toISOString().split('T')[0]);
    });

    it('应该只返回在职人员（work_status = working）', async () => {
      const dataSource = await IntegrationTestDatabase.getDataSource();
      const orderPersonRepo = dataSource.getRepository(OrderPerson);
      const disabledPersonRepo = dataSource.getRepository(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 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 recentJoinDate = new Date();
      recentJoinDate.setDate(recentJoinDate.getDate() - 7);
      const workingOrderPerson = orderPersonRepo.create({
        orderId: order.id,
        personId: disabledPerson.id,
        joinDate: recentJoinDate,
        workStatus: WorkStatus.WORKING,
        salaryDetail: 5000.00
      });
      await orderPersonRepo.save(workingOrderPerson);

      // 创建离职记录
      const resignedOrderPerson = orderPersonRepo.create({
        orderId: order.id,
        personId: disabledPerson.id,
        joinDate: recentJoinDate,
        workStatus: WorkStatus.RESIGNED,
        salaryDetail: 6000.00
      });
      await orderPersonRepo.save(resignedOrderPerson);

      // 调用API
      const response = await client['allocations']['recent'].$get({
        query: {}
      },{
        headers: {
          Authorization: `Bearer ${testToken}`
        }
      });

      expect(response.status).toBe(200);
      const data = await response.json() as any;
      // 应该只返回1条记录（在职的）
      expect(data.人才列表.length).toBe(1);
      expect(data.人才列表[0].workStatus).toBe('working');
    });

    it('未认证用户应该返回401', async () => {
      const response = await client['allocations']['recent'].$get({
        query: {}
      });
      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['allocations']['recent'].$get({
        query: {}
      },{
        headers: {
          Authorization: `Bearer ${nonEnterpriseToken}`
        }
      });

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

    it('企业用户只能访问自己企业的数据', 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 disabledPersonRepo = dataSource.getRepository(DisabledPerson);
      const disabledPerson = disabledPersonRepo.create({
        name: '其他公司残疾人',
        idCard: `110101${Date.now() % 100000000 + 999}`,
        gender: '男',
        birthDate: new Date('1990-01-01'),
        disabilityType: '视力残疾',
        disabilityLevel: '一级',
        disabilityId: `DIS${Date.now() % 100000000 + 999}`,
        idAddress: '身份证地址',
        phone: '13800138999',
        province: '北京市',
        city: '北京市'
      });
      await disabledPersonRepo.save(disabledPerson);

      const orderRepo = dataSource.getRepository(EmploymentOrder);
      const otherOrder = orderRepo.create({
        orderName: '其他公司订单',
        platformId: testPlatform.id,
        companyId: otherCompany.id,
        orderStatus: OrderStatus.IN_PROGRESS,
        workStatus: WorkStatus.WORKING
      });
      await orderRepo.save(otherOrder);

      const orderPersonRepo = dataSource.getRepository(OrderPerson);
      const recentJoinDate = new Date();
      recentJoinDate.setDate(recentJoinDate.getDate() - 7);
      const orderPerson = orderPersonRepo.create({
        orderId: otherOrder.id,
        personId: disabledPerson.id,
        joinDate: recentJoinDate,
        workStatus: WorkStatus.WORKING,
        salaryDetail: 5000.00
      });
      await orderPersonRepo.save(orderPerson);

      // 调用API - 当前企业用户不应该看到其他公司的数据
      const response = await client['allocations']['recent'].$get({
        query: {}
      },{
        headers: {
          Authorization: `Bearer ${testToken}`
        }
      });

      expect(response.status).toBe(200);
      const data = await response.json() as any;
      // 应该返回空数组，因为当前企业没有近期入职人员
      expect(data.人才列表.length).toBe(0);
    });

    it('无效limit参数应该返回400', async () => {
      // 测试非数字limit
      const response1 = await client['allocations']['recent'].$get({
        query: { limit: 'invalid' }
      },{
        headers: {
          Authorization: `Bearer ${testToken}`
        }
      });
      expect(response1.status).toBe(400);

      // 测试负数limit
      const response2 = await client['allocations']['recent'].$get({
        query: { limit: -1 }
      },{
        headers: {
          Authorization: `Bearer ${testToken}`
        }
      });
      expect(response2.status).toBe(400);

      // 测试超过最大值的limit
      const response3 = await client['allocations']['recent'].$get({
        query: { limit: 200 }
      },{
        headers: {
          Authorization: `Bearer ${testToken}`
        }
      });
      expect(response3.status).toBe(400);
    });
  });
});