import { invoke } from '@tauri-apps/api/core';
import {
  Model,
  CreateModelRequest,
  UpdateModelRequest,
  ModelQueryParams,
  ModelStatistics,
  ModelPhoto,
  PhotoType,
  ModelStatus,
  ModelAPI
} from '../types/model';

/**
 * 模特管理服务
 * 遵循 Tauri 开发规范的前端服务层设计
 */
export class ModelService implements ModelAPI {
  /**
   * 创建模特
   */
  async createModel(request: CreateModelRequest): Promise<Model> {
    try {
      const model = await invoke<Model>('create_model', { request });
      return model;
    } catch (error) {
      console.error('创建模特失败:', error);
      throw new Error(`创建模特失败: ${error}`);
    }
  }

  /**
   * 根据ID获取模特详情
   */
  async getModelById(id: string): Promise<Model | null> {
    try {
      const model = await invoke<Model | null>('get_model_by_id', { id });
      return model;
    } catch (error) {
      console.error('获取模特详情失败:', error);
      throw new Error(`获取模特详情失败: ${error}`);
    }
  }

  /**
   * 获取所有模特
   */
  async getAllModels(): Promise<Model[]> {
    try {
      console.log('调用 get_all_models 命令...');
      const models = await invoke<Model[]>('get_all_models');
      console.log('get_all_models 命令返回:', models);
      return models;
    } catch (error) {
      console.error('获取模特列表失败:', error);
      throw new Error(`获取模特列表失败: ${error}`);
    }
  }

  /**
   * 搜索模特
   */
  async searchModels(params: ModelQueryParams): Promise<Model[]> {
    try {
      const models = await invoke<Model[]>('search_models', { params });
      return models;
    } catch (error) {
      console.error('搜索模特失败:', error);
      throw new Error(`搜索模特失败: ${error}`);
    }
  }

  /**
   * 更新模特信息
   */
  async updateModel(id: string, request: UpdateModelRequest): Promise<Model> {
    try {
      const model = await invoke<Model>('update_model', { id, request });
      return model;
    } catch (error) {
      console.error('更新模特失败:', error);
      throw new Error(`更新模特失败: ${error}`);
    }
  }

  /**
   * 删除模特（软删除）
   */
  async deleteModel(id: string): Promise<void> {
    try {
      await invoke('delete_model', { id });
    } catch (error) {
      console.error('删除模特失败:', error);
      throw new Error(`删除模特失败: ${error}`);
    }
  }

  /**
   * 永久删除模特
   */
  async deleteModelPermanently(id: string): Promise<void> {
    try {
      await invoke('delete_model_permanently', { id });
    } catch (error) {
      console.error('永久删除模特失败:', error);
      throw new Error(`永久删除模特失败: ${error}`);
    }
  }

  /**
   * 添加模特照片
   */
  async addModelPhoto(
    modelId: string,
    filePath: string,
    photoType: PhotoType,
    description?: string,
    tags?: string[]
  ): Promise<ModelPhoto> {
    try {
      const photo = await invoke<ModelPhoto>('add_model_photo', {
        modelId,
        filePath,
        photoType,
        description,
        tags
      });
      return photo;
    } catch (error) {
      console.error('添加模特照片失败:', error);
      throw new Error(`添加模特照片失败: ${error}`);
    }
  }

  /**
   * 删除模特照片
   */
  async deleteModelPhoto(modelId: string, photoId: string): Promise<void> {
    try {
      await invoke('delete_model_photo', { modelId, photoId });
    } catch (error) {
      console.error('删除模特照片失败:', error);
      throw new Error(`删除模特照片失败: ${error}`);
    }
  }

  /**
   * 设置封面照片
   */
  async setCoverPhoto(modelId: string, photoId: string): Promise<void> {
    try {
      await invoke('set_cover_photo', { modelId, photoId });
    } catch (error) {
      console.error('设置封面照片失败:', error);
      throw new Error(`设置封面照片失败: ${error}`);
    }
  }

