import { Injectable } from '@angular/core';
import { FmodeObject, FmodeParse, FmodeQuery } from 'fmode-ng/core';

/**
 * 管理系统数据服务基类
 * 提供统一的数据访问接口，所有数据操作都指向 cDL6R1hgSi 映三色帐套
 */
@Injectable({
  providedIn: 'root'
})
export class AdminDataService {
  private readonly COMPANY_ID = 'cDL6R1hgSi'; // 映三色帐套ID
  private Parse: any;

  constructor() {
    this.Parse = FmodeParse.with("nova")
  }

  /**
   * 获取公司指针
   */
  getCompanyPointer(): any {
    return {
      __type: 'Pointer',
      className: 'Company',
      objectId: this.COMPANY_ID
    };
  }

  /**
   * 创建查询并自动添加公司和非删除过滤
   */
  createQuery(className: string): FmodeQuery {
    const query = new this.Parse.Query(className);
    query.equalTo('company', this.getCompanyPointer());
    query.notEqualTo('isDeleted', true);
    return query;
  }

  /**
   * 创建新对象
   */
  createObject(className: string, data: any): FmodeObject {
    const obj = new this.Parse.Object(className);
    obj.set('company', this.getCompanyPointer());
    obj.set('isDeleted', false);

    // 设置其他字段
    Object.keys(data).forEach(key => {
      if (key !== 'company' && key !== 'isDeleted') {
        obj.set(key, data[key]);
      }
    });

    return obj;
  }

  /**
   * 软删除对象
   */
  async softDelete(obj: FmodeObject): Promise<FmodeObject> {
    obj.set('isDeleted', true);
    return await obj.save();
  }

  /**
   * 批量软删除
   */
  async softDeleteBatch(objects: FmodeObject[]): Promise<FmodeObject[]> {
    objects.forEach(obj => obj.set('isDeleted', true));
    return await this.Parse.Object.saveAll(objects);
  }

  /**
   * 查询统计数量
   */
  async count(className: string, additionalQuery?: (query: FmodeQuery) => void): Promise<number> {
    const query = this.createQuery(className);
    if (additionalQuery) {
      additionalQuery(query);
    }
    return await query.count();
  }

  /**
   * 查询列表
   */
  async findAll(
    className: string,
    options?: {
      include?: string[];
      limit?: number;
      skip?: number;
      descending?: string;
      ascending?: string;
      additionalQuery?: (query: FmodeQuery) => void;
    }
  ): Promise<FmodeObject[]> {
    const query = this.createQuery(className);

    if (options?.include) {
      options.include.forEach(field => query.include(field));
    }

    if (options?.limit) {
      query.limit(options.limit);
    }

    if (options?.skip) {
      query.skip(options.skip);
    }

    if (options?.descending) {
      query.descending(options.descending);
    }

    if (options?.ascending) {
      query.ascending(options.ascending);
    }

    if (options?.additionalQuery) {
      options.additionalQuery(query);
    }

    return await query.find();
  }

  /**
   * 根据ID获取对象
   */
  async getById(className: string, objectId: string, include?: string[]): Promise<FmodeObject | null> {
    try {
      const query = this.createQuery(className);
      if (include) {
        include.forEach(field => query.include(field));
      }
      return await query.get(objectId);
    } catch (error) {
      console.error(`获取${className} ${objectId}失败:`, error);
      return null;
    }
  }

  /**
   * 保存对象
   */
  async save(obj: FmodeObject): Promise<FmodeObject> {
    return await obj.save();
  }

  /**
   * 批量保存
   */
  async saveAll(objects: FmodeObject[]): Promise<FmodeObject[]> {
    return await this.Parse.Object.saveAll(objects);
  }

  /**
   * 将Parse对象转换为普通对象
   */
  toJSON(obj: FmodeObject): any {
    let json = obj.toJSON();
    return json;
  }

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