import axios, {InternalAxiosRequestConfig, AxiosResponse} from "axios";
import {getToken, setToken, removeToken} from '@/utils/js-cookie'
import {ElMessage, ElMessageBox} from "element-plus";
// 创建 axios 实例
const service = axios.create({
    baseURL: import.meta.env.VITE_APP_BASE_API,
    timeout: 50000,
    headers: {"Content-Type": "application/json;charset=utf-8"},
});

// 请求拦截器
service.interceptors.request.use(
    (config: InternalAxiosRequestConfig) => {
        config.headers['X-ERP-User-From'] = 10;
        if (getToken('token')) {
            config.headers['X-Token'] = getToken('token');
        }
        if (getToken('dataBaseAlias')) {
            config.headers['X-ERP-DataSource-Id'] = getToken('dataSourceId');
        }
        if (getToken('shardingKey')) {
            config.headers['X-ERP-Supplier-Code'] = getToken('supplierCode');
        }
        return config;
    },
    (error: any) => {
        return Promise.reject(error);
    }
);

// 响应拦截器
service.interceptors.response.use(
    (response: AxiosResponse) => {
        const res = response.data
        // console.log(res);
        if (res.httpCode !== 200 && res.httpCode != undefined) {
            ElMessage({
                message: res.msg || res.data,
                type: 'error',
                duration: 5 * 1000,
                showClose: true,
            })
            // if (res.httpCode === 403 || res.httpCode === 401 || res.httpCode === 50014) {
            //     // to re-login
            //     ElMessageBox.confirm('您已注销，可以取消以留在此页，或重新登录', '确认？', {
            //         confirmButtonText: '重新登录',
            //         cancelButtonText: '取消',
            //         type: 'warning'
            //     }).then(() => {
            //         location.reload()
            //     })
            // }
            return Promise.reject(res)
        } else {
            return res
        }
    },
    (error: any) => {
        console.log('err' + error) // for debug
        return Promise.reject(error)
    }
);

// 导出 axios 实例
export default service;
