import axios from 'axios'
import {VueAxios} from './axios'
import {Toast} from 'vant'

// 创建 axios 实例
const service = axios.create({
    baseURL: '/happyjob', // api base_url
    timeout: 15000 // 请求超时时间
})

const err = (error) => {
    if (error.response) {
        let data = error.response.data;
        switch (error.response.status) {
            case 403:
                Toast('拒绝访问');
                break;
            case 500:
                Toast('很抱歉，登录已过期，请重新登录');
                this.$router.go(0);
                break;
            case 502:
                Toast('很抱歉，服务器正在维护');
                this.$router.go(0);
                break;
            case 404:
                Toast('很抱歉，资源未找到!');
                break;
            case 504:
                Toast('网络超时');
                break;
            case 401:
                Toast('未授权，请重新登录');
                setTimeout(() => {
                    this.$router.go(0);
                }, 1500)
                break
            default:
                Toast(data.errmsg);
                break
        }
    }
    return Promise.reject(error)
};

// request interceptor
service.interceptors.request.use(config => {
    // const token = Vue.ls.get(ACCESS_TOKEN)
    // if (token) {
    //   config.headers[ 'X-Access-Token' ] = token // 让每个请求携带自定义 token 请根据实际情况自行修改
    // }
    Toast.loading({
        message: '加载中...',
        forbidClick: true,
    })
    return config
}, (error) => {
    return Promise.reject(error)
})

// response interceptor
service.interceptors.response.use((response) => {
    Toast.clear()
    if (response.data.errcode === 0) {
        return response.data
    } else {
        switch (response.data.errcode) {
            case 3001:
                Toast('企业未注册');
                break;
            case 3002:
                // Toast('用户未注册');
                break;
            case 3003:
                Toast('用户未被邀请');
                break;
            case 3004:
                Toast('该手机号已存在企业');
                break;
            case 3005:
                Toast('该手机号已存在用户');
                break;
            default:
                Toast(response.data.errmsg || response.data.errsg);
                break;
        }
        return Promise.reject(response.data)
    }
}, err);

const installer = {
    vm: {},
    install(Vue, router = {}) {
        Vue.use(VueAxios, router, service)
    }
};

export {
    installer as VueAxios,
    service as axios
}
