import { http } from "@/utils/http";
import { baseUrlApi } from "@/api/utils";
import OSS from "ali-oss";
import type { AxiosInstance } from "axios";

type Result = {
  msg: boolean;
  data: any;
  code: number;
};

interface UploadOptions {
  accessKeyId: string;
  accessKeySecret: string;
  stsToken: string;
  bucket: string;
  region?: string;
  endpoint?: string;
  secure?: boolean;
  cname?: boolean;
  timeout?: number;
  refreshSTSToken?: () => Promise<{
    accessKeyId: string;
    accessKeySecret: string;
    stsToken: string;
  }>;
  refreshSTSTokenInterval?: number;
  axiosOptions?: AxiosInstance;
}

export const getAliossToken = () => {
  return http.request<Result>("post", baseUrlApi("/alioss/token"));
};

export default class Clients {
  client: OSS;

  constructor() {
    this.client = null;
    // this.getClient()
  }

  async getClient() {
    const params: UploadOptions = {
      accessKeyId: "",
      accessKeySecret: "",
      bucket: "",
      stsToken: ""
    };
    const res = await getAliossToken();
    if (res.code === 0) {
      params.accessKeyId = res.data.accessKeyId;
      params.accessKeySecret = res.data.accessKeySecret;
      params.stsToken = res.data.securityToken;
    }
    //后端提供数据
    this.client = new OSS({
      region: "oss-cn-hangzhou", //oss-cn-beijing-internal.aliyuncs.com
      accessKeyId: params.accessKeyId,
      accessKeySecret: params.accessKeySecret,
      stsToken: params.stsToken,
      bucket: "loansm"
    });
  }

  async put(fileName: string, file: File | Blob | string) {
    if (!this.client) {
      await this.getClient();
    }
    return await this.client.put(fileName, file);
  }
}
