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

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

  /**
   * 查询客户列表
   */
  async findCustomers(options?: {
    keyword?: string;
    source?: string;
    skip?: number;
    limit?: number;
  }): Promise<FmodeObject[]> {
    return await this.adminData.findAll('ContactInfo', {
      skip: options?.skip || 0,
      limit: options?.limit || 50,
      descending: 'createdAt',
      additionalQuery: query => {
        if (options?.source) {
          query.equalTo('source', options.source);
        }
        if (options?.keyword) {
          const kw = options.keyword.trim();
          if (kw) {
            query.matches('name', new RegExp(kw, 'i'));
          }
        }
      }
    });
  }

  /**
   * 统计客户数量
   */
  async countCustomers(source?: string): Promise<number> {
    return await this.adminData.count('ContactInfo', query => {
      if (source) {
        query.equalTo('source', source);
      }
    });
  }

  /**
   * 根据ID获取客户
   */
  async getCustomer(objectId: string): Promise<FmodeObject | null> {
    return await this.adminData.getById('ContactInfo', objectId);
  }

  /**
   * 创建客户
   */
  async createCustomer(data: {
    name: string;
    mobile?: string;
    external_userid?: string;
    source?: string;
    data?: any;
  }): Promise<FmodeObject> {
    const customerData: any = {
      name: data.name,
      mobile: data.mobile || '',
      external_userid: data.external_userid || '',
      source: data.source || '其他'
    };

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

    const customer = this.adminData.createObject('ContactInfo', customerData);
    return await this.adminData.save(customer);
  }

  /**
   * 更新客户
   */
  async updateCustomer(
    objectId: string,
    updates: {
      name?: string;
      mobile?: string;
      source?: string;
      data?: any;
    }
  ): Promise<FmodeObject | null> {
    const customer = await this.getCustomer(objectId);
    if (!customer) {
      return null;
    }

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

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

    if (updates.source !== undefined) {
      customer.set('source', updates.source);
    }

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

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

  /**
   * 删除客户（软删除）
   */
  async deleteCustomer(objectId: string): Promise<boolean> {
    const customer = await this.getCustomer(objectId);
    if (!customer) {
      return false;
    }

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

  /**
   * 转换为JSON
   */
  toJSON(customer: FmodeObject): any {
    return this.adminData.toJSON(customer);
  }

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