import OSS from 'ali-oss';
import request from '@/utils/request';

let client;
let stsInfo;

/**
 * 获取 OSS-STS 临时凭证
 * @returns
 */
export const getSTSToken = () => request('/oss-sts');

/**
 * 获取 OSS 客户端
 * @returns
 */
export function getOSSClient() {
  if (client) {
    return Promise.resolve(client);
  }

  return getSTSToken().then((sts) => {
    stsInfo = sts;

    client = new OSS({
      accessKeyId: sts.accessKeyId,
      accessKeySecret: sts.accessKeySecret,
      stsToken: sts.stsToken,
      bucket: sts.bucket,
      endpoint: sts.endpoint,
      refreshSTSTokenInterval: 25 * 60 * 1000, // 每25min刷新一次
      refreshSTSToken: () => {
        return getSTSToken().then((res) => {
          return {
            accessKeyId: res.accessKeyId,
            accessKeySecret: res.accessKeySecret,
            stsToken: res.stsToken,
          };
        });
      },
    });

    return client;
  });
}

/**
 * 上传文件到 OSS
 * @param {*} file
 * @returns
 */
export function upload(file) {
  return getOSSClient().then(() => {
    const data = new FormData();
    data.append('file', file);
    const now = new Date();
    const fileName = `${stsInfo.path}/${now.valueOf()}-${file.name}`;

    return client.put(fileName, file).then((res) => res.url);
  });
}
