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, OrderPersonAsset } from '@d8d/allin-order-module/entities';
import { AssetType, AssetFileType } from '@d8d/allin-order-module/schemas';
import { OrderStatus, WorkStatus } from '@d8d/allin-order-module/schemas';
import { BankName } from '@d8d/bank-names-module';
import { DisabledPerson, DisabledBankCard, DisabledPhoto, DisabledRemark, DisabledVisit } from '../../src/entities';
import personExtensionRoutes from '../../src/routes/person-extension.route';
import { Company } from '@d8d/allin-company-module/entities';

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

describe('人才扩展API集成测试', () => {
  let client: ReturnType<typeof testClient<typeof personExtensionRoutes>>;
  let testToken: string;
  let testUser: UserEntity;
  let testCompany: Company;
  let testPlatform: Platform;
  let testDisabledPerson: DisabledPerson;
  let testOrder: EmploymentOrder;

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

    // 获取数据源
    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);

    // 创建测试企业用户
    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 }>);

    // 创建测试残疾人
    const disabledPersonRepo = dataSource.getRepository(DisabledPerson);
    testDisabledPerson = 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: '北京市',
      detailedAddress: '测试地址'
    });
    await disabledPersonRepo.save(testDisabledPerson);

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

    // 创建订单人员关联，使人员属于该企业
    const orderPersonRepo = dataSource.getRepository(OrderPerson);
    const orderPerson = orderPersonRepo.create({
      orderId: testOrder.id,
      personId: testDisabledPerson.id,
      joinDate: new Date('2024-01-01'),
      workStatus: WorkStatus.WORKING,
      salaryDetail: 5000.00
    });
    await orderPersonRepo.save(orderPerson);
  });

  describe('GET /api/v1/yongren/disability-person/{id}/work-history', () => {
    it('应该返回人员工作历史', async () => {
      // 准备测试数据：多个订单关联
      const dataSource = await IntegrationTestDatabase.getDataSource();
      const orderPersonRepo = dataSource.getRepository(OrderPerson);

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

      const anotherOrderPerson = orderPersonRepo.create({
        orderId: anotherOrder.id,
        personId: testDisabledPerson.id,
        joinDate: new Date('2024-06-01'),
        actualStartDate: new Date('2024-06-02'),
        leaveDate: new Date('2024-12-31'),
        workStatus: WorkStatus.RESIGNED,
        salaryDetail: 6000.00
      });
      await orderPersonRepo.save(anotherOrderPerson);

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

      console.debug('响应状态:', response.status);

      // 类型保护：如果状态不是200，抛出错误
      if (response.status !== 200) {
        try {
          const errorData = await response.json();
          console.debug('错误响应:', errorData);
          throw new Error(`API returned ${response.status}: ${errorData.message}`);
        } catch (e) {
          console.debug('无法解析错误响应:', e);
          throw new Error(`API returned ${response.status} and response could not be parsed`);
        }
      }

      const data = await response.json();

      // 验证响应结构
      expect(data).toHaveProperty('工作历史');
      expect(Array.isArray(data.工作历史)).toBe(true);

      // 验证数据
      expect(data.工作历史.length).toBeGreaterThanOrEqual(1);
      const workHistory = data.工作历史[0];
      expect(workHistory).toHaveProperty('订单ID');
      expect(workHistory).toHaveProperty('订单名称');
      expect(workHistory).toHaveProperty('入职日期');
      expect(workHistory).toHaveProperty('工作状态');
      expect(workHistory).toHaveProperty('个人薪资');
    });

    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 disabledPersonRepo = dataSource.getRepository(DisabledPerson);
      const otherDisabledPerson = disabledPersonRepo.create({
        name: '其他公司残疾人',
        idCard: `110101${Date.now() % 100000000 + 1000}`,
        gender: '女',
        birthDate: new Date('1995-01-01'),
        disabilityType: '听力残疾',
        disabilityLevel: '二级',
        disabilityId: `DIS${Date.now() % 100000000 + 1000}`,
        idAddress: '其他地址',
        phone: '13900139000',
        province: '上海市',
        city: '上海市',
        detailedAddress: '其他地址'
      });
      await disabledPersonRepo.save(otherDisabledPerson);

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

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

  describe('GET /api/v1/yongren/disability-person/{id}/salary-history', () => {
    it('应该返回人员薪资历史', async () => {
      // 注意：薪资历史可能需要从薪资模块获取，这里暂时返回空数组
      const response = await client[':id']['salary-history'].$get({
        param: { id: testDisabledPerson.id }
      },{
        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);
    });
  });

  describe('GET /api/v1/yongren/disability-person/{id}/credit-info', () => {
    it('应该返回人员征信信息', async () => {
      // 准备测试数据：银行卡信息
      const dataSource = await IntegrationTestDatabase.getDataSource();

      // 创建文件
      const fileRepository = dataSource.getRepository(File);
      const testFile = fileRepository.create({
        name: '银行卡照片.jpg',
        type: 'image/jpeg',
        size: 1024,
        path: 'uploads/bank-card.jpg',
        description: '银行卡照片',
        uploadUserId: testUser.id,
        uploadTime: new Date()
      });
      await fileRepository.save(testFile);

      // 创建银行名称记录
      const bankNameRepo = dataSource.getRepository(BankName);
      const bankName = bankNameRepo.create({
        name: '测试银行',
        code: 'TESTBANK',
        status: 1
      });
      await bankNameRepo.save(bankName);

      // 创建银行卡记录
      const bankCardRepo = dataSource.getRepository(DisabledBankCard);
      const bankCard = bankCardRepo.create({
        personId: testDisabledPerson.id,
        subBankName: '测试支行',
        bankNameId: bankName.id, // 使用实际创建的银行ID
        cardNumber: '6228481234567890123',
        cardholderName: '测试持卡人',
        cardType: '一类卡',
        fileId: testFile.id,
        isDefault: 1
      });
      await bankCardRepo.save(bankCard);

      // 调用API
      const response = await client[':id']['credit-info'].$get({
        param: { id: testDisabledPerson.id }
      },{
        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);

      if (data.征信信息.length > 0) {
        const creditInfo = data.征信信息[0];
        expect(creditInfo).toHaveProperty('文件ID');
        expect(creditInfo).toHaveProperty('银行卡号');
        expect(creditInfo).toHaveProperty('持卡人姓名');
      }
    });
  });

  describe('GET /api/v1/yongren/disability-person/{id}/videos', () => {
    it('应该返回人员视频关联', async () => {
      // 准备测试数据：订单人员资产（视频）
      const dataSource = await IntegrationTestDatabase.getDataSource();

      // 创建文件
      const fileRepository = dataSource.getRepository(File);
      const testFile = fileRepository.create({
        name: '工作视频.mp4',
        type: 'video/mp4',
        size: 1024000,
        path: 'uploads/work-video.mp4',
        description: '工作视频',
        uploadUserId: testUser.id,
        uploadTime: new Date()
      });
      await fileRepository.save(testFile);

      // 创建订单人员资产记录
      const assetRepo = dataSource.getRepository(OrderPersonAsset);
      const asset = assetRepo.create({
        orderId: testOrder.id,
        personId: testDisabledPerson.id,
        assetType: AssetType.WORK_VIDEO,
        assetFileType: AssetFileType.VIDEO,
        fileId: testFile.id,
        relatedTime: new Date()
      });
      await assetRepo.save(asset);

      // 调用API
      const response = await client[':id'].videos.$get({
        param: { id: testDisabledPerson.id }
      },{
        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);

      if (data.视频列表.length > 0) {
        const video = data.视频列表[0];
        expect(video).toHaveProperty('视频类型');
        expect(video).toHaveProperty('文件ID');
        expect(video).toHaveProperty('关联订单ID');
      }
    });
  });

  describe('GET /api/v1/yongren/disability-person (企业专用人才列表)', () => {
    it('应该返回企业人才列表', async () => {
      console.debug('测试token:', testToken);
      console.debug('测试用户companyId:', testUser.companyId);
      console.debug('测试公司ID:', testCompany.id);

      const response = await client.index.$get({
        query: {
          page: '1',
          limit: '10'
        }
      }, {
        headers: {
          Authorization: `Bearer ${testToken}`
        }
      });

      console.debug('响应状态:', response.status);
      if (response.status !== 200) {
        try {
          const errorData = await response.json();
          console.debug('错误响应:', errorData);
        } catch (e) {
          console.debug('无法解析错误响应:', e);
        }
      }

      expect(response.status).toBe(200);
      const data = await response.json() as { data: any[], pagination: any };

      // 验证响应结构
      expect(data).toHaveProperty('data');
      expect(data).toHaveProperty('pagination');
      expect(Array.isArray(data.data)).toBe(true);
      expect(data.pagination).toHaveProperty('page');
      expect(data.pagination).toHaveProperty('limit');
      expect(data.pagination).toHaveProperty('total');
      expect(data.pagination).toHaveProperty('totalPages');

      // 应该至少包含我们创建的人员
      if (data.data.length > 0) {
        const person = data.data[0];
        expect(person).toHaveProperty('personId');
        expect(person).toHaveProperty('name');
        expect(person).toHaveProperty('gender');
        expect(person).toHaveProperty('idCard');
        expect(person).toHaveProperty('disabilityType');
        expect(person).toHaveProperty('disabilityLevel');
        expect(person).toHaveProperty('phone');
        expect(person).toHaveProperty('jobStatus');
      }
    });

    it('应该支持搜索功能', async () => {
      const response = await client.index.$get({
        query: {
          search: '测试残疾人',
          page: '1',
          limit: '10'
        }
      }, {
        headers: {
          Authorization: `Bearer ${testToken}`
        }
      });

      expect(response.status).toBe(200);
      const data = await response.json() as { data: any[], pagination: any };
      expect(data.data.length).toBeGreaterThan(0);
    });

    it('应该支持残疾类型筛选', async () => {
      const response = await client.index.$get({
        query: {
          disabilityType: '视力残疾',
          page: '1',
          limit: '10'
        }
      }, {
        headers: {
          Authorization: `Bearer ${testToken}`
        }
      });

      expect(response.status).toBe(200);
      const data = await response.json() as { data: any[], pagination: any };
      // 可能匹配我们创建的人员
    });

    it('应该支持分页', async () => {
      const response = await client.index.$get({
        query: {
          page: '1',
          limit: '5'
        }
      }, {
        headers: {
          Authorization: `Bearer ${testToken}`
        }
      });

      expect(response.status).toBe(200);
      const data = await response.json() as { data: any[], pagination: any };
      expect(data.pagination.limit).toBe(5);
    });

    it('应该支持工作状态筛选（枚举值）', async () => {
      const response = await client.index.$get({
        query: {
          jobStatus: WorkStatus.WORKING,
          page: '1',
          limit: '10'
        }
      }, {
        headers: {
          Authorization: `Bearer ${testToken}`
        }
      });

      expect(response.status).toBe(200);
      const data = await response.json() as { data: any[], pagination: any };
      // 应该至少包含一个在职人员（我们创建的人员是在职状态）
    });

    it('应该支持工作状态筛选（中文标签）', async () => {
      const response = await client.index.$get({
        query: {
          jobStatus: '在职', // 中文标签
          page: '1',
          limit: '10'
        }
      }, {
        headers: {
          Authorization: `Bearer ${testToken}`
        }
      });

      expect(response.status).toBe(200);
      const data = await response.json() as { data: any[], pagination: any };
      // 验证返回的数据
    });

    it('其他企业用户不应该看到数据', async () => {
      // 创建另一个企业的用户
      const dataSource = await IntegrationTestDatabase.getDataSource();
      const companyRepository = dataSource.getRepository(Company);
      const otherCompany = companyRepository.create({
        companyName: `其他公司_${Date.now()}_2`,
        contactPerson: '其他联系人2',
        contactPhone: '13900139002',
        contactEmail: 'other2@example.com',
        address: '其他地址2',
        platformId: testPlatform.id,
        status: 1
      });
      await companyRepository.save(otherCompany);

      const userRepository = dataSource.getRepository(UserEntity);
      const otherUser = userRepository.create({
        username: `other_enterprise_user_${Date.now()}`,
        password: 'test_password',
        nickname: '其他企业用户',
        registrationSource: 'web',
        companyId: otherCompany.id
      });
      await userRepository.save(otherUser);

      // 生成其他企业用户的token
      const otherToken = JWTUtil.generateToken({
        id: otherUser.id,
        username: otherUser.username,
        roles: [{ name: 'enterprise_user' }]
      }, { companyId: otherCompany.id } as Partial<JWTPayload & { companyId: number }>);

      // 其他企业用户应该看不到任何数据（因为人员不属于他的企业）
      const response = await client.index.$get({
        query: {
          page: '1',
          limit: '10'
        }
      }, {
        headers: { Authorization: `Bearer ${otherToken}` }
      });

      expect(response.status).toBe(200);
      const data = await response.json() as { data: any[], pagination: any };
      // 可能返回空数组，因为人员不属于其他企业
    });
  });

  describe('GET /api/v1/yongren/disability-person/{id} (企业专用人才详情)', () => {
    it('应该返回企业人才详情', async () => {
      const response = await client[':id'].$get({
        param: { id: testDisabledPerson.id }
      }, {
        headers: {
          Authorization: `Bearer ${testToken}`
        }
      });

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

      // 验证响应结构
      expect(data).toHaveProperty('personId');
      expect(data).toHaveProperty('name');
      expect(data).toHaveProperty('gender');
      expect(data).toHaveProperty('idCard');
      expect(data).toHaveProperty('disabilityType');
      expect(data).toHaveProperty('disabilityLevel');
      expect(data).toHaveProperty('birthDate');
      expect(data).toHaveProperty('phone');
      expect(data).toHaveProperty('jobStatus');
      expect(data).toHaveProperty('bankCards');
      expect(data).toHaveProperty('photos');
      expect(Array.isArray(data.bankCards)).toBe(true);
      expect(Array.isArray(data.photos)).toBe(true);
    });

    it('访问其他企业人员应该返回404', async () => {
      // 创建另一个公司的残疾人
      const dataSource = await IntegrationTestDatabase.getDataSource();

      // 创建另一个公司
      const companyRepository = dataSource.getRepository(Company);
      const otherCompany = companyRepository.create({
        companyName: `其他公司_${Date.now()}_3`,
        contactPerson: '其他联系人3',
        contactPhone: '13900139003',
        contactEmail: 'other3@example.com',
        address: '其他地址3',
        platformId: testPlatform.id,
        status: 1
      });
      await companyRepository.save(otherCompany);

      // 创建另一个公司的残疾人（但不关联到当前企业）
      const disabledPersonRepo = dataSource.getRepository(DisabledPerson);
      const otherDisabledPerson = disabledPersonRepo.create({
        name: '其他公司残疾人详情测试',
        idCard: `110101${Date.now() % 100000000 + 2000}`,
        gender: '女',
        birthDate: new Date('1995-01-01'),
        disabilityType: '听力残疾',
        disabilityLevel: '二级',
        disabilityId: `DIS${Date.now() % 100000000 + 2000}`,
        idAddress: '其他地址',
        phone: '13900139003',
        province: '上海市',
        city: '上海市',
        detailedAddress: '其他地址'
      });
      await disabledPersonRepo.save(otherDisabledPerson);

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

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

    it('访问不存在的人员应该返回404', async () => {
      const nonExistentId = 999999;
      const response = await client[':id'].$get({
        param: { id: nonExistentId }
      }, {
        headers: {
          Authorization: `Bearer ${testToken}`
        }
      });

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