/**
 * 文件上传服务
 * 处理图片、视频等文件上传功能
 */

import { api } from './api';

/**
 * 根据 URI 扩展名和 mimeType 推断正确的文件信息
 * 优先使用 providedType，其次从 URI 推断，最后默认 JPEG
 * 这对 GIF 至关重要：Content-Type 错误会导致后端存为 .jpg，丢失动画
 */
function resolveFileInfo(uri: string, providedType?: string): { name: string; type: string } {
  const ts = Date.now();

  // 先从 providedType 判断
  if (providedType === 'image/gif') return { name: `img_${ts}.gif`, type: 'image/gif' };
  if (providedType === 'image/png') return { name: `img_${ts}.png`, type: 'image/png' };
  if (providedType === 'image/webp') return { name: `img_${ts}.webp`, type: 'image/webp' };
  if (providedType === 'video/mp4') return { name: `video_${ts}.mp4`, type: 'video/mp4' };
  if (providedType === 'video/quicktime') return { name: `video_${ts}.mov`, type: 'video/quicktime' };

  // 再从 URI 路径推断（expo-image-picker 返回的 URI 通常包含原始扩展名）
  const uriLower = uri.toLowerCase();
  if (uriLower.includes('.gif')) return { name: `img_${ts}.gif`, type: 'image/gif' };
  if (uriLower.includes('.png')) return { name: `img_${ts}.png`, type: 'image/png' };
  if (uriLower.includes('.webp')) return { name: `img_${ts}.webp`, type: 'image/webp' };
  if (uriLower.includes('.mp4')) return { name: `video_${ts}.mp4`, type: 'video/mp4' };
  if (uriLower.includes('.mov')) return { name: `video_${ts}.mov`, type: 'video/quicktime' };

  // 默认 JPEG
  return { name: `img_${ts}.jpg`, type: providedType || 'image/jpeg' };
}

// 上传响应
export interface UploadResponse {
  url: string;
  preview_url?: string;       // 列表/网格预览图
  preview_url_large?: string;  // 详情页预览图
  width?: number;
  height?: number;
  size?: number;
  type?: string;
}

// 上传服务类
class UploadService {
  // 上传图片
  async uploadImage(file: {
    uri: string;
    name?: string;
    type?: string;
  }): Promise<UploadResponse | null> {
    try {
      const { name, type } = resolveFileInfo(file.uri, file.type);
      
      const response = await api.upload<UploadResponse>('/uploads/images', {
        uri: file.uri,
        name: file.name || name,
        type,
      });
      
      return response.data;
    } catch (error) {
      console.error('上传图片失败:', error);
      return null;
    }
  }

  // 上传多张图片
  async uploadImages(files: {
    uri: string;
    name?: string;
    type?: string;
  }[]): Promise<UploadResponse[]> {
    const results: UploadResponse[] = [];
    
    for (const file of files) {
      const result = await this.uploadImage(file);
      if (result) {
        results.push(result);
      }
    }
    
    return results;
  }

  // 上传头像
  async uploadAvatar(file: {
    uri: string;
    name?: string;
    type?: string;
  }): Promise<UploadResponse | null> {
    try {
      const { name, type } = resolveFileInfo(file.uri, file.type);
      
      const response = await api.upload<UploadResponse>('/users/me/avatar', {
        uri: file.uri,
        name: file.name || name,
        type,
      });
      
      return response.data;
    } catch (error) {
      console.error('上传头像失败:', error);
      return null;
    }
  }

  // 上传视频
  async uploadVideo(file: {
    uri: string;
    name?: string;
    type?: string;
  }): Promise<UploadResponse | null> {
    try {
      const fileName = file.name || `video_${Date.now()}.mp4`;
      const fileType = file.type || 'video/mp4';
      
      const response = await api.upload<UploadResponse>('/upload/video', {
        uri: file.uri,
        name: fileName,
        type: fileType,
      });
      
      return response.data;
    } catch (error) {
      console.error('上传视频失败:', error);
      return null;
    }
  }

