import NProgress from 'nprogress';
import 'nprogress/nprogress.css';
import { Id, toast } from 'react-toastify';
import { nanoid } from 'nanoid';
import { toastLogin } from '@kevisual/resources/pages/message/ToastLogin';
import { uploadFiles, UploadProgress } from '@kevisual/query-upload/query-upload';

export type ConvertOpts = {
  appKey?: string;
  version?: string;
  username?: string;
  directory?: string;
  isPublic?: boolean;

  maxSize?: number;
  maxCount?: number;
};

export const uploadFilesV2 = async (files: File[], opts: ConvertOpts) => {
  const token = localStorage.getItem('token');
  if (!token) {
    console.log('uploadChunk token', token);
    toastLogin();
    return;
  }
  const length = files.length;
  const maxSize = opts.maxSize || 20 * 1024 * 1024; // 10MB
  const totalSize = files.reduce((acc, file) => acc + file.size, 0);
  if (totalSize > maxSize) {
    toast.error('有文件大小不能超过20MB');
    return;
  }
  const maxCount = opts.maxCount || 10;
  if (length > maxCount) {
    toast.error(`最多只能上传${maxCount}个文件`);
    return;
  }
  toast.info(`上传中，共${length}个文件`);

  let loaded: Id;
  const uploadProgress = new UploadProgress({
    onStart: function () {
      NProgress.start();
      loaded = toast.loading(`上传中...`);
    },
    onDone: () => {
      NProgress.done();
      toast.dismiss(loaded);
    },
    onProgress: (progress, data) => {
      NProgress.set(progress);
      console.log('uploadChunk progress', progress, data);
      toast.update(loaded, {
        render: `上传中... ${progress.toFixed(2)}%`,
        isLoading: true,
        autoClose: false,
      });
    },
  });

  const result = await uploadFiles(files, opts, {
    uploadProgress,
    token,
    createEventSource: (url: string, searchParams: URLSearchParams) => {
      return new EventSource(url + '?' + searchParams.toString());
    },
    FormDataFn: FormData,
  });
  return result;
};
