import { invoke } from '@tauri-apps/api/core';
import {
  CustomTagCategory,
  CustomTag,
  CustomTagWithCategory,
  TagAssociation,
  TagStatistics,
  CreateCustomTagCategoryRequest,
  UpdateCustomTagCategoryRequest,
  CreateCustomTagRequest,
  UpdateCustomTagRequest,
  TagFilter,
  EntityType,
} from '../types/customTag';

/**
 * 自定义标签服务
 * 遵循 Tauri 开发规范的服务层设计
 */
export class CustomTagService {
  // 标签分类管理
  
  /**
   * 获取所有标签分类
   */
  static async getCategories(activeOnly: boolean = true): Promise<CustomTagCategory[]> {
    return invoke('get_custom_tag_categories', { activeOnly });
  }

  /**
   * 创建标签分类
   */
  static async createCategory(request: CreateCustomTagCategoryRequest): Promise<CustomTagCategory> {
    return invoke('create_custom_tag_category', { request });
  }

  /**
   * 更新标签分类
   */
  static async updateCategory(
    id: string,
    request: UpdateCustomTagCategoryRequest
  ): Promise<CustomTagCategory | null> {
    return invoke('update_custom_tag_category', { id, request });
  }

  /**
   * 删除标签分类
   */
  static async deleteCategory(id: string): Promise<boolean> {
    return invoke('delete_custom_tag_category', { id });
  }

  // 标签管理

  /**
   * 获取标签列表
   */
  static async getTags(filter?: TagFilter): Promise<CustomTagWithCategory[]> {
    return invoke('get_custom_tags', { filter });
  }

  /**
   * 创建标签
   */
  static async createTag(request: CreateCustomTagRequest): Promise<CustomTag> {
    return invoke('create_custom_tag', { request });
  }

  /**
   * 更新标签
   */
  static async updateTag(id: string, request: UpdateCustomTagRequest): Promise<CustomTag | null> {
    return invoke('update_custom_tag', { id, request });
  }

  /**
   * 删除标签
   */
  static async deleteTag(id: string): Promise<boolean> {
    return invoke('delete_custom_tag', { id });
  }

  // 标签关联管理

  /**
   * 为实体添加标签
   */
  static async addEntityTag(
    tagId: string,
    entityType: EntityType,
    entityId: string
  ): Promise<TagAssociation> {
    return invoke('add_entity_tag', {
      tagId,
      entityType: entityType.toString(),
      entityId,
    });
  }

  /**
   * 移除实体标签
   */
  static async removeEntityTag(
    tagId: string,
    entityType: EntityType,
    entityId: string
  ): Promise<boolean> {
    return invoke('remove_entity_tag', {
      tagId,
      entityType: entityType.toString(),
      entityId,
    });
  }

  /**
   * 获取实体的标签
   */
  static async getEntityTags(
    entityType: EntityType,
    entityId: string
  ): Promise<CustomTagWithCategory[]> {
    return invoke('get_entity_tags', {
      entityType: entityType.toString(),
      entityId,
    });
  }

  /**
   * 批量为实体添加标签
   */
  static async batchAddEntityTags(
    tagIds: string[],
    entityType: EntityType,
    entityId: string
  ): Promise<TagAssociation[]> {
    return invoke('batch_add_entity_tags', {
      tagIds,
      entityType: entityType.toString(),
      entityId,
    });
  }

  /**
   * 批量移除实体标签
   */
  static async batchRemoveEntityTags(
    tagIds: string[],
    entityType: EntityType,
    entityId: string
  ): Promise<number> {
    return invoke('batch_remove_entity_tags', {
      tagIds,
      entityType: entityType.toString(),
      entityId,
    });
  }

  // 统计信息

  /**
   * 获取标签统计信息
   */
  static async getStatistics(): Promise<TagStatistics> {
    return invoke('get_tag_statistics');
  }

  // 便捷方法

  /**
   * 根据分类获取标签
   */
  static async getTagsByCategory(categoryId: string): Promise<CustomTagWithCategory[]> {
    return this.getTags({
      category_ids: [categoryId],
      active_only: true,
    });
  }

  /**
   * 搜索标签
   */
  static async searchTags(query: string): Promise<CustomTagWithCategory[]> {
    return this.getTags({
      name_search: query,
      active_only: true,
    });
  }

