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:60018/danger/",
	baseURL:METHOD.URL,
    // baseURL:"http://192.168.1.104:60018/danger/",
    timeout: 10000, //超时时间
    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/'){
        //         Message.error('未登录，即将返回登录页面！')
        //         router.push('/')
        //     }
        // }
        return config;
    }, (err: any) => {
        Promise.reject(err);
    }
)

//响应拦截
service.interceptors.response.use(
    (response: AxiosResponse) => {
        if (response.headers.authorization) sessionStorage.setItem('token', response.headers.authorization);
        if (response.data.code != 0) {
            Message.error(response.data.msg)
        }
        return response.data;
    },
    (error) => {
        if( error.response ){
            Message.error( '错误状态码' + error.response.status)
        }else{
            Message.error('NetWork Error!')
        }
        return Promise.reject(error)
    }
)
export default service;

