import { GenericCrudService } from '@d8d/shared-crud';
import { DataSource, Repository, Like, Not, MoreThanOrEqual } from 'typeorm';
import { EmploymentOrder, OrderPerson } from '@d8d/allin-order-module';
import { OrderStatus, WorkStatus } from '@d8d/allin-enums';
import { Company } from '../entities/company.entity';

export class CompanyService extends GenericCrudService<Company> {
  private searchFields = ['companyName', 'contactPerson', 'contactPhone'];

  constructor(dataSource: DataSource) {
    super(dataSource, Company);
  }

  /**
   * 创建公司 - 覆盖父类方法，添加公司名称在同一平台下唯一性检查
   */
  override async create(data: Partial<Company>, userId?: string | number): Promise<Company> {
    // 检查公司名称是否在同一平台下已存在
    if (data.companyName) {
      const whereCondition: any = { companyName: data.companyName };
      if (data.platformId !== undefined) {
        whereCondition.platformId = data.platformId;
      } else {
        whereCondition.platformId = null;
      }

      const existingCompany = await this.repository.findOne({
        where: whereCondition
      });
      if (existingCompany) {
        throw new Error('公司名称在该平台下已存在');
      }
    }

    // 设置默认值，过滤掉undefined值
    const companyData: Partial<Company> = {
      status: 1,
      createTime: new Date(),
      updateTime: new Date()
    };

    // 只复制非undefined的值
    for (const [key, value] of Object.entries(data)) {
      if (value !== undefined) {
        (companyData as any)[key] = value;
      }
    }

    return super.create(companyData, userId);
  }

  /**
   * 更新公司 - 覆盖父类方法，添加存在性和名称重复检查
   */
  override async update(id: number, data: Partial<Company>, userId?: string | number): Promise<Company | null> {
    // 检查公司是否存在
    const company = await this.repository.findOne({ where: { id } });
    if (!company) {
      throw new Error('公司不存在');
    }

    // 检查公司名称是否与同一平台下的其他公司重复
    const platformId = data.platformId !== undefined ? data.platformId : company.platformId;
    const companyName = data.companyName ?? company.companyName;

    if (companyName !== company.companyName || platformId !== company.platformId) {
      const whereCondition: any = {
        companyName,
        id: Not(id)
      };

      if (platformId !== undefined && platformId !== null) {
        whereCondition.platformId = platformId;
      } else {
        whereCondition.platformId = null;
      }

      const existingCompany = await this.repository.findOne({
        where: whereCondition
      });
      if (existingCompany) {
        throw new Error('公司名称在该平台下已存在');
      }
    }

    // 设置更新时间，过滤掉undefined值
    const updateData: Partial<Company> = {
      updateTime: new Date()
    };

    // 只复制非undefined的值
    for (const [key, value] of Object.entries(data)) {
      if (value !== undefined) {
        (updateData as any)[key] = value;
      }
    }

    return super.update(id, updateData, userId);
  }

  /**
   * 删除公司 - 覆盖父类方法，改为软删除（设置status为0）
   */
  override async delete(id: number, userId?: string | number): Promise<boolean> {
    // 改为软删除：设置status为0
    const result = await this.repository.update({ id }, { status: 0 });
    return result.affected === 1;
  }

  /**
   * 获取所有公司（分页） - 自定义方法，返回源服务的格式，加载平台关联
   */
  async findAll(skip?: number, take?: number): Promise<{ data: Company[], total: number }> {
    const [data, total] = await this.repository.findAndCount({
      relations: ['platform'],
      where: { status: 1 }, // 只返回正常状态的公司
      skip: skip ?? 0,
      take: take ?? 10,
      order: { id: 'DESC' }
    });
    return { data, total };
  }

  /**
   * 按名称搜索公司 - 自定义方法，加载平台关联
   */
  async searchByName(name: string, skip?: number, take?: number): Promise<{ data: Company[], total: number }> {
    const [data, total] = await this.repository.findAndCount({
      relations: ['platform'],
      where: {
        companyName: Like(`%${name}%`),
        status: 1 // 只返回正常状态的公司
      },
      skip: skip ?? 0,
      take: take ?? 10,
      order: { id: 'DESC' }
    });
    return { data, total };
  }

  /**
   * 按平台ID查询公司 - 自定义方法
   */
  async findByPlatform(platformId: number): Promise<Company[]> {
    return this.repository.find({
      where: { platformId }
    });
  }

  /**
   * 获取单个公司 - 自定义方法，加载平台关联
   */
  async findOne(id: number): Promise<Company | null> {
    return this.repository.findOne({
      where: { id },
      relations: ['platform']
    });
  }

