/**
 * @作者: 阿瑞
 * @功能: 图片上传组件，支持拖拽上传、粘贴上传和指定文件夹
 * @版本: 2.0.0
 */

'use client';

import React, { useState, useEffect, useCallback } from 'react';
import { nanoid } from 'nanoid';
import Image from 'next/image';
import { useParams } from 'next/navigation';
import { Upload, message, Button, Typography } from 'antd';
import { InboxOutlined, CopyOutlined, DeleteOutlined } from '@ant-design/icons';
import type { UploadFile } from 'antd';

const { Text } = Typography;
const { Dragger } = Upload;

// 定义组件属性接口
interface UploadImageProps {
  /** 文件上传成功后的回调函数，返回上传后的URL */
  onSuccess?: (imageUrl: string) => void;
  /** 上传文件夹，不传则使用默认根目录 */
  folder?: string;
}

// 定义远程服务器的URL (当前项目中测试时设为null)
const API_SERVER_URL = null; // 生产环境中设置为 'http://localhost:3000'

// 获取API完整URL
const getApiUrl = (path: string) => {
  return API_SERVER_URL ? `${API_SERVER_URL}${path}` : path;
};

/**
 * 图片上传组件
 * 支持拖拽上传、粘贴上传和指定文件夹
 */
const UploadImage: React.FC<UploadImageProps> = ({
  onSuccess,
  folder = ''
}) => {
  const [fileList, setFileList] = useState<UploadFile[]>([]);
  const [isPasteEnabled, setIsPasteEnabled] = useState(true);
  const [isUploading, setIsUploading] = useState(false);
  const maxFileSizeMB = 5; // 默认5MB

  // 获取团队信息
  const params = useParams();
  const teamCode = params?.teamCode as string || '';

  // 组合文件夹路径：如果有folder，则添加团队信息
  const getTargetFolder = () => {
    let targetFolder = folder;
    if (folder && teamCode) {
      targetFolder = `${folder}_${teamCode}`;
    }
    return targetFolder;
  };

  // 生成格式化的日期字符串 (YYYYMMDD)
  const getFormattedDate = (): string => {
    const now = new Date();
    const year = now.getFullYear();
    const month = String(now.getMonth() + 1).padStart(2, '0');
    const day = String(now.getDate()).padStart(2, '0');
    return `${year}${month}${day}`;
  };

  // 创建标准文件名
  const createStandardFileName = useCallback((file: File): string => {
    // 获取文件扩展名
    const originalFileName = file.name;
    const fileExt = file.type.split('/')[1] || originalFileName.split('.').pop() || 'png';

    // 生成日期字符串
    const dateStr = getFormattedDate();

    // 生成6位nanoid
    const shortId = nanoid(6);

    // 创建新的文件名: 20231012_a4f8c0.png 格式
    return `${dateStr}_${shortId}.${fileExt}`;
  }, []);

  /**
   * 处理粘贴事件
   */
  const handlePaste = useCallback((e: ClipboardEvent) => {
    if (!isPasteEnabled || isUploading) return;

    const items = e.clipboardData?.items;
    if (!items) return;

    // 查找剪贴板中的图片
    for (let i = 0; i < items.length; i++) {
      if (items[i].type.indexOf('image') !== -1) {
        const file = items[i].getAsFile();
        if (file) {
          e.preventDefault(); // 阻止默认粘贴行为
          
          // 验证文件类型
          const validTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
          if (!validTypes.includes(file.type)) {
            message.error('不支持的文件类型，请上传JPG、PNG、GIF或WEBP格式的图片');
            return;
          }

          // 验证文件大小
          const maxSizeBytes = maxFileSizeMB * 1024 * 1024;
          if (file.size > maxSizeBytes) {
            message.error(`文件过大，请上传小于${maxFileSizeMB}MB的图片`);
            return;
          }
          
          // 创建标准文件名
          const newFileName = createStandardFileName(file);
          const newFile = new File([file], newFileName, { type: file.type });
          
          // 创建上传文件对象
          const uploadFile: UploadFile = {
            uid: `-${Date.now()}`,
            name: newFileName,
            status: 'uploading',
            originFileObj: newFile as any,
            percent: 0,
          };
          
          setFileList([uploadFile]);
          
          // 自动上传文件
          uploadImage(newFile);
          break;
        }
      }
    }
  }, [isPasteEnabled, isUploading, createStandardFileName]);

  /**
   * 上传图片到服务器
   */
  const uploadImage = async (file: File) => {
    setIsUploading(true);
    
    try {
      const formData = new FormData();
      formData.append('file', file);

      // 添加文件夹信息
      const targetFolder = getTargetFolder();
      if (targetFolder) {
        formData.append('folder', targetFolder);
      }

      const response = await fetch(getApiUrl('/api/tools/upload'), {
        method: 'POST',
        body: formData,
      });

      if (!response.ok) {
        const errorData = await response.json();
        throw new Error(errorData.error || errorData.details || '上传失败');
      }

      const data = await response.json();
      
      // 更新文件状态
      setFileList(prev => prev.map(file => ({
        ...file,
        status: 'done',
        url: data.url,
      })));
      
      // 显示成功信息
      message.success(`图片上传成功！${targetFolder ? `已保存到文件夹 ${targetFolder}` : ''}`);

      // 调用回调函数
      if (onSuccess) {
        onSuccess(data.url);
      }
    } catch (error) {
      console.error('上传图片时出错:', error);
      const errorMsg = error instanceof Error ? error.message : '上传图片时出错';
      message.error(errorMsg);
      
      setFileList(prev => prev.map(file => ({
        ...file,
        status: 'error',
        error: new Error(errorMsg) as any,
      })));
    } finally {
      setIsUploading(false);
    }
  };

  // 注册和清理粘贴事件监听器
  useEffect(() => {
    document.addEventListener('paste', handlePaste);

    return () => {
      document.removeEventListener('paste', handlePaste);
    };
  }, [handlePaste]);

  /**
   * 上传前处理
   */
  const beforeUpload = (file: File) => {
    // 验证文件类型
    const validTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
    if (!validTypes.includes(file.type)) {
      message.error('不支持的文件类型，请上传JPG、PNG、GIF或WEBP格式的图片');
      return Upload.LIST_IGNORE;
    }

    // 验证文件大小
    const maxSizeBytes = maxFileSizeMB * 1024 * 1024;
    if (file.size > maxSizeBytes) {
      message.error(`文件过大，请上传小于${maxFileSizeMB}MB的图片`);
      return Upload.LIST_IGNORE;
    }

    // 创建标准文件名
    const newFileName = createStandardFileName(file);
    const newFile = new File([file], newFileName, { type: file.type });
    
    // 重命名文件后，替换当前文件
    setFileList([{
      uid: `-${Date.now()}`,
      name: newFileName,
      status: 'uploading',
      originFileObj: newFile as any,
      percent: 0,
    }]);
    
    // 自动上传文件
    uploadImage(newFile);
    
    // 阻止默认上传行为
    return false;
  };

  /**
   * 移除文件处理
   */
  const handleRemove = () => {
    const file = fileList[0];
    if (file && file.status === 'done' && file.url) {
      // 执行服务器端删除
      deleteImageFromServer(file.url)
        .then(() => {
          setFileList([]);
          message.success('图片已删除');
          // 通知父组件图片已删除（传递空字符串）
          if (onSuccess) {
            onSuccess('');
          }
        })
        .catch(() => {
          message.warning('服务器端删除失败，但已从预览中移除');
          setFileList([]);
          // 即使删除失败，也通知父组件图片已被移除
          if (onSuccess) {
            onSuccess('');
          }
        });
    } else {
      // 如果图片尚未上传到服务器或上传失败，直接从本地移除
      setFileList([]);
      // 通知父组件图片已被移除
      if (onSuccess) {
        onSuccess('');
      }
    }
    return true;
  };

  /**
   * 从服务器删除图片
   */
  const deleteImageFromServer = async (imageUrl: string) => {
    try {
      // 检查URL格式
      if (!imageUrl.startsWith('/api/tools/images/')) {
        throw new Error('无效的图片URL格式');
      }
      
      // 直接对完整URL发送DELETE请求
      const response = await fetch(imageUrl, { 
        method: 'DELETE' 
      });
      
      if (!response.ok) {
        const errorData = await response.json();
        throw new Error(errorData.error || errorData.details || '删除失败');
      }
      
      return await response.json();
    } catch (error) {
      console.error('删除图片时出错:', error);
      throw error;
    }
  };

  /**
   * 切换粘贴功能
   */
  const togglePasteEnabled = () => {
    setIsPasteEnabled(!isPasteEnabled);
    message.info(isPasteEnabled ? '已关闭粘贴检测' : '已开启粘贴检测');
  };

  /**
   * 自定义文件上传按钮
   */
  const uploadButton = (
    <div>
      <Dragger 
        showUploadList={false}
        accept="image/jpeg,image/png,image/gif,image/webp"
        beforeUpload={beforeUpload}
        fileList={[]}
        disabled={isUploading}
      >
        <p className="ant-upload-drag-icon">
          <InboxOutlined />
        </p>
        <p className="ant-upload-text">点击或拖拽图片到此处上传</p>
        <p className="ant-upload-hint">
          支持PNG、JPG、GIF、WEBP格式，最大{maxFileSizeMB}MB
        </p>
        <p className="ant-upload-hint" style={{ color: '#1677ff' }}>
          您也可以直接粘贴剪贴板中的图片 (Ctrl+V)
        </p>
      </Dragger>
    </div>
  );

  /**
   * 渲染预览图
   */
  const renderPreview = () => {
    const file = fileList[0];
    if (!file) return null;
    
    const previewUrl = file.url || (file.originFileObj && URL.createObjectURL(file.originFileObj));
    if (!previewUrl) return null;
    
    return (
      <div style={{ position: 'relative', marginBottom: '16px', border: '1px solid #f0f0f0', borderRadius: '8px', overflow: 'hidden' }}>
        <Image
          src={previewUrl}
          alt="预览图片"
          width={500}
          height={300}
          style={{ width: '100%', height: 'auto', maxHeight: '200px', objectFit: 'contain' }}
        />
        {file.status === 'uploading' && (
          <div style={{ 
            position: 'absolute', 
            top: 0, 
            left: 0, 
            right: 0, 
            bottom: 0, 
            background: 'rgba(0,0,0,0.4)', 
            display: 'flex', 
            alignItems: 'center', 
            justifyContent: 'center',
            color: 'white',
            fontSize: '16px'
          }}>
            上传中...
          </div>
        )}
        <Button
          type="primary"
          danger
          size="small"
          icon={<DeleteOutlined />}
          onClick={handleRemove}
          disabled={isUploading}
          style={{ position: 'absolute', top: '8px', right: '8px' }}
        >
          删除
        </Button>
        
        {/* 在预览下方显示文件夹信息（如果有设置） */}
        {folder && (
          <div style={{ 
            position: 'absolute', 
            top: '8px', 
            left: '8px', 
            padding: '2px 8px', 
            background: 'rgba(0,0,0,0.4)', 
            borderRadius: '4px', 
            fontSize: '12px', 
            color: 'white' 
          }}>
            文件夹: {getTargetFolder()}
          </div>
        )}
      </div>
    );
  };

  return (
    <div className="uploader-container">
      {/* 错误处理区域由antd message组件处理 */}
      
      {/* 图片预览 */}
      {fileList.length > 0 ? renderPreview() : uploadButton}
      
      {/* 控制按钮区域 */}
      <div style={{ display: 'flex', alignItems: 'center', marginTop: '8px' }}>
        <Button
          type="text"
          icon={<CopyOutlined />}
          onClick={togglePasteEnabled}
          size="small"
          style={{ 
            color: isPasteEnabled ? '#52c41a' : '#bfbfbf'
          }}
        >
          {isPasteEnabled ? '已开启粘贴检测' : '已关闭粘贴检测'}
        </Button>
        
        <div style={{ flex: 1 }} />
        
        {fileList.length > 0 && fileList[0].status === 'done' && (
          <Text type="success">上传成功</Text>
        )}
      </div>
    </div>
  );
};

export default UploadImage; 