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

export const partSize = 1024 * 1024 * 1; // 每个分片大小(byte)
export 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}`;
    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('上传失败！');
      return new Promise.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?.res?.requestUrls[0].split("?")[0];
          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('上传失败！');
      return new Promise.reject(err);
    });
  } catch (e) {
    // 捕获超时异常。
    if (e.code === 'ConnectionTimeoutError') {
      console.log('TimeoutError');
    }
    message.error('上传失败！');
  }
};

// 断点续传
