import { Injectable } from '@angular/core';
import { AdminDataService } from './admin-data.service';
import { FmodeObject, FmodeParse } from 'fmode-ng/core';
const Parse = FmodeParse.with("nova")

/**
 * 项目组(部门)管理数据服务
 */
@Injectable({
  providedIn: 'root'
})
export class DepartmentService {
  constructor(private adminData: AdminDataService) {}

  /**
   * 查询项目组列表
   */
  async findDepartments(options?: {
    type?: string;
    keyword?: string;
    skip?: number;
    limit?: number;
  }): Promise<FmodeObject[]> {
    return await this.adminData.findAll('Department', {
      include: ['leader'],
      skip: options?.skip || 0,
      limit: options?.limit || 100,
      descending: 'createdAt',
      additionalQuery: query => {
        // 默认只查询项目组类型
        query.equalTo('type', options?.type || 'project');

        if (options?.keyword) {
          const kw = options.keyword.trim();
          if (kw) {
            query.matches('name', new RegExp(kw, 'i'));
          }
        }
      }
    });
  }

  /**
   * 统计项目组数量
   */
  async countDepartments(type?: string): Promise<number> {
    return await this.adminData.count('Department', query => {
      query.equalTo('type', type || 'project');
    });
  }

  /**
   * 根据ID获取项目组
   */
  async getDepartment(objectId: string): Promise<FmodeObject | null> {
    return await this.adminData.getById('Department', objectId, ['leader']);
  }

  /**
   * 创建项目组
   */
  async createDepartment(data: {
    name: string;
    leaderId?: string;
    type?: string;
    data?: any;
  }): Promise<FmodeObject> {
    const deptData: any = {
      name: data.name,
      type: data.type || 'project'
    };

    // 设置组长指针
    if (data.leaderId) {
      deptData.leader = {
        __type: 'Pointer',
        className: 'Profile',
        objectId: data.leaderId
      };
    }

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

    const dept = this.adminData.createObject('Department', deptData);
    return await this.adminData.save(dept);
  }

  async saveProfileDepart(pid:string,did:string){
    let query = new Parse.Query("Profile");
    let profile = await query.get(pid);
    profile.set("department",{__type:"Pointer",className:"Department",objectId:did});
    profile.save();
  }
  /**
   * 更新项目组
   */
  async updateDepartment(
    objectId: string,
    updates: {
      name?: string;
      leaderId?: string;
      type?: string;
      data?: any;
    }
  ): Promise<FmodeObject | null> {
    const dept = await this.getDepartment(objectId);
    if (!dept) {
      return null;
    }

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

    if (updates.leaderId) {
      dept.set('leader', {
        __type: 'Pointer',
        className: 'Profile',
        objectId: updates.leaderId
      });
      this.saveProfileDepart(updates.leaderId,objectId)
    }

    if (updates.type !== undefined) {
      dept.set('type', updates.type);
    }

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

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

  /**
   * 删除项目组（软删除）
   */
  async deleteDepartment(objectId: string): Promise<boolean> {
    const dept = await this.getDepartment(objectId);
    if (!dept) {
      return false;
    }

    await this.adminData.softDelete(dept);
    return true;
  }

  /**
   * 获取项目组的成员列表
   */
  async getDepartmentMembers(departmentId: string): Promise<FmodeObject[]> {
    return await this.adminData.findAll('Profile', {
      additionalQuery: query => {
        query.equalTo('department', {
          __type: 'Pointer',
          className: 'Department',
          objectId: departmentId
        });
      }
    });
  }

  /**
   * 统计项目组成员数量
   */
  async countDepartmentMembers(departmentId: string): Promise<number> {
    return await this.adminData.count('Profile', query => {
      query.equalTo('department', {
        __type: 'Pointer',
        className: 'Department',
        objectId: departmentId
      });
    });
  }

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

    // 处理组长关联
    if (json.leader && typeof json.leader === 'object') {
      json.leaderName = json.leader.name || '';
      json.leaderId = json.leader.objectId;
    }

    return json;
  }

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