import axios from 'axios'
import {BASE_API} from '/public/config/server.js'
import router from '../router/index.js'
import {ElMessage, ElMessageBox} from 'element-plus'
// import store from '../store'
// import { getToken } from '@/utils/auth'

// 创建axios实例
const service = axios.create({
    // baseURL: process.env.VUE_APP_BASE_API, // api的base_url
    baseURL: BASE_API + "/api",
    // baseURL:"http://192.168.10.123:9272/api",
    timeout: 50000, // 请求超时时间
    withCredentials: false,
})

// request拦截器
service.interceptors.request.use(config => {

    config.headers['Authorization'] = 'Bearer ' + localStorage.getItem("Token");
    config.headers['Content-Type'] = 'application/json;charset=UTF-8'
    config.headers['X-Token'] = localStorage.getItem("Token");
    return config
}, error => {
    // Do something with request error
    console.log(error) // for debug
    Promise.reject(error)
})

// respone拦截器
service.interceptors.response.use(response => {
        /**
         * code为非200是抛错 可结合自己业务进行修改
         */
        const res = response.data
        if (res.code !== 200) {
            // 50008:非法的token; 50012:其他客户端登录了;  50014:Token 过期了;
            if (res.code === 50008 || res.code === 50012 || res.code === 50014 || res.code == 401) {

            } else {
                // Message({
                //   message: res.message || res.msg,
                //   type: 'error',
                //   duration: 5 * 1000
                // })
            }
            return Promise.reject('error')
        } else {

            return response.data
        }
    },
    error => {
        console.log(error)
        if (String(error) === 'Error: Request failed with status code 401') {
            router.replace({
                path: '/login',
                // query: { redirect: router.currentRoute.fullPath }
            })

            // ElMessageBox.confirm('未登录用户，可以【取消】继续留在该页面，或者点击【登录】', '登录提醒', {
            //     confirmButtonText: '登录',
            //     cancelButtonText: '取消',
            //     type: 'warning'
            // }).then(() => {
            //     localStorage.setItem("Token", "");
            //     router.replace({
            //         path: '/',
            //         // query: { redirect: router.currentRoute.fullPath }
            //     })
            // })
            // console.log('response' + error)// for debug

        }

        return Promise.reject(error)
    }
)

export default service
