import axios, { AxiosResponse, AxiosRequestConfig } from 'axios';
import { Message } from 'element-ui';
import router from '@/router'
import METHOD from '../utils/methods'

/*
*http工具
*请求拦截器 负责将客户端标识token值存储并置放在头部提交给服务器
*响应拦截器 负责全局处理业务请求的网络或者业务错误
*/

//创建axios实例
const service = axios.create({
    // baseURL:"http://47.104.61.232:8902/ioc/",
    // baseURL:"http://192.168.1.104:8902/ioc/",
    baseURL:"http://" + METHOD.GlobalUrl + "/ioc/",
    timeout:30000, //超时时间
    headers:{
        // 'Content-Type':'application/x-www-form-urlencoded'
    }
})

//请求拦截
service.interceptors.request.use(
    (config: AxiosRequestConfig) => {
        let token = sessionStorage.getItem('token');
        if (token) {//如果已经登录 请求时加上token
            config.headers.Authorization = token;
        }
        else{
            if(config.url != '/account/login/'&&config.url != '/eventInfo/addOrEditEventInfo'){
                Message.error('未登录，即将返回登录页面！')
                router.push('/')
            }
        }
        return config;
    }, (err: any) => {
        Promise.reject(err);
    }
)

//响应拦截
service.interceptors.response.use(
    (response: AxiosResponse) => {
        let url = response.config.url;
        if( response.headers.authorization ) sessionStorage.setItem('token',response.headers.authorization);
        if(response.data.code == 0){
            if( url.indexOf('del') > -1 ){
                return response.data
            }
            return response.data.data;
        }else{
            Message.error(response.data.msg)
            return
        }
    },
    (err: any) => {
        let errMsg = "";
        if (err && err.response.status) {
            switch (err.response.status) {
                case 401:
                    errMsg = "登录状态失效，请重新登录"; break;
                    sessionStorage.removeItem('userData');
                    router.push('/login')
                case 404:
                    errMsg = "找不到请求接口！"; break;
                case 500:
                    errMsg = "服务端出错！"; break;
                case 404:
                    errMsg = "找不到请求接口！"; break;
                default:
                    errMsg = "请求出错！"
            }
        } else {
            errMsg = err
        }
        Message.error(errMsg)
        return Promise.reject(errMsg)
    }
)
export default service;

