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 { uploadFileChunked, UploadProgress } from '@kevisual/query-upload/query-upload';

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

export const uploadChunkV2 = async (file: File, opts: ConvertOpts) => {
  const filename = opts.filename || file.name;
  const token = localStorage.getItem('token');
  if (!token) {
    console.log('uploadChunk token', token);
    toastLogin();
    return;
  }
  let loaded: Id;
  const uploadProgress = new UploadProgress({
    onStart: function () {
      NProgress.start();
      loaded = toast.loading(`${filename} 上传中...`);
    },
    onDone: () => {
      NProgress.done();
      toast.dismiss(loaded);
    },
    onProgress: (progress, data) => {
      NProgress.set(progress);
      console.log('uploadChunk progress', progress, data);
      toast.update(loaded, {
        render: `${filename} 上传中... ${progress.toFixed(2)}%`,
        isLoading: true,
        autoClose: false,
      });
    },
  });

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