import dayjs from 'dayjs';
import { message } from 'antd';

// 根据文件大小判断使用普通上传还是分片上传
const fileSizeInMB = file.size / (1024 * 1024); // 将文件大小转换为 MB
if (fileSizeInMB <= 10) {
  // 文件大小小于等于 10 MB，使用普通上传
  normalUploader(file, type, ossClient);
} else {
  // 文件大小大于 10 MB，使用分片上传
  multipartUploader(file, type, ossClient, progress, callback);
}

export const partSize = 1024 * 1024; // 每个分片大小(byte)
const parallel = 3; // 同时上传的分片数

// 普通上传
export const normalUploader = async (file, type, ossClient) => {
  if (!ossClient) {
    return;
  }

  try {
    const fileExt = file.name.substring(file.name.lastIndexOf('.'));
    const fileName = `${type}-${dayjs().valueOf()}-${Math.random()
      .toString(36)
      .substring(2)}${fileExt}`;
    const filePath = `${dayjs().format('YYYY/MM/DD')}/${fileName}`;
    console.log(filePath);
    return new Promise((resolve, reject) => {
      ossClient
        .put(filePath, file)
        .then((res) => {
          console.log('普通上传result', res);
          const status = res?.res?.status;
          const statusCode = res?.res?.statusCode;
          const url = res?.url;
          const name = res?.name;
          resolve({ status, statusCode, url, name });
        })
        .catch((err) => {
          console.log(`普通上传 ${file.name} failed === `, err);
          message.error('上传失败！');
          reject(err);
        });
    }).catch((err) => {
      console.error(`文件上传失败`, err);
      message.error('上传失败！');
      reject(err);
    });
  } catch (e) {
    message.error('上传失败！');
    return new Promise.reject(false);
  }
};

// 分片上传
export const multipartUploader = async (file, type, ossClient, progress, callback) => {
  if (!ossClient) {
    return;
  }

  try {
    const fileExt = file.name.substring(file.name.lastIndexOf('.'));
    const fileName = `${type}-${dayjs().valueOf()}-${Math.random()
      .toString(36)
      .substring(2)}${fileExt}`;
    const filePath = `${dayjs().format('YYYY/MM/DD')}/${fileName}`;

    return new Promise((resolve, reject) => {
      ossClient
        .multipartUpload(filePath, file, {
          progress,
          parallel,
          partSize,
        })
        .then((res) => {
          console.log('分片上传result', res);
          const status = res?.res?.status;
          const statusCode = res?.res?.statusCode;
          const url = res?.url;
          const name = res?.name;
          resolve({ status, statusCode, url, name });
        })
        .catch((err) => {
          console.error(`文件上传失败`, err);
          message.error('上传失败！');
          reject(err);
        });
    }).catch((err) => {
      console.error(`文件上传失败`, err);
      message.error('上传失败！');
      reject(err);
    });
  } catch (e) {
    // 捕获超时异常。
    if (e.code === 'ConnectionTimeoutError') {
      console.log('TimeoutError');
    }
    message.error('上传失败！');
  }
};

// 断点续传
