import type { UseFetchOptions } from '#app';
import { useToken } from "~/composables/configState";
import { isProxy, toRaw } from 'vue';

export const request = <T>(url:string, options?: UseFetchOptions<T, unknown>) => {
    const nuxtApp = useNuxtApp()
    const config = useRuntimeConfig()
    let TenantId = localStorage.getItem('TenantId') || `${config.public.tenantId}`;
    const body = options?.body;
    // @ts-ignore
    const tenantIdByOptions = body?.tenantId;
    if(tenantIdByOptions){
      // 自定义传TenantId
      TenantId = tenantIdByOptions;
    }
    return useFetch<T>(url,{
        baseURL: config.public.apiBaseUrl,
        onRequest({ options }: any){
            let token = ''
            if(import.meta.client){
                 token = `${useToken().value}`
            }
            options.headers = {
                TenantId,
                'Authorization': `${token}`,
                ...options.headers
            }
        },
        onResponse({ response }: any){
            // 200xx 以内错误
            if(response.status >= 200 && response.status < 300){
                if(response._data.code !== 0){
                    console.log('>>>>200xx 以内错误')
                    if(import.meta.client){
                        ElMessage.error(response._data.message)
                        nuxtApp.runWithContext(() => {
                            // navigateTo({
                            //     path: '/404',
                            //     query: {
                            //         code: response.status,
                            //         message: response._data.message
                            //     }
                            // })
                        })
                    }
                }
            }
        },
        onResponseError({ response }: any){
            // 200xx 以外错误
            if(import.meta.client){
                console.log('200xx 以外错误',response)
                ElMessage.error(isArray(response._data.data.message) ? response._data.data.message[0] : response._data.data.message);
            }
        },
        ...options
    } as any)
}

export const get = <T>(url: string,options?: UseFetchOptions<T, unknown>) => {
    return <T>new Promise((resolve,reject) => {
        request(url,{
            method: 'get',
            ...options
        }).then(res => {
            resolve(res.data.value)
        }).catch(err => {
            reject(err)
        })
    })
}
export const post = <T>(url:string,data?: any) => {
    return <T>new Promise((resolve,reject) => {
        // 避免传入 reactive 对象导致 useFetch 监听变更重复发送请求
        const payload = isProxy(data) ? toRaw(data) : data;
        request(url,{
            method: 'post',
            body: payload
        }).then(res => {
            resolve(res.data.value)
        }).catch(err => {
            reject(err)
        })
    })
}
export const put = <T>(url:string,data?: any) => {
    return <T>new Promise((resolve,reject) => {
        const payload = isProxy(data) ? toRaw(data) : data;
        request(url,{
            method: 'put',
            body: payload
        }).then(res => {
            resolve(res.data.value)
        }).catch(err => {
            reject(err)
        })
    })
}
export const del = <T>(url:string,data?: any) => {
    return <T>new Promise((resolve,reject) => {
        request(url,{
            method: 'delete',
            ...data
        }).then(res => {
            resolve(res.data.value)
        }).catch(err => {
            reject(err)
        })
    })
}

export default {
    request,
    get,
    post,
    put,
    del
}
