import axios from "axios";
import { useUserStore } from '@/stores/user'
import i18n from '@/i18n/index.js'
import { ElLoading, ElMessage } from "element-plus";
let current = (localStorage && localStorage.getItem('language')) || 'zh'
let token = (localStorage && localStorage.getItem('token')) || 'eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxNTkxNTgxNjA0MSIsImxvZ2luVHlwZSI6InVzZXIiLCJ1c2VyTmFtZSI6IjE1OTE1ODE2MDQxIiwiaWF0IjoxNjgxODAzNzY1LCJqdGkiOiJhMDU4M2EwZS01M2EzLTQ1YTUtOTI1ZS1kZDgzYzU5Y2Y5MGMifQ.bdu5jqbSxSlo9LH4w_uPEuP67DUJk6w5Yqnu633OtQI'
// request是一个axios实例,每一个实例你都可以单独定制它的baseURL,超时时间,请求头和一些其他配置项。
const baseUrl = import.meta.env.VITE_BASE_URL; //接口统一域名
let store = null
const timeZone = new Date().getTimezoneOffset()
const lang = i18n.global.locale;
const instance = axios.create({
    baseURL: baseUrl,
    // timeout: 60 * 1000, //设置超时
    headers: {
        "Content-Type": "application/json;charset=UTF-8;",
        "Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8",
        ".AspNetCore.Culture": "c=zh-Hans|uic=zh-Hans",
        token: token,
        current,
        lang: current,
    },
});

let loading;
//正在请求的数量
let requestCount = 0;
//显示loading
const showLoading = () => {
    if (requestCount === 0) {
        loading = ElLoading.service({
            fullscreen: true,
            text: "Loading  ",

            // background: "rgba(0, 0, 0, 0.7)",
        });
    }
    requestCount++;
};
//隐藏loading
const hideLoading = () => {
    requestCount--;
    if (requestCount == 0) {
        loading.close();
    }
};

//请求拦截器
instance.interceptors.request.use(
    (config) => {
        if (!store) store = useUserStore()
        console.log('config', config.loading, 'if', store)
        token = store.token
        if (token) {
            // 判断是否存在token，如果存在的话，则每个http header都加上token
            config.headers.token = token //请求头加上token
        }
        if (!config.loading) {
            showLoading();
        }
        // 每次发送请求之前判断是否存在token，如果存在，则统一在http请求的header都加上token，不用每次请求都手动添加了
        //若请求方式为post，则将data参数转为JSON字符串
        if (config.method === "POST") {
            config.data = JSON.stringify(config.data);
        }
        return config;
    },
    (error) =>
        // 对请求错误做些什么
        Promise.reject(error)
);

//响应拦截器
instance.interceptors.response.use(
    (response) => {
        console.log('response', i18n, response.data)
        let t = i18n.global.t;
        let code = Number(response.data.code)

        hideLoading();
        if(code == 3004){
            ElMessage.error(t(`toast.${code}`) || response.data.message);
            throw response.data.msg || response.data.message;
            // window.location.href = '/#/login/login?from=%2F'
        }else if (code !== 200 && code !== 0) {
            ElMessage.error(t(`toast.${code}`) || response.data.message);
            return Promise.reject(response.data)
            // router.push("/");
        }
        else return response.data?.data;
    },
    (error) => {
        hideLoading();
        //响应错误
        let message = "";
        if (error.response && error.response.status) {
            const status = error.response.status;
            console.log('Error', error.response)
            switch (status) {
                case 400:
                    message = "请求错误";
                    break;
                case 401:
                    message = "请求错误";
                    break;
                case 404:
                    message = "请求地址出错";
                    break;
                case 408:
                    message = "请求超时";
                    break;
                case 500:
                    message = "服务器内部错误!";
                    break;
                case 501:
                    message = "服务未实现!";
                    break;
                case 502:
                    message = "网关错误!";
                    break;
                case 503:
                    message = "服务不可用!";
                    break;
                case 504:
                    message = "网关超时!";
                    break;
                case 505:
                    message = "HTTP版本不受支持";
                    break;
                default:
                    message = "请求失败";
            }

            ElMessage.error(message);
            return Promise.reject(error);
        }
        return Promise.reject(error);
    }
);

export default instance;
