import axios from 'axios'; // 引入axios
import { Message } from 'element-ui';
import { store } from '@/store/index'
import context from '@/main.js'
const secret = "017c0743819088468e590246464cc75f"
import md5 from 'js-md5'
const service = axios.create({
    baseURL: '',
    timeout: 99999
})
let acitveAxios = 0
let timer
const showLoading = () => {
    acitveAxios++
    if (timer) {
        clearTimeout(timer)
    }
    timer = setTimeout(() => {
        if (acitveAxios > 0) {
            context.$bus.emit("showLoading")
        }
    }, 400);
}

const closeLoading = () => {
        acitveAxios--
        if (acitveAxios <= 0) {
            clearTimeout(timer)
            context.$bus.emit("closeLoading")
        }
    }
    //http request 拦截器
service.interceptors.request.use(
    config => {
        if (!config.donNotShowLoading) {
            showLoading()
        }
        let  token = store.getters['user/token']||''
        const user = store.getters['user/userInfo']||{}
		
        config.data = JSON.stringify(config.data);
		let timestamp = Date.now()
		let urls = config.url.split("/")
		let action = urls[ urls.length -1].toLowerCase()
		let userId = user.id||0
		if(action == "login"){
			token = ""
			userId=0
		}
		let signstr=`admin_${token}_${action}_${timestamp}_${secret}`
		let signsure = md5( signstr )
        config.headers = {
            'Content-Type': 'application/json',
            'x-token': token,
            'x-signsure': signsure,
			'x-timestamp': timestamp,
			'x-userId': userId
        }
        return config;
    },
    error => {
        closeLoading()
        Message({
            showClose: true,
            message: error,
            type: 'error'
        })
        return error;
    }
);


//http response 拦截器
service.interceptors.response.use(
    response => {
        closeLoading()
        if (response.headers["new-token"]) {
            store.commit('user/setToken', response.headers["new-token"])
        }
		
        if (response.data.code == 200) {
            return response.data
        } else {
            Message({
                showClose: true,
                message: response.data.msg || decodeURI(response.headers.msg),
                type: response.headers.msgtype||'error',
            })
			if(response.data.code == 401){
				store.commit('user/LoginOut')
			}else if (response.data.data && response.data.data.reload) {
                store.commit('user/LoginOut')
            }
            return response.data.msg ? response.data : response
        }
    },
    error => {
        closeLoading()
        Message({
            showClose: true,
            message: error,
            type: 'error'
        })
        return error
    }
)

export default service