export interface RequestWithPercentProps {
  url: string;
  option?: RequestInit;
  /**
   * 进度回调
   * @param now 已下载 buffer 数量
   * @param all 总长度
   * @returns
   */
  onProcess: (now: number, all: number) => void;
}

/**
 * 文件下载并获取下载进度
 */
export const requestWithPercent = async ({
  url = "",
  option = {},
  onProcess,
}: RequestWithPercentProps) => {
  const res = await fetch(url, {
    mode: "cors",
    headers: {
      responseType: "arraybuffer",
      Accept: "application/json, text/plain, */*",
      "Cache-Control": "no-cache",
    },
    ...option,
  });
  const reader = res.body?.getReader();
  /** 文件总长度 */
  const contentLength = Number(res.headers.get("content-length"));

  const chunks = [];
  let receivedLength = 0;

  if (!reader) return Promise.reject(new Error("无法解析请求体"));

  while (true) {
    const { done, value } = await reader.read();

    if (done) {
      break;
    }

    chunks.push(value);
    receivedLength += value.length;

    onProcess(receivedLength, contentLength);
  }

  const chunksAll = new Uint8Array(receivedLength);
  let position = 0;

  for (const chunk of chunks) {
    chunksAll.set(chunk, position);
    position += chunk.length;
  }

  return chunksAll;
};
