import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'
import router from "@/router"; //看具体项目封装的路由文件修改

// create an axios instance
const service = axios.create({
    // baseURL: process.env.VUE_APP_BASE_API, 
baseURL: 'http://127.0.0.1:8898/api', 
    timeout: 5000 
})

//跳转登陆页面
const toLogin = () => {
    // 执行退出操作
    store.dispatch('user/logout').then(() => {
        // 返回登录页面
        router.push('/login')
    })
};


//封装状态码错误处理函数
const errorHandle = status => {
    switch (status) {
        //登录不成功时跳转到登录页面
        case 401:
            console.log("认证失败,未登录或无权限");
            toLogin();
            break;
        case 403:
            //token过期了,清除token存储
            localStorage.removeItem("token");
            console.log("token校验失败");
            toLogin();
            break;
        case 404:
            console.log("请求的资源不存在");
            break;
        default:
            console.log("请求出错,状态码为:" + status);
            break;
    }
};
// request interceptor
service.interceptors.request.use(
    config => {
        // do something before request is sent

        if (store.getters.token) {
            // let each request carry token
            // ['X-Token'] is a custom headers key
            // please modify it according to the actual situation
            config.headers['Authorization'] = getToken(); // 携带token
            config.headers['Content-Type'] = 'application/x-www-form-urlencoded'
                // config.headers['Username'] = getUsername();  // 携带token
            return config;
        }
        return config
    },
    error => {
        // do something with request error
        console.log(error) // for debug
        return Promise.reject(error)
    }
)

// response interceptor
service.interceptors.response.use(
    /**
     * If you want to get http information such as headers or status
     * Please return  response => response
     */

    /**
     * Determine the request status by custom code
     * Here is just an example
     * You can also judge the status by HTTP Status Code
     */
    response => {
        const res = response.data
        console.log(res.status); // 添加此行
        if (res.status == 401) {
            toLogin()
        }
        // if the custom code is not 20000, it is judged as an error.   
        if (res.status !== 20000 && res.status !== 200 && res.status !== 201) {
            Message({
                message: res.message || 'Error',
                type: 'error',
                duration: 5 * 1000
            })

            // 50008: Illegal token; 50012: Other clients logged in; 50014: Token expired;
            if (res.status === 50008 || res.status === 50012 || res.status === 50014) {
                // to re-login
                MessageBox.confirm('You have been logged out, you can cancel to stay on this page, or log in again', 'Confirm logout', {
                    confirmButtonText: 'Re-Login',
                    cancelButtonText: 'Cancel',
                    type: 'warning'
                }).then(() => {
                    store.dispatch('user/resetToken').then(() => {
                        location.reload()
                    })
                })
            }
            return Promise.reject(new Error(res.message || 'Error'))
        } else {
            return res
        }
        // const data = response.data;
        // // console.log(data);
        // // 不为0，即接口异常时
        // if (data.resCode !== 0) {
        //   Message.error(data.message);
        //   return Promise.reject(data);
        // } else {
        //   return data; // return Promise.resolve(data);
        // }
    },
    error => {
        // let { response } = error;
        //判断是否为重复请求而出错
        // if (isCancel(error)) console.log("请求失败,原因是" + error.message);
        if (error.response) {
            errorHandle(error.response.status);

        }
        //判断客户端有无联网
        if (!window.navigator.onLine) {
            //断网处理：跳转断网页面/提示网络错误等等
            alert("请检查网络是否连接");
        }
        //出错中断promise链
        // return new Promise(() => {});
        console.log('err' + error) // for debug
        Message({
            message: error.message,
            type: 'error',
            duration: 5 * 1000
        })
        return Promise.reject(error)
    }
)

export default service