  /**
   * 获取热门标签（按使用次数排序）
   */
  static async getPopularTags(limit: number = 10): Promise<CustomTagWithCategory[]> {
    const allTags = await this.getTags({ active_only: true });
    return allTags
      .sort((a, b) => b.tag.usage_count - a.tag.usage_count)
      .slice(0, limit);
  }

  /**
   * 获取最近创建的标签
   */
  static async getRecentTags(limit: number = 10): Promise<CustomTagWithCategory[]> {
    const allTags = await this.getTags({ active_only: true });
    return allTags
      .sort((a, b) => new Date(b.tag.created_at).getTime() - new Date(a.tag.created_at).getTime())
      .slice(0, limit);
  }

  /**
   * 检查标签名称是否已存在
   */
  static async isTagNameExists(name: string, categoryId: string, excludeId?: string): Promise<boolean> {
    const tags = await this.getTagsByCategory(categoryId);
    return tags.some(tag => 
      tag.tag.name.toLowerCase() === name.toLowerCase() && 
      tag.tag.id !== excludeId
    );
  }

  /**
   * 检查分类名称是否已存在
   */
  static async isCategoryNameExists(name: string, excludeId?: string): Promise<boolean> {
    const categories = await this.getCategories(false);
    return categories.some(category => 
      category.name.toLowerCase() === name.toLowerCase() && 
      category.id !== excludeId
    );
  }

  /**
   * 获取实体类型的所有标签（去重）
   */
  static async getTagsByEntityType(entityType: EntityType): Promise<CustomTagWithCategory[]> {
    return this.getTags({
      entity_type: entityType.toString(),
      active_only: true,
    });
  }

  /**
   * 同步实体标签（替换现有标签）
   */
  static async syncEntityTags(
    tagIds: string[],
    entityType: EntityType,
    entityId: string
  ): Promise<void> {
    // 获取当前标签
    const currentTags = await this.getEntityTags(entityType, entityId);
    const currentTagIds = currentTags.map(t => t.tag.id);

    // 计算需要添加和删除的标签
    const toAdd = tagIds.filter(id => !currentTagIds.includes(id));
    const toRemove = currentTagIds.filter(id => !tagIds.includes(id));

    // 执行批量操作
    if (toAdd.length > 0) {
      await this.batchAddEntityTags(toAdd, entityType, entityId);
    }
    if (toRemove.length > 0) {
      await this.batchRemoveEntityTags(toRemove, entityType, entityId);
    }
  }

  /**
   * 获取标签的颜色（优先使用标签自定义颜色，否则使用分类颜色）
   */
  static getTagColor(tag: CustomTagWithCategory): string {
    return tag.tag.color || tag.category.color;
  }

  /**
   * 格式化标签显示名称
   */
  static formatTagDisplayName(tag: CustomTagWithCategory, showCategory: boolean = false): string {
    if (showCategory) {
      return `${tag.category.name} / ${tag.tag.name}`;
    }
    return tag.tag.name;
  }

  /**
   * 验证标签数据
   */
  static validateTagData(data: Partial<CreateCustomTagRequest>): string[] {
    const errors: string[] = [];

    if (!data.name || data.name.trim().length === 0) {
      errors.push('标签名称不能为空');
    }

    if (data.name && data.name.length > 50) {
      errors.push('标签名称不能超过50个字符');
    }

    if (!data.category_id || data.category_id.trim().length === 0) {
      errors.push('必须选择标签分类');
    }

    if (data.description && data.description.length > 200) {
      errors.push('标签描述不能超过200个字符');
    }

    return errors;
  }

  /**
   * 验证分类数据
   */
  static validateCategoryData(data: Partial<CreateCustomTagCategoryRequest>): string[] {
    const errors: string[] = [];

    if (!data.name || data.name.trim().length === 0) {
      errors.push('分类名称不能为空');
    }

    if (data.name && data.name.length > 30) {
      errors.push('分类名称不能超过30个字符');
    }

    if (data.description && data.description.length > 200) {
      errors.push('分类描述不能超过200个字符');
    }

    if (data.color && !/^#[0-9A-Fa-f]{6}$/.test(data.color)) {
      errors.push('颜色格式不正确，请使用十六进制格式（如：#3b82f6）');
    }

    return errors;
  }
}
