import OSS from "ali-oss";
import versionApi from "@/api/system/version";

const $headers = {
  "Access-Control-Allow-Origin": "*",
};
const $config = {
  region: "oss-cn-beijing",
  accessKeyId: "",
  accessKeySecret: "",
  bucket: "cashier-oss",
};
import { ElMessage } from "element-plus";
function urlConversion(path) {
  let reg = /^(https?:\/\/)([0-9a-z.]+)(:[0-9]+)?([/0-9a-z.]+)?(\?[0-9a-z&=]+)?(#[0-9-a-z]+)?/i;
  path = path.replace(reg, "https://$2$3$4$5$6");
  return path;
}

async function uploadAndDownloadFile(name, file, headers) {
  return new Promise((resolve, reject) => {
    try {
      ossClient.put(name, file, { ...$headers, ...headers }).then((res) => {
        console.log(res);
        resolve(res);
      });
    } catch (error) {
      console.error(error);
      reject(error);
    }
  });
}
class ossClient {
  constructor(config) {
    this.ossClient = new OSS({
      ...$config,
      ...config,
      refreshSTSToken: async () => {
        // 向您搭建的STS服务获取临时访问凭证。
        const res = await versionApi.getCredentials();
        return {
          accessKeyId: res.accessKeyId, // 自己账户的accessKeyId或临时秘钥
          accessKeySecret: res.accessKeySecret, // 自己账户的accessKeySecret或临时秘钥
          stsToken: res.securityToken, //  从STS服务获取的安全令牌（SecurityToken）。
        };
      },
      // 刷新临时访问凭证的时间间隔，单位为毫秒。
      refreshSTSTokenInterval: 3600 * 1000,
    });
  }
  async upload(name, file, progressCallback) {
    try {
      let options = {
        // 获取分片上传进度、断点和返回值。
        progress: progressCallback,
        headers: $headers,
      };
      const { res: resp } = await this.ossClient.put(name, file, options).catch((error) => {
        reject(error);
      });
      return resp.requestUrls;
    } catch (error) {
      console.log(error);
      reject(error);
    }
  }
  /**
   * 分片上传
   * @param {Object} client oss客户端
   * @param {Object} file 上传的文件
   * @param {Object} dir 上传oss的文件夹
   * @param {Object} progressCallback 分片进度回调
   */
  async partUpload(name, file, progressCallback) {
    try {
      let options = {
        // 获取分片上传进度、断点和返回值。
        progress: progressCallback,

        // 设置并发上传的分片数量。
        parallel: 8,
        // 设置分片大小。默认值为1 MB，最小值为100 KB。
        partSize: 100 * 1024,
        mime: file.type,
      };
      const { res: resp } = await this.ossClient.multipartUpload(
        name ? name : file.name,
        file,
        options
      );
      // return resp.requestUrls
      console.log("------resp---");
      console.log(resp);
      return urlConversion(`${resp.requestUrls[0]}`.split("?")[0]);
    } catch (e) {
      console.log("------e---");
      console.log(e);
      if (e.name == "cancel") {
        ElMessage.error({
          title: "上传已取消",
          duration: 3000,
        });
        return e;
      }
    }
  }

  /**
   * 结束上传并删除碎片
   * @param {Object} client
   * @param {Object} uploadId
   * @param {Object} name
   */
  async abortUpload(uploadId, name) {
    try {
      const res = await this.ossClient.abortMultipartUpload(name, uploadId);
      return res;
    } catch (error) {
      console.log(error);
      return error;
    }
  }
}
export default ossClient;
