import store from "@/store";
import Config from "@/util/config";
import axios, { AxiosResponse } from "axios";
// 添加请求拦截器
axios.defaults.headers.common["Content-Type"] = "application/json; charset=utf8";
axios.defaults.headers.common["X-Requested-With"] = "XMLHttpRequest";
axios.interceptors.request.use((config) => {
    config.baseURL = `${Config.baseUrl}`;
    config.timeout = 50000;
    let token = window.localStorage.getItem("token")
    config.headers.Authorization = token ?? "1"
    return config;
}, (error) => {
    // 对请求错误做些什么
    return Promise.reject(error);
});

// 添加响应拦截器
axios.interceptors.response.use((res: AxiosResponse) => {
    if (res.data?.status === 401) {
        store.usrStore.openLoginDilog()
        store.usrStore.logOut()
        window.location.href = '#/login'
    }
    return res;
}, (err) => {
    if (err.status === 401) {
        store.usrStore.openLoginDilog()
        store.usrStore.logOut()
        window.location.href = '#/login'
    }
    return Promise.reject(err);
});
class BaseHttp {
    async gets(url: string, params: any) {
        let res = await axios({
            method: 'get',
            url: url,
            headers: {
                "token": window.localStorage.getItem("video-token"),
                'Content-Type': 'application/json; charset=utf-8'
            },
            params
        });
        return res.data;
    };
    async get(url: string, params: any) {
        let res = await axios({
            method: 'get',
            url: url,
            params
        });
        return res.data;
    };
    async post(url: string, params: any) {
        let res = await axios({
            method: 'post',
            url: url,
            data: params
        });
        return res.data;
    };

    async forms(url: string, params: any) {
        let res = await axios({
            method: 'post',
            url: url,
            params: params
        });
        return res.data;
    };
    async upload(url: string, params: any) {
        let res = await axios({
            method: 'post',
            url: url,
            data: params
        });
        return res.data;
    };
    async put(url: string, params: any) {
        let res = await axios({
            method: 'put',
            url: url,
            data: params
        });
        return res.data;
    };
    async delete(url: string, params: any) {
        let res = await axios({
            method: 'delete',
            url: url,
            params
        })
        return res.data;
    };

    async downloadFile(url: string, params: any) {
        let res = await axios({
            method: 'get',
            url: url,
            params,
            responseType: 'blob',
        })
        return res;
    };
}

// eslint-disable-next-line import/no-anonymous-default-export
export default new BaseHttp()