import { Injectable } from '@angular/core';
import { AdminDataService } from './admin-data.service';
import { FmodeObject } from 'fmode-ng/core';

/**
 * 员工管理数据服务 (Profile表)
 */
@Injectable({
  providedIn: 'root'
})
export class EmployeeService {
  constructor(private adminData: AdminDataService) {}

  /**
   * 查询员工列表
   */
  async findEmployees(options?: {
    roleName?: string;
    departmentId?: string;
    keyword?: string;
    skip?: number;
    limit?: number;
  }): Promise<FmodeObject[]> {
    return await this.adminData.findAll('Profile', {
      include: ['department'],
      skip: options?.skip || 0,
      limit: options?.limit || 100,
      descending: 'createdAt',
      additionalQuery: query => {
        if (options?.roleName) {
          query.equalTo('roleName', options.roleName);
        }
        if (options?.departmentId) {
          query.equalTo('department', {
            __type: 'Pointer',
            className: 'Department',
            objectId: options.departmentId
          });
        }
        if (options?.keyword) {
          const kw = options.keyword.trim();
          if (kw) {
            query.matches('name', new RegExp(kw, 'i'));
          }
        }
      }
    });
  }

  /**
   * 统计员工数量
   */
  async countEmployees(roleName?: string): Promise<number> {
    return await this.adminData.count('Profile', query => {
      if (roleName) {
        query.equalTo('roleName', roleName);
      }
    });
  }

  /**
   * 根据ID获取员工
   */
  async getEmployee(objectId: string): Promise<FmodeObject | null> {
    return await this.adminData.getById('Profile', objectId, ['department']);
  }

  /**
   * 创建员工 (注意: 员工从企微同步，实际可能不需要创建功能)
   */
  async createEmployee(data: {
    name: string;
    mobile?: string;
    userId?: string;
    roleName: string;
    departmentId?: string;
    data?: any;
  }): Promise<FmodeObject> {
    const employeeData: any = {
      name: data.name,
      mobile: data.mobile || '',
      userId: data.userId || '',
      roleName: data.roleName
    };

    if (data.departmentId) {
      employeeData.department = {
        __type: 'Pointer',
        className: 'Department',
        objectId: data.departmentId
      };
    }

    if (data.data) {
      employeeData.data = data.data;
    }

    const employee = this.adminData.createObject('Profile', employeeData);
    return await this.adminData.save(employee);
  }

  /**
   * 更新员工
   */
  async updateEmployee(
    objectId: string,
    updates: {
      name?: string;
      mobile?: string;
      roleName?: string;
      departmentId?: string;
      isDisabled?: boolean;
      data?: any;
    }
  ): Promise<FmodeObject | null> {
    const employee = await this.getEmployee(objectId);
    if (!employee) {
      return null;
    }

    if (updates.name !== undefined) {
      employee.set('name', updates.name);
    }

    if (updates.mobile !== undefined) {
      employee.set('mobile', updates.mobile);
    }

    if (updates.roleName !== undefined) {
      employee.set('roleName', updates.roleName);
    }

    if (updates.departmentId !== undefined) {
      employee.set('department', {
        __type: 'Pointer',
        className: 'Department',
        objectId: updates.departmentId
      });
    }

    if (updates.isDisabled !== undefined) {
      employee.set('isDisabled', updates.isDisabled);
    }

    if (updates.data !== undefined) {
      const currentData = employee.get('data') || {};
      employee.set('data', { ...currentData, ...updates.data });
    }

    return await this.adminData.save(employee);
  }

  /**
   * 禁用/启用员工
   */
  async toggleEmployee(objectId: string, isDisabled: boolean): Promise<boolean> {
    const employee = await this.getEmployee(objectId);
    if (!employee) {
      return false;
    }

    employee.set('isDisabled', isDisabled);
    await this.adminData.save(employee);
    return true;
  }

  /**
   * 转换为JSON
   */
  toJSON(employee: FmodeObject): any {
    const json = this.adminData.toJSON(employee);

    // 处理部门关联
    if (json.department && typeof json.department === 'object') {
      json.departmentName = json.department.name || '';
      json.departmentId = json.department.objectId;
    }

    return json;
  }

  /**
   * 批量转换
   */
  toJSONArray(employees: FmodeObject[]): any[] {
    return employees.map(e => this.toJSON(e));
  }
}
