import axios from "axios";
import { Loading } from "element-ui";
import Cookies from "js-cookie";
const { getSetting } = window.systemParamsUtils;
console.log("BASE_API:" + getSetting("BASE_API"));
let loadingMap = {};
let loadingShow = function(config) {
    if (!config["loading"]) {
        return;
    }
    let loading = Loading.service({
        lock: true,
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.8)",
        text: "数据加载中..."
    });
    config.uuid = new Date().getTime() + "=" + config.url;
    loadingMap[config.uuid] = loading;
};
let loadingHide = function(config) {
    if (!config["loading"]) {
        return;
    }
    loadingMap[config.uuid] && loadingMap[config.uuid].close();
    delete loadingMap[config.uuid];
};
// create an axios instance
const service = axios.create({
    baseURL: getSetting("BASE_API"), // api 的 base_url
    timeout: getSetting("REQ_TIMEOUT") || 5000 // request timeout
});
// request interceptor
service.interceptors.request.use(
    config => {
        // Do something before request is sent
        config = window.loginUtil.beforeRequest(config);
        config.headers["X-Requested-With"] = "XMLHttpRequest";
        config.headers['userToken'] = Cookies.get('_idp_session') || null,
        loadingShow(config);

        return config;
    },
    error => {
        // Do something with request error
        console.log(error); // for debug
        Promise.reject(error);
    }
);

// response interceptor
service.interceptors.response.use(
    response => {
        loadingHide(response.config);
        response = window.loginUtil.afterResponseSuccess(response);
        return response;
    },
    error => {
        error = window.loginUtil.afterResponseFailed(error);
        if (error && error.config) {
            loadingHide(error.config);
        }
        console.log("err" + error); // for debug
        return Promise.reject(error);
    }
);

export default service;
