import axios from "axios";
import request from "./request";
import { getUploadSign, onOnlyFileUpload } from "./oss-file-upload";
const bucketName = "gyt";
const ACL = "public-read";
const ossUploadUrl = `https://${bucketName}.ks3-cn-beijing.ksyuncs.com/`;

const policy = (params: object) => {
  return request.post("/open/getUploadSign", {
    data: params,
    requestType: "json",
  });
};

const getPolicy = async (fileName: string) => {
  const obj = {
    filename: fileName,
    bucketName: bucketName,
    postData: {
      filename: fileName,
      acl: ACL,
      key: fileName,
    },
  };
  // console.log("🚀 ~ obj:", obj)
  // const { data } = await policy(obj);
  const { data } = await getUploadSign(obj);
  // console.log(data);
  return data;
};
const upload = async (policy: any, fileName: string, file: any, progress?: Function) => {
  // const url = ossUploadUrl + fileName;
  // const formData = new FormData();
  // formData.append("policy", policy.policy);
  // formData.append("signature", policy.signature);
  // formData.append("key", fileName);
  // formData.append("KSSAccessKeyId", policy.kssAccessKeyId);
  // formData.append("acl", ACL);
  // formData.append("name", fileName);
  // formData.append("file", file);
  // const res = await axios({
  //   url: ossUploadUrl,
  //   method: "post",
  //   headers: {
  //     "Content-Type": "multipart/form-data",
  //   },
  //   data: formData,
  //   onUploadProgress: (progressEvent: any) => {
  //     const complete = ((progressEvent.loaded / progressEvent.total) * 100) | 0;
  //     progress && progress(complete);
  //   },
  // } as any);
  // return url;
  const fileParams = {
    policy: policy.policy,
    signature: policy.signature,
    key: fileName,
    KSSAccessKeyId: policy.kssAccessKeyId,
    acl: ACL,
    name: fileName,
    file: file,
  };
  return await onOnlyFileUpload(ossUploadUrl, fileParams);
};

export const api_uploadFile = async (file: any, fileName: string, progress?: Function) => {
  const policy = await getPolicy(fileName);
  const url = await upload(policy, fileName, file, progress && progress);
  console.log("🚀 ~ url:", url);
  return url;
};
