import { httpApp } from "@/plugins/axiosIndex";
import { getMd5FromBlob, object2QueryString } from "@/utils/utils";
import { pickBy } from "lodash-es";

export async function uploadFile({ file, onProgress }) {
  const form = new FormData();
  form.append("file", file);

  const md5 = await getMd5FromBlob(file);

  return httpApp.post(
    "/api/admin/sys/file/upload?" + object2QueryString({ type: "frontend" }),
    form,
    {
      headers: { "Content-Type": "multipart/form-data", md5: md5 },
      onUploadProgress:
        onProgress &&
        function (progressEvent) {
          // console.log(progressEvent);
          let e = {};
          if (progressEvent.total > 0 && progressEvent.loaded) {
            e.percent = (
              (progressEvent.loaded / progressEvent.total) *
              100
            ).toFixed(0);
          }
          onProgress(e);
        },
    }
  );
}

export function downloadFile({ id = "", type = "" }) {
  const data = pickBy({ id, type }, (v) => v !== "");
  return httpApp.post(
    "/api/admin/sys/file/download?" +
      object2QueryString({ ...data, type: type })
  );
}
