import axios, {
    AxiosInstance,
    InternalAxiosRequestConfig,
    AxiosResponse,
    AxiosRequestHeaders,
} from 'axios'
import Toast from '../components/Toast'
import { BASE_URL, WITH_CREDENTIALS, NETWORK_ERROR } from '../common/constans/international'

// 创建一个 Axios 实例
const axiosInstance: AxiosInstance = axios.create({
    baseURL: BASE_URL,
    timeout: 20000,
    headers: {
        'Content-Type': 'application/json',
    },
    withCredentials: WITH_CREDENTIALS,
})

// 请求拦截器
axiosInstance.interceptors.request.use(
    async (config: InternalAxiosRequestConfig) => {
        // 这里的 config 对象包含了本次请求的相关配置
        config.params = { ...config.params /* 公共参数 */ }
        config.headers = {} as AxiosRequestHeaders
        config.headers['Weshop-Language'] = document?.documentElement?.lang
        config.headers['Did'] = 'local'
        return config
    },
    (error) => {
        Toast({
            message: error.message,
            duration: 3000,
        })
        // 请求出错时的处理s
        return Promise.reject(error)
    },
)

// 响应拦截器
axiosInstance.interceptors.response.use(
    (response: AxiosResponse) => {
        const { success, msg, data, code } = response.data
        // eslint-disable-next-line @typescript-eslint/no-explicit-any
        let params = {} as any
        if (response?.config?.data) {
            params = JSON.parse(response?.config?.data)
        } else {
            params = response?.config?.params
        }
        if (success) return data
        else if (params?.replicateList) {
            // 复刻请求任务list
            return { code, msg }
        } else if (code === '2005') {
            if (!params?.noLogin) {
                location.href = '/login?from=' + encodeURIComponent(window.location.href)
            }
        } else if (code === '2007' || code === '2014') {
            // 2007 算力不足, 2014 完成注册
            return { code, msg }
        } else if (code === '2011' || code === '2006') {
            Toast({
                message: `🔴 ${msg} 🙅🏻‍♀️`,
                duration: 2000,
            })

            if (params?.requestTaskExecutions) {
                return {
                    clearInterval: true,
                }
            }
        } else {
            if (params?.noShowToast) return
            if (typeof window === 'undefined') {
                console.error(msg)
            } else {
                Toast({
                    message: `🔴 ${msg} 🙅🏻‍♀️`,
                    duration: 2000,
                })
            }
            return
        }
    },
    (error) => {
        // eslint-disable-next-line @typescript-eslint/no-explicit-any
        let params = {} as any
        if (error?.config?.data) {
            params = JSON.parse(error?.config?.data)
        } else {
            params = error?.config?.params
        }
        if (params?.noShowToast) return
        // 响应出错时的处理
        if (error.response) {
            const msg = error?.response?.data?.message || NETWORK_ERROR
            if (typeof window === 'undefined') {
                console.error(msg)
            } else {
                Toast({
                    message: msg,
                    duration: 2000,
                })
            }
        } else {
            if (typeof window === 'undefined') {
                console.error(NETWORK_ERROR)
            } else {
                Toast({
                    message: NETWORK_ERROR,
                    duration: 2000,
                })
            }
        }
    },
)

/* 导出封装的请求方法 */
export const http = {
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    get<T = any>(url: string, config?: InternalAxiosRequestConfig): Promise<T> {
        return axiosInstance.get(url, config)
    },
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    post<T = any>(url: string, data?: object, config?: InternalAxiosRequestConfig): Promise<T> {
        return axiosInstance.post(url, data, config)
    },
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    put<T = any>(url: string, data?: object, config?: InternalAxiosRequestConfig): Promise<T> {
        return axiosInstance.put(url, data, config)
    },
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    delete<T = any>(url: string, config?: InternalAxiosRequestConfig): Promise<T> {
        return axiosInstance.delete(url, config)
    },
}

export default axiosInstance
