
import OSS from "ali-oss";
import { request } from "./http"; // 导入 request
const { VITE_APP_OSS } = import.meta.env;
import { randomString } from "./common";
let client = null; // 保持一个单例的 OSS 客户端

async function getClient() {
  if (!client) {
    const { data } = await request.get("/commonService/oss/config") as any; // 从服务器获取凭证信息

    client = new OSS({
      accessKeyId: data.config.accessKeyId,
      accessKeySecret: data.config.accessKeySecret,
      bucket: data.config.bucket,
      region: data.config.region,
      stsToken: data.config.securityToken
    });
  }
  return client;
}

export async function uploadToOSS(file, fileName = '', progress?) {
  try {
    const client = await getClient();
    console.log("client", client);
    console.log(file, fileName);
    // if (fileName) {
    //   fileName = fileName.replace(
    //     /(\+| )/g,
    //     "-"
    //   );
    // }
    fileName = randomString(48) + '.' + fileName.split('.')?.at(-1)
    const result = await client.put(`/merchant/${fileName}`, file, { progress });
    console.log("上传成功", result);
    return `${VITE_APP_OSS}/merchant/${fileName}`; // 返回上传后的文件 URL
  } catch (error) {
    console.error("上传失败");
    console.log(error);

    client = null;
    throw error;
  }
}
