import NProgress from 'nprogress';
import 'nprogress/nprogress.css';
import { toast } from 'react-toastify';
import { nanoid } from 'nanoid';
import { toastLogin } from '@kevisual/resources/pages/message/ToastLogin';
type ConvertOpts = {
  appKey?: string;
  version?: string;
  username?: string;
  directory?: string;
};
export const uploadFiles = async (files: File[], opts: ConvertOpts) => {
  const { directory, appKey, version, username } = opts;
  const length = files.length;
  const maxSize = 10 * 1024 * 1024; // 10MB
  const totalSize = files.reduce((acc, file) => acc + file.size, 0);
  if (totalSize > maxSize) {
    toast.error('有文件大小不能超过10MB');
    return;
  }
  const maxCount = 10;
  if (length > maxCount) {
    toast.error(`最多只能上传${maxCount}个文件`);
    return;
  }
  toast.info(`上传中，共${length}个文件`);
  return new Promise((resolve, reject) => {
    const formData = new FormData();
    const webkitRelativePath = files[0]?.webkitRelativePath;
    const keepDirectory = webkitRelativePath !== '';
    const root = keepDirectory ? webkitRelativePath.split('/')[0] : '';
    for (let i = 0; i < files.length; i++) {
      const file = files[i];
      if (keepDirectory) {
        // relativePath 去除第一级
        const webkitRelativePath = file.webkitRelativePath.replace(root + '/', '');
        formData.append('file', file, webkitRelativePath); // 保留文件夹路径
      } else {
        formData.append('file', files[i], files[i].name);
      }
    }
    if (directory) {
      formData.append('directory', directory);
    }
    if (appKey && version) {
      formData.append('appKey', appKey);
      formData.append('version', version);
    }
    if (username) {
      formData.append('username', username);
    }
    const token = localStorage.getItem('token');
    if (!token) {
      console.log('uploadFiles token', token);
      toastLogin();
      return;
    }
    const taskId = nanoid();
    const eventSource = new EventSource('/api/s1/events?taskId=' + taskId);
    const load = toast.loading('上传中...');
    NProgress.start();
    eventSource.onopen = async function (event) {
      console.log('eventSource.onopen', event);
      const res = await fetch('/api/s1/resources/upload?taskId=' + taskId, {
        method: 'POST',
        body: formData,
        headers: {
          'task-id': taskId,
          Authorization: `Bearer ${token}`,
        },
      }).then((response) => response.json());

      console.log('upload success', res);
      fetch('/api/s1/events/close?taskId=' + taskId);
      eventSource.close();
      NProgress.done();
      toast.dismiss(load);
      resolve(res);
    };
    // 监听服务器推送的进度更新
    eventSource.onmessage = function (event) {
      console.log('Progress update:', event.data);
      const parseIfJson = (data: string) => {
        try {
          return JSON.parse(data);
        } catch (e) {
          return data;
        }
      };
      const receivedData = parseIfJson(event.data);
      if (typeof receivedData === 'string') return;
      const progress = receivedData.progress;
      console.log('progress', progress);
      toast.update(load, { render: `上传中...${progress}%`, isLoading: true, autoClose: false });
      if (progress) {
        NProgress.set(progress);
      }
    };
    eventSource.onerror = function (event) {
      console.log('eventSource.onerror', event);
      reject(event);
    };
  });
};
