
import axios from 'axios';
import { ElMessage, ElMessageBox, ElLoading } from 'element-plus';
import { nextTick } from "vue";
import {baseURL, socketURL} from './config';
import JSONBIG from 'json-bigint';
// 配置新建一个 axios 实例
var loading = null;
const service = axios.create({
    baseURL: baseURL,
    timeout: 20000,
    withCredentials: false,
    headers: { 'Content-Type': 'application/json' },
    transformResponse: [
        function (data) {
            const json = JSONBIG({
                storeAsString: true
            });
            const res = json.parse(data);
            return res;
        }
    ],
    showLoading: {
        statu: true,
        text: '加载中...'
    }
});

// 添加请求拦截器
service.interceptors.request.use(
    (config) => {
        if (config.showLoading.statu) {
            loading = ElLoading.service({
                lock: true,
                text: config.showLoading.text,
                spinner: 'el-icon-loading',
                background: 'rgba(0, 0, 0, 0.3)'
            });
        }
        // 在发送请求之前做些什么 token
        // let token = sessionStorage.getItem('token')
        // if (token) {
        //     config.headers.common['token'] = token;
        // }
        config.headers.common['Authorization'] = 'Basic cm9vdDp0YW9zZGF0YQ=='
        return config
    },
    (error) => {
        // 对请求错误做些什么
        return Promise.reject(error);
    }
);

// 添加响应拦截器
service.interceptors.response.use(
    (response) => {
        // 对响应数据做点什么
        nextTick(async () => {
            loading && await loading.close()
        })
        const res = response.data;
        console.warn(res);
        if (response.status === 401 || response.status === 4001 || response.status == 521) {
            sessionStorage.clear(); // 清除浏览器全部临时缓存
            window.location.href = '/'; // 去登录页
            ElMessage.error(res.msg)
        } else {
            if(response.status === 200 && res.code &&  res.code !== 200){
                ElMessage.error(res.msg)
            }
            return response.data;
        }
    },
    (error) => {
        nextTick(async () => {
            loading && await loading.close()
        })
        // 对响应错误做点什么
        if (error.message.indexOf('timeout') != -1) {
            // ElMessage.error('网络超时');
        } else if (error.message == 'Network Error') {
            // ElMessage.error('网络连接错误');

        } else {
            if (error.response.data) ElMessage.error(error.response.statusText);
            // else ElMessage.error('接口路径找不到');
        }
        return Promise.reject(error);
    }
);

// 导出 axios 实例
export default service;
export {
    baseURL,
    socketURL
}