import superagent, {
  SuperAgentRequest,
  Response,
  ProgressEvent,
} from "superagent";
import message from "../../../../utils/message";
import { toLoginPage } from "../../../../utils/toLogin";

enum METHOD {
  POST = "POST",
  GET = "GET",
  PUT = "PUT",
  DELETE = "DELETE",
}

interface Options {
  baseURL: string;
}

interface RequestHandlerOptions {
  url: string;
  methods: METHOD;
  data: {
    [key: string]: any;
    params?: Record<string, any>;
  };
}

class Request {
  baseURL: string = "";
  constructor(options: Options) {
    this.baseURL = options.baseURL;
  }
  formateUrl(url) {
    return this.baseURL + url;
  }
  resultSuccessCallback(res: Response) {
    const body = res.body;
    const code = body.code;
    if (code !== 1000) {
      message.error(body.msg);
      if (code === 40001) {
        toLoginPage();
      }
      return Promise.reject(res);
    }
    return Promise.resolve(body);
  }
  requestHandler({
    url,
    methods,
    data,
  }: RequestHandlerOptions): SuperAgentRequest {
    let req = superagent(methods, this.formateUrl(url));

    if (data) {
      if (methods === METHOD.GET) {
        req = req.query(data);
      }
      req = req.send(data);
    }
    return req;
  }
  get(url, data?) {
    return this.requestHandler({
      url,
      methods: METHOD.GET,
      data,
    }).then(this.resultSuccessCallback);
  }
  post(url, data?, onProgress?: (value: ProgressEvent) => void) {
    return this.requestHandler({
      url,
      methods: METHOD.POST,
      data,
    })
      .on("progress", onProgress || (() => {}))
      .then(this.resultSuccessCallback);
  }
  put(url, data?) {
    return this.requestHandler({
      url,
      methods: METHOD.PUT,
      data,
    }).then(this.resultSuccessCallback);
  }
  delete(url, data?) {
    return this.requestHandler({
      url,
      methods: METHOD.POST,
      data,
    }).then(this.resultSuccessCallback);
  }
}

let baseURL = "https://test-www.kube.ucas";

if (process.env.NODE_ENV === "development") {
  baseURL = "/saturn";
}

const request = new Request({ baseURL });

export default request;
