import OSS from "ali-oss";
import API from "@/server/api";
import dayjs from "dayjs";
import LoadingManager from "@/utils/LoadingManager";

let ossCredentials = null;

/**
 * 判断临时凭证是否到期。
 **/
function isCredentialsExpired(credentials) {
  if (!credentials) {
    return true;
  }
  const expireDate = dayjs(credentials.expiration).valueOf();
  const now = dayjs().valueOf();
  // 如果有效期不足一分钟，视为过期。
  return expireDate - now <= 60000;
}

const progress = (p) => {
  // Object的上传进度。
  console.log(p);
};

export default function useOSS() {
  const uploadFile = async (file, path = "LOAN-CUSTOMER") => {
    const EXT = file.name.split(".");
    const PATH_FILE_SUFFIX = `${path}/${dayjs().format("YYYYMMDD")}/${
      EXT[0]
    }-${dayjs().valueOf()}.${EXT[EXT.length - 1]}`;
    console.log(EXT, PATH_FILE_SUFFIX, "那是");
    if (isCredentialsExpired(ossCredentials)) {
      const params = { filePath: PATH_FILE_SUFFIX };
      const { data } = await API.ossToken({ ...params });
      ossCredentials = Object.assign({}, data.result);
    }
    console.log(ossCredentials, "xx ");

    const client = new OSS({
      bucket: ossCredentials.bucket,
      region: "oss-cn-hangzhou" || ossCredentials.region,
      accessKeyId: ossCredentials.accessKeyId,
      accessKeySecret: ossCredentials.accessKeySecret,
      stsToken: ossCredentials.securityToken,
      refreshSTSTokenInterval: 300000, // refresh token every 30 minutes
    });

    try {
      LoadingManager.showFullScreenLoading();
      const result = await client.multipartUpload(PATH_FILE_SUFFIX, file, {
        progress,
      });
      LoadingManager.hideFullScreenLoading();

      const FILE_HOST = ossCredentials.hostUrl; // 资源地址
      const originalUrl = result.res.requestUrls[0].split("?")[0];
      const url = originalUrl.replace(/^https?:\/\/[^\/]+/, FILE_HOST); // 拼接完整资源地址

      if (url) {
        return [
          {
            url: url,
            name: file.name,
          },
        ];
      } else {
        throw new Error("上传失败");
      }
    } catch (error) {
      LoadingManager.hideFullScreenLoading();
      // eslint-disable-next-line no-console
      console.log(error);
      throw new Error(error);
    }
  };
  return { uploadFile };
}
