import axios, { AxiosInstance } from 'axios';
import { IHttpResponse } from "./IHttpResponse";
import { RequestBodyType } from "../../enums/RequestBodyType";
import { HttpMethodType } from "../../enums/HttpMethodType";
import { ServiceClientConfig } from "../../config/ServiceClientConfig";


export class SimpleHttpUtil {

    private readonly axios: AxiosInstance;
    private readonly serviceClientConfig: ServiceClientConfig;

    constructor(serviceClientConfig: ServiceClientConfig) {
        this.serviceClientConfig = serviceClientConfig;
        this.axios = axios.create({
            timeout: serviceClientConfig.requestTimeout || 5000
        });
        serviceClientConfig.configAxiosInterceptors(this.axios.interceptors.request, this.axios.interceptors.response)
    }

    async request(method: HttpMethodType, url: string, params: {}, data: object, headers: {}, bodyType: RequestBodyType): Promise<IHttpResponse> {
        let config = {}, requestBody = data || {}
        config['url'] = url;
        config['headers'] = headers;
        config['headers']['content-type'] = 'application/x-www-form-urlencoded;charset=utf-8';
        if (bodyType == RequestBodyType.RAW_JSON) {
            config['headers']['content-type'] = 'application/json;charset=utf-8';
        }
        config["method"] = method.toLowerCase();
        config["params"] = params;
        config["data"] = requestBody;
        const response: IHttpResponse = await this.axios.request(config);
        return response
    }


    /**
     * 文件上传
     * @param url
     * @param files
     * @param headers
     * @param config
     */
    async upload(url: string, data: object = {}, formData: FormData, headers: object = {}) {
        for (let attr in data) {
            formData.append(attr, data[attr])
        }
        let config = {}
        config['headers'] = headers;
        const response: IHttpResponse = await this.axios.post(url, formData, config);
        return response
    }
}