import { UploadFileController } from "queenjs/framework/utils";

export class Uploader extends UploadFileController {
  async uploadFile2Server(
    file: File | Blob
  ): Promise<{ url?: string; size?: number; error?: string }> {
    const formData = new FormData();
    formData.append("file", file);

    let result: any = await this.Post(
      this.requestConfig.baseURL + "/upload",
      formData
    );
    if (typeof result == "string") {
      result = JSON.parse(result);
    }

    if (result && result.result) {
      console.log("uploadFile2Server back", result.result);
      return { url: result.result, size: file.size };
    }
    return {
      error:
        result && result.errorDesc ? result.errorDesc : "文件上传服务器失败!",
    };
  }

  Post(url: string, data: any) {
    return new Promise((resolve, reject) => {
      const xhr = new XMLHttpRequest();
      xhr.open("POST", url, true);

      xhr.onload = () => {
        resolve(xhr.response);
      };
      xhr.onerror = (e) => {
        resolve(false);
      };
      try {
        xhr.send(data);
      } catch (error) {
        resolve(false);
      }
    });
  }
}
