import React, { useState, useEffect } from 'react';
import { Upload } from 'tdesign-mobile-react';
import type { UploadFile as TDesignUploadFile } from 'tdesign-mobile-react/es/upload/type';
import { uploadImage } from '@/api/upload';

interface UploadImageProps {
  value?: string[];
  onChange?: (urls: string[]) => void;
  max?: number;
  accept?: string;
  disabled?: boolean;
}

const UploadImage: React.FC<UploadImageProps> = ({ value = [], onChange, ...props }) => {
  // 受控 files 状态
  const [files, setFiles] = useState<TDesignUploadFile[]>(value.map(url => ({ url })));

  // value 变化时同步 files
  useEffect(() => {
    setFiles(value.map(url => ({ url })));
  }, [value]);

  // 处理上传
  const requestMethod = async (file: TDesignUploadFile) => {
    try {
      const url = await uploadImage(file.raw as File);
      return {
        status: 'success' as const,
        response: {
          url
        },
        url,
      };
    } catch (e: any) {
      return {
        status: 'fail' as const,
        error: e.message || '上传失败',
        response: {},
      };
    }
  };

  // 处理文件变更
  const handleChange = (newFiles: TDesignUploadFile[]) => {
    setFiles(newFiles);
    const urls = newFiles.map(f => f.url).filter((url): url is string => Boolean(url));
    onChange?.(urls);
  };

  return (
    <Upload
      files={files}
      requestMethod={requestMethod}
      onChange={handleChange}
      multiple
      accept={props.accept}
      max={props.max}
      disabled={props.disabled}
    />
  );
};

export default UploadImage; 