import axios, {AxiosInstance} from 'axios';
import {ElLoading, ElMessage, ElMessageBox} from 'element-plus';
import {Session} from '/@/utils/storage';
import qs from 'qs';

// @ts-ignore
let loadingInstance: ElLoading = null;

let url = import.meta.env.VITE_API_URL;
if (!url) {
    url = `${location.origin}/admin/`;
}
// 配置新建一个 axios 实例
const service: AxiosInstance = axios.create({
    baseURL: url,
    timeout: 50000,
    headers: {'Content-Type': 'application/json'},

    paramsSerializer: {
        serialize(params) {
            return qs.stringify(params, {allowDots: true});
        },
    },
});

// 添加请求拦截器
service.interceptors.request.use(
    (config) => {
        // 在发送请求之前做些什么 token
        if (Session.get('accessToken')) {
            config.headers!['accessToken'] = `${Session.get('accessToken')}`;
        }
        return config;
    },
    (error) => {
        // 对请求错误做些什么
        return Promise.reject(error);
    }
);

// 添加响应拦截器
service.interceptors.response.use(
    (response) => {
        // 对响应数据做点什么
        const res = response.data;
        // //console.log(res)
        if (res.code && res.code !== 0) {
            // `token` 过期或者账号已在别处登录
            if (res.code === 401) {
                Session.clear(); // 清除浏览器全部临时缓存
                ElMessageBox.alert('你已被登出，请重新登录', '提示', {})
                    .then(() => {
                        window.location.href = '/'; // 去登录页
                    })
                    .catch(() => {
                        window.location.href = '/'; // 去登录页
                    });
                return Promise.reject(service.interceptors.response);
            } else if (res.code === 200) {
                return response.data;
            } else {
                ElMessage.error(res.msg||res.message || '系统繁忙，请稍后再试！');
                return Promise.reject(res.msg||res.message  || '系统繁忙，请稍后再试！');
            }
        } else {
            return response.data;
        }
    },
    (error) => {
        // //console.error(error)
        // 对响应错误做点什么
        if (error.message.indexOf('timeout') != -1) {
            ElMessage.error('网络超时');
        } else if (error.message == 'Network Error') {
            ElMessage.error('网络连接错误');
        } else if (error.message.includes("404")) {
            ElMessage.error('接口不存在');
        } else {
            if (error.response.data) {
                ElMessage.error(error.response.data.message || error.response.statusText);
                return Promise.reject(error.response.data.message || error.response.statusText);
            } else {
                ElMessage.error('接口路径找不到');
            }
        }
        return Promise.reject(error);
    }
);


export function $put(url: string, data = {}, showLoading = false) {
    if (showLoading) {
        loadingInstance = ElLoading.service({fullscreen: true})
    }
    return new Promise((resolve, reject) => {
        service.put(url, data)
            .then(response => {
                if (showLoading) {
                    loadingInstance.close();
                }
                resolve(response.data);
            }, err => {
                // ////if(showLoading)Spin.hide();
                reject(err)
            })
    })
}

export function $patch(url: string, data = {}, showLoading = false) {
    //if(showLoading)Spin.show();
    return new Promise((resolve, reject) => {
        service.patch(url, data)
            .then(response => {
                ////if(showLoading)Spin.hide();
                resolve(response.data);
            }, err => {
                ////if(showLoading)Spin.hide();
                reject(err)
            })
    })
}

export function $get(url: string, params = {}, showLoading = false) {
    //if(showLoading)Spin.show();
    return new Promise((resolve, reject) => {
        service.get(url, {
            params: params
        }).then(response => {
            ////if(showLoading)Spin.hide();
            resolve(response.data);
        }).catch(err => {
            //console.error("err=>" + err)
            ////if(showLoading)Spin.hide();
            reject(err)
        })
    })
}

export function $post(url: string, data = {}, showLoading = false) {
    //if(showLoading)Spin.show();
    return new Promise((resolve, reject) => {
        service.post(url, data, {
            headers: {"Content-Type": "application/x-www-form-urlencoded;charset=UTF-8;"}
        })
            .then(response => {
                ////if(showLoading)Spin.hide();
                resolve(response.data);
            }, err => {
                //console.error("err=>" + err)
                ////if(showLoading)Spin.hide();
                reject(err)
            })
    })
}

export function $body(url: string, data = {}, showLoading = false) {
    //if(showLoading)Spin.show();
    return new Promise((resolve, reject) => {
        service.post(url, data)
            .then(response => {
                ////if(showLoading)Spin.hide();
                resolve(response.data);
            }, err => {
                ////if(showLoading)Spin.hide();
                reject(err)
            })
    })
}

export function $upload(url: string, formData = {}, showLoading = false) {
    //if(showLoading)Spin.show();
    return new Promise((resolve, reject) => {
        service.post(url, formData, {
            headers: {'Content-Type': 'multipart/form-data'}
        }).then(response => {
            ////if(showLoading)Spin.hide();
            resolve(response.data);
        }, err => {
            ////if(showLoading)Spin.hide();
            reject(err)
        })
    })
}

// 导出 axios 实例
// export default {service,$post:post,$get:get,$upload:upload,$put:put,$body:body};
