import axios from "axios";
import { getToken } from "@/util/auth";
import NProgress from "nprogress";
import "nprogress/nprogress.css";
import qs from 'qs'
import merge from 'lodash/merge'
import { Message } from "element-ui";
var instance = axios.create({
    timeout: 360000,
    headers: {
        'Content-Type': 'application/json; charset=utf-8',
        'Access-Control-Allow-Origin': '*',
    }
});

instance.interceptors.request.use(
    (config) => {
        // config.headers['content-type'] = 'application/json'

        // config.headers['Shop-Id'] = localStorage.getItem('shopId') || 1

        // 在发送请求之前做些什么
        // config.headers['content-type'] = 'application/json'
        config.headers.Authorization = "Bearer " + getToken(); // 请求头
        NProgress.start();
        return config;
    },
    (error) => {
        // 对请求错误做些什么
        return Promise.reject(error);
    }
);

// 添加响应拦截器
instance.interceptors.response.use(
    (response) => {
        NProgress.done();
        const res = response.status;
        // 对响应数据做点什么
        if (res === 200 || res === 201) {
            return response;
        }
    },
    (error) => {
        NProgress.done();
        // 对响应错误做点什么
        if (error.response.status === 400) {
            Message({
                message: error.response.data.errorMessage,
                type: "error",
            });
        }

        if (error.response.status === 500) {
            Message({
                message: error.response.data.message,
                type: "error",
            });
        }
        return Promise.reject(error);
    }
);
instance.adornParams = (params = {}, openDefultParams = false) => {
	var defaults = {
		't': new Date().getTime()
	}
	return openDefultParams ? merge(defaults, params) : params
}

instance.adornData = (data = {}, openDefultdata = false, contentType = 'json') => {
	var defaults = {
		't': new Date().getTime()
	}
	data = openDefultdata ? merge(defaults, data) : data
	return contentType === 'json' ? JSON.stringify(data) : qs.stringify(data)
}
instance.adornUrl = (actionName) => {
	//return (process.env.NODE_ENV !== 'production' && process.env.OPEN_PROXY ? 'proxyApi/' : process.env.VUE_APP_URL) + actionName
	if (process.env.VUE_APP_API_NODE !== 'production' && process.env.VUE_APP_API_PROXY_PREFIX) {
        console.log(111111111);
		return `${actionName}`
	} else {
        console.log(111111111);
		env.VUE_APP_BASE_URL + actionName
	}
}
instance.get = (url, query) => {
	return instance({
		url: instance.adornUrl(url),
		method: 'get',
		params: query
	})
}

instance.post = (url, data = {}) => {
	return instance({
		url: instance.adornUrl(url),
		method: 'post',
		data: data
	})
}
export default instance;
