import axios from 'axios'
import router from '../router'
import { Toast } from 'vant';
import { Notify } from 'vant';
import { Dialog } from 'vant';
import { getToken, removeToken } from '@/utils/auth' // get token from cookie
const service = axios.create({
    timeout: 20000,
    // baseURL: '/aqpt/app-api', //前缀路径
    baseURL: '/app-api', //前缀路径
    headers: {//请求头部
        // "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
        "content-type": "application/json",
        "data-type": "json"
    }
})
//拦截接口请求
service.interceptors.request.use(config => {
    if (getToken()) {
        config.headers['Authorization'] = getToken()
    }
    return config
}, error => {
    return Promise.reject(error)
})
service.interceptors.response.use(response => {
    Toast.clear(); // 关闭之前的弹出信息
    const code = response.status//获取请求响应码
    const res = response.data//获取请求返回数据
    if (code == 200) {//请求响应码200 代表已经请求到接口
        if (res.code !== 0 && res.code !== 200 && res.code !== 402 && res.code !== 403 && res.code !== undefined) {
            if (res.code === 500 && res.msg == "运行时异常:token已过期,请重新登录") {
                Dialog.alert({
                    title: '提示',
                    message: res.msg,
                    theme: 'round-button',
                }).then(() => {
                    removeToken()
                    location.reload()
                });
            } else if (res.code === 401 && res.errorMessage == "图片类型错误") {
                Dialog.alert({
                    title: '提示',
                    message: res.errorMessage,
                    theme: 'round-button',
                }).then(() => {
                    router.go(-1);
                });
            } else if (res.code === 401) {
                Dialog.alert({
                    title: '提示',
                    message: '登录过期，请重新登录！',
                    theme: 'round-button',
                }).then(() => {
                    removeToken()
                    location.href = "/login"
                });
            } else {
                Toast.fail({
                    title: '提示',
                    forbidClick: true,
                    message: res.msg || '数据异常请稍后再试',
                })
            }
            return Promise.reject(res);
        } else {
            return res;
        }
    } else {
        Toast.fail({
            title: '提示',
            forbidClick: true,
            message: '接口请求失败',
        })
    }
}, err => {
    Toast.fail('接口请求失败');
    return Promise.reject(err)
})

export default service