  /**
   * 添加标签
   */
  async addModelTag(modelId: string, tag: string): Promise<void> {
    try {
      await invoke('add_model_tag', { modelId, tag });
    } catch (error) {
      console.error('添加标签失败:', error);
      throw new Error(`添加标签失败: ${error}`);
    }
  }

  /**
   * 移除标签
   */
  async removeModelTag(modelId: string, tag: string): Promise<void> {
    try {
      await invoke('remove_model_tag', { modelId, tag });
    } catch (error) {
      console.error('移除标签失败:', error);
      throw new Error(`移除标签失败: ${error}`);
    }
  }

  /**
   * 更新模特状态
   */
  async updateModelStatus(modelId: string, status: ModelStatus): Promise<void> {
    try {
      await invoke('update_model_status', { modelId, status });
    } catch (error) {
      console.error('更新模特状态失败:', error);
      throw new Error(`更新模特状态失败: ${error}`);
    }
  }

  /**
   * 设置模特评分
   */
  async setModelRating(modelId: string, rating?: number): Promise<void> {
    try {
      await invoke('set_model_rating', { modelId, rating });
    } catch (error) {
      console.error('设置模特评分失败:', error);
      throw new Error(`设置模特评分失败: ${error}`);
    }
  }

  /**
   * 设置头像
   */
  async setModelAvatar(modelId: string, avatarPath?: string): Promise<void> {
    try {
      await invoke('set_model_avatar', { modelId, avatarPath });
    } catch (error) {
      console.error('设置头像失败:', error);
      throw new Error(`设置头像失败: ${error}`);
    }
  }

  /**
   * 获取模特统计信息
   */
  async getModelStatistics(): Promise<ModelStatistics> {
    try {
      const stats = await invoke<ModelStatistics>('get_model_statistics');
      return stats;
    } catch (error) {
      console.error('获取模特统计信息失败:', error);
      throw new Error(`获取模特统计信息失败: ${error}`);
    }
  }

  /**
   * 选择多个照片文件
   */
  async selectPhotoFiles(): Promise<string[]> {
    try {
      const files = await invoke<string[]>('select_photo_files');
      return files;
    } catch (error) {
      console.error('选择照片文件失败:', error);
      throw new Error(`选择照片文件失败: ${error}`);
    }
  }

  /**
   * 选择单个照片文件
   */
  async selectPhotoFile(): Promise<string | null> {
    try {
      const file = await invoke<string | null>('select_photo_file');
      return file;
    } catch (error) {
      console.error('选择照片文件失败:', error);
      throw new Error(`选择照片文件失败: ${error}`);
    }
  }

  /**
   * 关联素材到模特
   */
  async associateMaterialToModel(materialId: string, modelId: string): Promise<void> {
    try {
      await invoke('associate_material_to_model', { materialId, modelId });
    } catch (error) {
      console.error('关联素材到模特失败:', error);
      throw new Error(`关联素材到模特失败: ${error}`);
    }
  }

  /**
   * 取消素材与模特的关联
   */
  async disassociateMaterialFromModel(materialId: string): Promise<void> {
    try {
      await invoke('disassociate_material_from_model', { materialId });
    } catch (error) {
      console.error('取消关联失败:', error);
      throw new Error(`取消关联失败: ${error}`);
    }
  }

  /**
   * 根据模特ID获取关联的素材
   */
  async getMaterialsByModelId(modelId: string): Promise<any[]> {
    try {
      const materials = await invoke<any[]>('get_materials_by_model_id', { modelId });
      return materials;
    } catch (error) {
      console.error('获取模特关联素材失败:', error);
      throw new Error(`获取模特关联素材失败: ${error}`);
    }
  }

  /**
   * 获取未关联模特的素材
   */
  async getUnassociatedMaterials(projectId?: string): Promise<any[]> {
    try {
      const materials = await invoke<any[]>('get_unassociated_materials', { projectId });
      return materials;
    } catch (error) {
      console.error('获取未关联素材失败:', error);
      throw new Error(`获取未关联素材失败: ${error}`);
    }
  }
}

// 创建单例实例
export const modelService = new ModelService();
