import axios from '../config/axiosConfig'

import { AxiosRequestConfig, CustomSuccessData } from 'axios';
import { getValue, toindex } from '@/utils/common';
import { message } from 'ant-design-vue';
import router from '@/router';
import { MessageType } from 'ant-design-vue/types/message';
import store from '@/store';
import { geti18n } from '@/utils/i18n';

// 泛型接口 
export interface Get {
    <T>(url: string, params?: unknown, config?: AxiosRequestConfig): Promise<CustomSuccessData<T>>;
}
let login: MessageType;
let count = 0;
const div: any = document.getElementById("make");
export function countadd(){
    if(count == 0){
        login = message.loading(geti18n().$t('jiazaizhong'), 0)
        div.style.display = "block"
    }
    count++;
}
export function countdel(){
    if(count != 0){
        setTimeout(()=>{
            count--;
            if(count == 0){
                login();
                div.style.display = "none"
            }
            console.log(count)
        }, 1000)
    }
}
axios.interceptors.request.use((config)=>{
    if(count == 0){
        login = message.loading(geti18n().$t('jiazaizhong'), 0)
        div.style.display = "block"
    }
    count++;
    return config;
})

axios.interceptors.response.use((response)=>{
    // console.log(response)
    if(count != 0){
        setTimeout(()=>{
            count--;
            if(count == 0){
                login();
                div.style.display = "none"
            }
            console.log(count)
        }, 1000)
    }
    
    if(response.data.code == 1001){
        store.commit("login", false)
        toindex();
    }
    return response;
},(error)=>{
    if(count != 0){
        setTimeout(()=>{
            count--;
            if(count == 0){
                login();
                div.style.display = "none"
            }
            console.log(count)
        }, 1000)
    }
    message.error(error.response.data.message)
    return Promise.reject(error) 
})

const get: Get = async function (url: string, data?: unknown) {
    const res =  await axios.get(url, {params:data});
    return res.data;
}

const post: Get = async function (url: string, data?: unknown) {
    const res =  await axios.post(url, data)
    return res.data;
}

const del: Get = async function (url: string, data?: unknown){
    const res =  await axios.delete(url, {params:data})
    return res.data;
}

const put: Get = async function (url: string, data?: unknown){
    const res =  await axios.put(url, data)
    return res.data;
}


function setToken(){
    axios.defaults.headers.common['Authorization'] = "Bearer " + getValue("token");
}
function setLanvuage(yuyan: string){
    axios.defaults.headers.common['Language'] = yuyan;
}

export {
    get,
    post,
    del,
    put,
    setToken,
    setLanvuage
}