import axios from 'axios'
import { getToken } from '@/utils/setToken.js'
import { Message, Loading } from 'element-ui'
const service = axios.create({
    // baseURL: '/api', //baseURL会自动加在请求地址上
    timeout: 5000
})
// 添加请求拦截器
service.interceptors.request.use((config) => {
    // 在请求之前做些什么（获取并设置token）
    if (config.isLoading) {
        startLoading()
    }
    config.headers['token'] = getToken('token')
    return config
}, (error) => {
    return Promise.reject(error)
})

// 添加响应拦截器
service.interceptors.response.use((response) => {
    // 在响应数据做些什么（获取并设置token）
    if (response.config.isLoading) {
        endLoading();
    }
    const res = response.data
    if (res.code == 1) {
        return res
    } else if( res.code === 0) {
        // Message({
        //     message: res.msg || 'Error',type: 'error',duration: 5 * 1000
        // })
    } else if (res.code === 401) {
        localStorage.clear()
        Message({
            message: '登录信息过期，请重新登录',type: 'error',duration: 3 * 1000,
            onClose: () => {
                window.location.href = '/'
            }
        })
    } else if (res.code === 402) {
        Message({
            message: '暂无权限访问或操作该页面',type: 'error',duration: 3 * 1000,
        })
    }
    return res
}, (error) => {
    Message({
        message: '系统错误',
        type: 'error',
        duration: 3 * 1000
    })
    endLoading();
    return Promise.reject(error)
})

let loading
function startLoading() {
    loading = Loading.service({
        lock: true,
        text: '加载中',
        background: 'rgba(0, 0, 0, 0.7)'
    })
}
function endLoading() {
    loading.close()
}
const request = (url, method = 'get', data, isLoading = false) => {
    const config = {}
    if (data) {
        if (method === 'get') {
            config.params = data
        } else {
            config.data = data
        }
    }

    return service({
        url,
        method,
        isLoading,
        ...config
    })
}
export default request
