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

/**
 * 群组管理数据服务
 */
@Injectable({
  providedIn: 'root'
})
export class GroupChatService {
  constructor(private adminData: AdminDataService) {}

  /**
   * 查询群组列表
   */
  async findGroupChats(options?: {
    keyword?: string;
    hasProject?: boolean;
    skip?: number;
    limit?: number;
  }): Promise<FmodeObject[]> {
    return await this.adminData.findAll('GroupChat', {
      include: ['project'],
      skip: options?.skip || 0,
      limit: options?.limit || 100,
      descending: 'createdAt',
      additionalQuery: query => {
        if (options?.keyword) {
          const kw = options.keyword.trim();
          if (kw) {
            query.matches('name', new RegExp(kw, 'i'));
          }
        }

        if (options?.hasProject !== undefined) {
          if (options.hasProject) {
            query.exists('project');
          } else {
            query.doesNotExist('project');
          }
        }
      }
    });
  }

  /**
   * 统计群组数量
   */
  async countGroupChats(): Promise<number> {
    return await this.adminData.count('GroupChat');
  }

  /**
   * 根据ID获取群组
   */
  async getGroupChat(objectId: string): Promise<FmodeObject | null> {
    return await this.adminData.getById('GroupChat', objectId, ['project']);
  }

  /**
   * 更新群组 (群组从企微同步,只能编辑部分字段)
   */
  async updateGroupChat(
    objectId: string,
    updates: {
      name?: string;
      projectId?: string | null;
      isDisabled?: boolean;
      data?: any;
    }
  ): Promise<FmodeObject | null> {
    const groupChat = await this.getGroupChat(objectId);
    if (!groupChat) {
      return null;
    }

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

    if (updates.projectId !== undefined) {
      if (updates.projectId) {
        groupChat.set('project', {
          __type: 'Pointer',
          className: 'Project',
          objectId: updates.projectId
        });
      } else {
        groupChat.unset('project');
      }
    }

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

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

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

  /**
   * 禁用/启用群组
   */
  async toggleGroupChat(objectId: string, isDisabled: boolean): Promise<boolean> {
    const groupChat = await this.getGroupChat(objectId);
    if (!groupChat) {
      return false;
    }

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

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

    // 处理项目关联
    if (json.project && typeof json.project === 'object') {
      json.projectTitle = json.project.title || '';
      json.projectId = json.project.objectId;
    }

    return json;
  }

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