  // 上传文件（通用）
  async uploadFile(
    file: {
      uri: string;
      name?: string;
      type?: string;
    },
    folder: string = 'general'
  ): Promise<UploadResponse | null> {
    try {
      const response = await api.upload<UploadResponse>('/upload/file', {
        uri: file.uri,
        name: file.name || `file_${Date.now()}`,
        type: file.type || 'application/octet-stream',
      }, { folder });
      
      return response.data;
    } catch (error) {
      console.error('上传文件失败:', error);
      return null;
    }
  }

  // 上传帖子图片
  async uploadPostImages(files: {
    uri: string;
    name?: string;
    type?: string;
  }[]): Promise<string[]> {
    const urls: string[] = [];
    
    for (const file of files) {
      const result = await this.uploadImage(file);
      if (result) {
        // 将预览图信息合并到 URL 中：url|preview_url|preview_url_large
        const parts = [result.url];
        if (result.preview_url) {
          parts.push(result.preview_url);
        } else {
          parts.push(''); // 空占位
        }
        if (result.preview_url_large) {
          parts.push(result.preview_url_large);
        } else {
          parts.push(''); // 空占位
        }
        urls.push(parts.join('|'));
      }
    }
    
    return urls;
  }

  // 上传聊天图片（复用上传图片接口）
  async uploadChatImage(file: {
    uri: string;
    name?: string;
    type?: string;
  }): Promise<UploadResponse | null> {
    // 使用通用的图片上传接口
    return this.uploadImage(file);
  }

  // 上传社区图标
  async uploadCommunityIcon(file: {
    uri: string;
    name?: string;
    type?: string;
  }): Promise<UploadResponse | null> {
    try {
      const fileName = file.name || `community_${Date.now()}.jpg`;
      const fileType = file.type || 'image/jpeg';
      
      const response = await api.upload<UploadResponse>('/upload/community-icon', {
        uri: file.uri,
        name: fileName,
        type: fileType,
      });
      
      return response.data;
    } catch (error) {
      console.error('上传社区图标失败:', error);
      return null;
    }
  }

  // 上传社区封面图
  async uploadCommunityCover(file: {
    uri: string;
    name?: string;
    type?: string;
  }): Promise<UploadResponse | null> {
    try {
      const fileName = file.name || `community_cover_${Date.now()}.jpg`;
      const fileType = file.type || 'image/jpeg';
      
      const response = await api.upload<UploadResponse>('/upload/community-cover', {
        uri: file.uri,
        name: fileName,
        type: fileType,
      });
      
      return response.data;
    } catch (error) {
      console.error('上传社区封面图失败:', error);
      return null;
    }
  }

  // 删除文件
  async deleteFile(url: string): Promise<boolean> {
    try {
      const response = await api.post('/upload/delete', { url });
      return response.code === 0;
    } catch (error) {
      console.error('删除文件失败:', error);
      return false;
    }
  }

  // 上传群头像
  async uploadGroupAvatar(file: {
    uri: string;
    name?: string;
    type?: string;
  }): Promise<UploadResponse | null> {
    try {
      const { name, type } = resolveFileInfo(file.uri, file.type);

      const response = await api.upload<UploadResponse>('/uploads/images', {
        uri: file.uri,
        name: file.name || name,
        type,
      });

      return response.data;
    } catch (error) {
      console.error('上传群头像失败:', error);
      return null;
    }
  }

  // 上传头图（个人主页封面）
  async uploadCover(file: {
    uri: string;
    name?: string;
    type?: string;
  }): Promise<UploadResponse | null> {
    try {
      const { name, type } = resolveFileInfo(file.uri, file.type);
      
      const response = await api.upload<UploadResponse>('/users/me/cover', {
        uri: file.uri,
        name: file.name || name,
        type,
      });
      
      return response.data;
    } catch (error) {
      console.error('上传头图失败:', error);
      return null;
    }
  }
}

// 导出上传服务实例
export const uploadService = new UploadService();
