import axios from 'axios';
import { stringify } from 'query-string';
import { isArray, map, omit } from 'lodash';
import noDataFilter from './noDataFilter';
import { getStorage, getToken } from './store';
const error = { code: 999, message: '服务器异常!', success: false };
class Request {
    constructor(config) {
        var _a, _b, _c, _d, _e, _f;
        // 	创建axios实例
        this.instance = axios.create(config);
        // 默认配置
        this.instance.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
        // 	传入拦截器
        this.interceptorsObj = config.interceptors;
        // 3.此处为了多个config传入不同的拦截器
        if ((_a = this.interceptorsObj) === null || _a === void 0 ? void 0 : _a.requestInterceptors) {
            this.instance.interceptors.request.use((_b = this.interceptorsObj) === null || _b === void 0 ? void 0 : _b.requestInterceptors, (_c = this.interceptorsObj) === null || _c === void 0 ? void 0 : _c.requestInterceptorsCatch);
        }
        else {
            //  default
            // Add a request interceptor
            this.instance.interceptors.request.use(function (config) {
                if (getToken()) {
                    config.headers.token = getToken();
                }
                return config;
            }, function (error) {
                // Do something with request error
                return Promise.reject(error);
            });
        }
        if ((_d = this.interceptorsObj) === null || _d === void 0 ? void 0 : _d.responseInterceptors) {
            this.instance.interceptors.response.use((_e = this.interceptorsObj) === null || _e === void 0 ? void 0 : _e.responseInterceptors, (_f = this.interceptorsObj) === null || _f === void 0 ? void 0 : _f.responseInterceptorsCatch);
        }
        else {
            // default
            this.instance.interceptors.response.use(function (response) {
                const { data, status } = response;
                if (Number(status) === 200) {
                    return data;
                }
                return error;
            });
        }
        this.requestPost = this.requestPost.bind(this);
        this.requestTableList = this.requestTableList.bind(this);
        this.requestGet = this.requestGet.bind(this);
        this.requestExport = this.requestExport.bind(this);
        this.requestOptions = this.requestOptions.bind(this);
        this.requestTreeOptions = this.requestTreeOptions.bind(this);
    }
    request(config) {
        return new Promise((resolve, reject) => {
            var _a;
            // 单个请求设置拦截器在这里
            if ((_a = config.interceptors) === null || _a === void 0 ? void 0 : _a.requestInterceptors) {
                this.instance.interceptors.request.use(config.interceptors.requestInterceptors);
            }
            this.instance
                .request(config)
                .then(res => {
                var _a;
                // 接口数据响应处理
                if ((_a = config.interceptors) === null || _a === void 0 ? void 0 : _a.responseInterceptors) {
                    res = config.interceptors.responseInterceptors(res);
                }
                resolve(res);
            })
                .catch((err) => {
                // 向上抛出错误
                reject(err);
            });
        });
    }
    /**
     * 发起post请求
     * @param baseURL
     * @param url
     * @param params
     * @return {Promise<AxiosResponse<any>>}
     */
    requestPost(baseURL, url, params) {
        const options = {
            baseURL,
            url,
            data: Object.assign({}, noDataFilter(params)),
            method: 'post',
            withCredentials: false,
            transformRequest: [
                function (data) {
                    return stringify(data, {
                        strict: false,
                    });
                },
            ],
        };
        return this.instance(options).then((result) => {
            if (result.code === 0 && result.success) {
                return Object.assign(Object.assign({}, result), { type: 'success' });
            }
            else {
                return Object.assign(Object.assign({}, result), { type: 'error' });
            }
        });
    }
    /**
     *获取table列表数据
     * @param baseURL
     * @param url
     * @param params
     * @return {success:true,total:'100',data:'[]'}
     */
    requestTableList(baseURL, url, params) {
        const _params = Object.assign({}, params);
        if (_params === null || _params === void 0 ? void 0 : _params.current) {
            _params.pageNum = _params.current;
            Reflect.deleteProperty(_params, 'current');
        }
        const options = {
            baseURL,
            url,
            params: _params,
            method: 'get',
            withCredentials: false,
        };
        return this.instance(options)
            .then((result) => {
            var _a;
            if (!result) {
                return null;
            }
            if (result.code === 0) {
                if (isArray(result.data)) {
                    return {
                        data: result.data,
                        total: result.data.length,
                        success: true,
                    };
                }
                return {
                    success: true,
                    total: ((_a = result === null || result === void 0 ? void 0 : result.data) === null || _a === void 0 ? void 0 : _a.total) || 0,
                    data: result.data.rows,
                };
            }
            else {
                return null;
            }
        })
            .catch(() => {
            return null;
        });
    }
    /**
     *
     * @param baseURL
     * @param url
     * @param params
     */
    requestGet(baseURL, url, params) {
        const options = {
            baseURL,
            url,
            params: Object.assign({}, noDataFilter(params)),
            method: 'get',
            withCredentials: false,
        };
        return this.instance(options).then((result) => {
            if (result.code === 0 && result.success) {
                return result.data;
            }
            else {
                return null;
            }
        });
    }
    /**
     *
     * @param baseURL
     * @param url
     * @param params
     */
    requestExport(baseURL, url, params) {
        const options = {
            baseURL,
            url,
            params: Object.assign({}, noDataFilter(params)),
            method: 'get',
            responseType: 'blob',
        };
        return this.instance(options);
    }
    /**
     *
     * @param api
     * @param path
     * @param params
     * @param keys
     * @return {Promise<[{label:'',value:''}]>}
     */
    requestOptions(baseURL, url, params, keys) {
        const options = {
            baseURL,
            url,
            params: Object.assign({}, noDataFilter(params)),
            method: 'get',
            withCredentials: false,
        };
        const value = keys[0];
        const label = keys[1];
        return this.instance(options)
            .then((result) => {
            if (result.code === 0 && result.success) {
                if (isArray(result.data)) {
                    return map(result.data, (item) => {
                        return Object.assign(Object.assign({}, omit(item, keys)), { value: item[value], label: item[label] });
                    });
                }
            }
            return null;
        })
            .catch(() => {
            return null;
        });
    }
    /**
     *
     * @param baseURL
     * @param url
     * @param params
     * @param keys
     */
    requestTreeOptions(baseURL, url, params, keys) {
        const options = {
            baseURL,
            url,
            params: Object.assign({}, noDataFilter(params)),
            method: 'get',
            withCredentials: false,
        };
        return this.instance(options)
            .then((result) => {
            if (result.code === 0 && result.success) {
                if (isArray(result.data)) {
                    return this.convertTree(result.data, keys);
                }
            }
            return null;
        })
            .catch(() => {
            return null;
        });
    }
    /**
     *
     * @param menu
     * @param keys
     */
    convertTree(menu, keys) {
        try {
            const pid = keys[0];
            const value = keys[1];
            const title = keys[2];
            const children = keys[3] || 'children';
            const convertMenu = (list, parent) => {
                if (list.length < 2) {
                    return list.map((item) => (Object.assign(Object.assign({}, item), { title: item[title], value: item[value], pid: item[pid] })));
                }
                return list
                    .filter((item) => {
                    if (item[pid] === parent) {
                        item[children] = convertMenu(list, item[value]);
                        return true;
                    }
                    return false;
                })
                    .map((item) => (Object.assign(Object.assign({}, item), { title: item[title], value: item[value], pid: item[pid] })));
            };
            return convertMenu(menu, String(getStorage('parentId')));
        }
        catch (error) {
            console.log(error);
        }
    }
}
const request = new Request({});
const requestPost = request.requestPost;
const requestTableList = request.requestTableList;
const requestGet = request.requestGet;
const requestExport = request.requestExport;
const requestOptions = request.requestOptions;
const requestTreeOptions = request.requestTreeOptions;
export { requestPost, requestTableList, requestGet, requestExport, requestOptions, requestTreeOptions };