  /**
   * 创建公司（兼容源服务API）- 返回布尔值
   */
  async createCompany(data: Partial<Company>): Promise<boolean> {
    try {
      await this.create(data);
      return true;
    } catch (error) {
      console.error('创建公司失败:', error);
      // 重新抛出错误，让路由层处理
      throw error;
    }
  }

  /**
   * 删除公司（兼容源服务API）- 返回布尔值
   */
  async deleteCompany(id: number): Promise<boolean> {
    try {
      return await this.delete(id);
    } catch (error) {
      console.error('删除公司失败:', error);
      return false;
    }
  }

  /**
   * 更新公司（兼容源服务API）- 返回布尔值
   */
  async updateCompany(data: Partial<Company> & { id: number }): Promise<boolean> {
    try {
      const { id, ...updateData } = data;
      await this.update(id, updateData);
      return true;
    } catch (error) {
      console.error('更新公司失败:', error);
      // 重新抛出错误，让路由层处理
      throw error;
    }
  }

  /**
   * 获取企业概览统计
   */
  async getCompanyOverview(companyId: number): Promise<any> {
    const employmentOrderRepo = this.dataSource.getRepository(EmploymentOrder);
    const orderPersonRepo = this.dataSource.getRepository(OrderPerson);

    // 查询在职人员数（order_person.work_status = 'working'）
    const workingCount = await orderPersonRepo.count({
      where: {
        workStatus: WorkStatus.WORKING,
        order: { companyId } // 通过关联查询
      }
    });

    // 查询进行中订单数（employment_order.order_status = 'in_progress'）
    const inProgressOrders = await employmentOrderRepo.count({
      where: {
        orderStatus: OrderStatus.IN_PROGRESS,
        companyId
      }
    });

    // 查询已完成订单数（employment_order.order_status = 'completed'）
    const completedOrders = await employmentOrderRepo.count({
      where: {
        orderStatus: OrderStatus.COMPLETED,
        companyId
      }
    });

    // 累计订单数
    const totalOrders = await employmentOrderRepo.count({
      where: { companyId }
    });

    return {
      在职人员数: workingCount,
      进行中订单数: inProgressOrders,
      已完成订单数: completedOrders,
      累计订单数: totalOrders
    };
  }

  /**
   * 获取企业维度人才统计
   */
  async getCompanyTalents(companyId: number): Promise<any> {
    const orderPersonRepo = this.dataSource.getRepository(OrderPerson);

    // 获取分配人才列表
    const talents = await orderPersonRepo.find({
      where: {
        order: { companyId }
      },
      relations: ['order', 'person'],
      order: { joinDate: 'DESC' }
    });

    // 统计状态分布
    const statusDistribution = {
      working: 0,
      on_leave: 0,
      left: 0
    };

    talents.forEach(talent => {
      if (talent.workStatus === WorkStatus.WORKING) {
        statusDistribution.working++;
      } else if (talent.workStatus === WorkStatus.RESIGNED) {
        statusDistribution.left++;
      } else {
        // 其他状态
      }
    });

    return {
      人才列表: talents.map(talent => ({
        personId: talent.personId,
        personName: talent.person?.name,
        joinDate: talent.joinDate || new Date(), // z.coerce.date()会自动转换
        workStatus: talent.workStatus,
        orderName: talent.order?.orderName
      })),
      状态分布: statusDistribution
    };
  }

  /**
   * 获取近期分配人才列表（最近30天入职的在职人员）
   */
  async getRecentAllocations(companyId: number, limit: number = 5): Promise<any> {
    const orderPersonRepo = this.dataSource.getRepository(OrderPerson);

    // 计算30天前的日期（时间设为00:00:00）
    const thirtyDaysAgo = new Date();
    thirtyDaysAgo.setDate(thirtyDaysAgo.getDate() - 30);
    thirtyDaysAgo.setHours(0, 0, 0, 0);

    // 获取近期分配人才列表
    const talents = await orderPersonRepo.find({
      where: {
        order: { companyId },
        workStatus: WorkStatus.WORKING,
        joinDate: MoreThanOrEqual(thirtyDaysAgo)
      },
      relations: ['order', 'person'],
      order: { joinDate: 'DESC' },
      take: limit
    });

    return {
      人才列表: talents.map(talent => ({
        personId: talent.personId,
        personName: talent.person?.name,
        joinDate: talent.joinDate || new Date(), // z.coerce.date()会自动转换
        workStatus: talent.workStatus,
        orderName: talent.order?.orderName
      }))
    };
  }
}