import Request from 'luch-request';
import { useGlobSetting } from '@/config';
import { useUserStoreWithOut } from '@/store/modules/user';
const { apiUrl } = useGlobSetting();

const http = new Request();
http.setConfig((config) => {
    config.baseURL = apiUrl;
    config.timeout = 10000;
    config.header = Object.assign({
        // 'Content-Type': 'application/json;charset=UTF-8',
    }, config.header);
    /* 设置全局配置 */
    config.validateStatus = (statusCode) => {
        // 不论什么状态,统一在正确中处理
        return true;
    };
    return config;
});
http.interceptors.request.use((config) => {
    config.header = Object.assign({}, config.header);
    if (config.params) {
        for (const [key, value] of Object.entries(config.params)) {
            if (value === undefined || value === null || value === '')
                delete config.params[key];
        }
    }
    if (config.data) {
        for (const [key, value] of Object.entries(config.data)) {
            if (value === undefined || value === null || value === '')
                delete config.data[key];
        }
    }
    const userStore = useUserStoreWithOut();
    const token = userStore.token;
    if (token != null) {
        config.header.Authorization = `Bearer ${token}`;
    }

    return config;
}, (config) => {
    return Promise.reject(config);
});

// 必须使用异步函数，注意
http.interceptors.response.use(async (response) => {

    // 处理响应结果
    const { statusCode, data } = response
    if (statusCode >= 400) {
        uni.showToast({
            title: data.message || '服务器错误',
            icon: 'none'
        })
        return Promise.reject(response)
    }

    const { isTransformResponse = true, isReturnNativeResponse } = response.config.custom;
    // 是否返回原生响应头
    if (isReturnNativeResponse) {
        return response;
    }
    // 是否需要处理请求结果
    if (!isTransformResponse) {
        return response.data.data;
    }
    return response.data;
}, (error) => {
    return error;
});
export { http };
export const Method = {
    GET: 'GET',
    POST: 'POST',
    PUT: 'PUT',
    DELETE: 'DELETE',
};