import axios, { AxiosInstance, AxiosResponse } from 'axios';
import { StringUtils } from 'refs/cm-tools'
const querystring = require('querystring');

/**
 * 基于Axios框架实现的Http工具
 * @author wufl2019@qq.com
 * @date 2020-06-23
 */
export class HttpUtils {

    private readonly axios: AxiosInstance;

    constructor(_timeout: number = 5000) {
        this.axios = axios.create({
            timeout: _timeout
        });
    }

    /**
     * @desc get请求
     * @param {String} path 请求api路径
     * @param {Object} data 参数对象
     * @param {Object} config 局部配置 {headers: {'X-Custom-Header': 'foobar'}}
     */
    async get(url: string, data: object = {}, headers: object = {}): Promise<AxiosResponse> {
        if(StringUtils.isEmpty(url)){
            throw Error('url can not empty !!')
        }
        let config = {}
        config['headers'] = headers
        const response: AxiosResponse = await this.axios.get(url, {
            params: data,
            ...config
        })
        return response
    }

    /**
     * @desc post表单请求
     * @param {String} path 请求api路径
     * @param {Object} data 参数对象
     * @param {Object} config 局部配置 {headers: {'X-Custom-Header': 'foobar'}}
     */
    async postForm(url: string, data: any = {}, headers: object = {}): Promise<AxiosResponse> {
        let config = {}
        config['headers'] = headers;
        config['headers']['content-type'] = 'application/x-www-form-urlencoded;charset=utf-8';
        const response: AxiosResponse = await this.axios.post(url, querystring.encode(data), config);
        return response
    }

    /**
     * @desc post表单请求
     * @param {String} path 请求api路径
     * @param {Object} data 参数对象
     * @param {Object} config 局部配置 {headers: {'X-Custom-Header': 'foobar'}}
     */
    async postJson(url: string, params: any = {}, bodyObj: object = {}, headers: object = {}): Promise<AxiosResponse> {
        let config = {}, requestUrl = url
        config['headers'] = headers;
        config['headers']['content-type'] = 'application/json;charset=utf-8';
        if (params && Object.keys(params).length) {
            requestUrl = requestUrl + '?' + querystring.encode(params)
        }
        const response: AxiosResponse = await this.axios.post(requestUrl, bodyObj, config);
        return response
    }
    
    /**
     * @desc post表单请求
     * @param {String} path 请求api路径
     * @param {Object} data 参数对象
     * @param {Object} config 局部配置 {headers: {'X-Custom-Header': 'foobar'}}
     */
    async post(url: string, data: any = {}, headers: object = {}, contentType: string): Promise<AxiosResponse> {
        let config = {}
        config['headers'] = headers;
        config['headers']['content-type'] = contentType;
        const response: AxiosResponse = await this.axios.post(url, data, config);
        return response
    }

}

export default new HttpUtils()