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";

const http = axios.create({
	timeout: 1000 * 50,
	withCredentials: true,
	headers: {
	  'Content-Type': 'application/json; charset=utf-8'
	}
})

axios.defaults.withCredentials = true;
axios.defaults.changeOrigin = true;


http.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);
    }
);

// 添加响应拦截器
http.interceptors.response.use(
    (response) => {
        NProgress.done();
        console.log('添加响应拦截器'+response);
        const res = response.status;
        // 对响应数据做点什么
        if (res === 200 || res === 201) {
            return response.data
        }
    },
    (error) => {
        console.log(error.response);
        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);
    }
);
http.adornParams = (params = {}, openDefultParams = false) => {
	var defaults = {
		't': new Date().getTime()
	}
	return openDefultParams ? merge(defaults, params) : params
}

http.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)
}
http.adornUrl = (actionName) => {
	if (process.env.VUE_APP_API_NODE !== 'production' && process.env.VUE_APP_API_PROXY_PREFIX) {
        return process.env.VUE_APP_API_PROXY_PREFIX+`${actionName}`
	} else {
		process.env.VUE_APP_BASE_URL + actionName
	}
}
http.get = (url, query) => {
	return http({
		url: http.adornUrl(url),
		method: 'get',
		params: query
	})
}

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