import config from '@/config';
import { useInfoStore } from '@/store';
import { getCurrentPage } from '@/utils/public';
import { recursiveDecodeURIComponent } from '@/utils/ruoyi';
import errorCode from '@/utils/errorCode';
const { clientId, appid } = config;
// uniapp封装的请求方法
let timeout = 60 * 1000;

// 获取全局请求头方法
const getHeader = () => {
    let header = {
        'Content-Type': 'application/json',
        Authorization: 'Bearer ' + useInfoStore().token || '',
        xid: config?.appid || '',
        clientId: config?.clientId || '',
    };
    return header;
};

// 获取host地址
export const request = ({ url, method = 'GET', data = {}, isToken = true, header = null }: any) => {
    const baseUrl = import.meta.env.VITE_API_BASE_URL || 'http://192.168.1.26:8080';
    // const baseUrl = 'http://192.168.1.26:8888';
    if (isToken && useInfoStore().isTokenExpired()) {
        uni.hideLoading();
        useInfoStore().removeToken();
        let fullPath = recursiveDecodeURIComponent(getCurrentPage()?.$page?.fullPath);
        const isLoginPage = recursiveDecodeURIComponent(fullPath)?.indexOf('/pages/login/login') !== -1;
        if (isLoginPage) {
            return;
        }
        const fulllpathParams = fullPath.split('?');
        const fullpathstr = fulllpathParams.length > 1 ? `${fulllpathParams[0]}?${fulllpathParams[fulllpathParams.length - 1]}` : fulllpathParams[0];
        // 获取当前页面路径
        uni.$u.route({
            type: 'redirect',
            url: '/pages/login/login',
            params: {
                // 转成浏览器可识别的字符串
                // 这里可以传递当前页面的路径作为参数，方便登录后重定向回原页面
                redirect: encodeURIComponent(fullpathstr),
            },
        });
        return;
    }
    return new Promise((resolve, reject) => {
        uni.request({
            url: baseUrl + url,
            method,
            data,
            timeout: timeout,
            header: header || getHeader(),
        })
            .then((response) => {
                let { data, statusCode } = response;
                if (statusCode !== 200) {
                    uni.showToast({
                        icon: 'none',
                        title: '后端接口连接异常',
                    });
                    reject('后端接口连接异常');
                    return;
                }
                const code = (data as any).code || 200;
                const msg = errorCode[code] || (data as any).msg || errorCode['default'];
                // 处理业务错误
                if (code === 401) {
                    uni.hideLoading();
                    useInfoStore().removeToken();
                    let fullPath = recursiveDecodeURIComponent(getCurrentPage()?.$page?.fullPath);
                    const isLoginPage = recursiveDecodeURIComponent(fullPath).indexOf('/pages/login/login') !== -1;
                    if (isLoginPage) {
                        return;
                    }
                    const fulllpathParams = fullPath.split('?');
                    const fullpathstr = fulllpathParams.length > 1 ? `${fulllpathParams[0]}?${fulllpathParams[fulllpathParams.length - 1]}` : fulllpathParams[0];
                    // 获取当前页面路径
                    uni.$u.route({
                        type: 'redirect',
                        url: '/pages/login/login',
                        params: {
                            // 转成浏览器可识别的字符串
                            // 这里可以传递当前页面的路径作为参数，方便登录后重定向回原页面
                            redirect: encodeURIComponent(fullpathstr),
                        },
                    });
                    return reject('无效的会话，或者会话已过期，请重新登录。');
                } else if (code === 500) {
                    uni.hideLoading();
                    if (msg) {
                        uni.showToast({
                            title: msg,
                            icon: 'none',
                        });
                    }
                    return reject(data);
                } else if (code !== 200) {
                    uni.hideLoading();
                    uni.showToast({
                        title: msg,
                        icon: 'none',
                    });
                    reject(code);
                }
                // 成功情况
                resolve(data);
            })
            .catch((error) => {
                let { message } = error;
                if (message === 'Network Error') {
                    message = '后端接口连接异常';
                } else if (message.includes('timeout')) {
                    message = '系统接口请求超时';
                } else if (message.includes('Request failed with status code')) {
                    message = '系统接口' + message.substr(message.length - 3) + '异常';
                }
                uni.hideLoading();
                uni.showToast({
                    title: message,
                    icon: 'none',
                });
                return reject(error);
            });
    });
};
export const useClientRequest = {
    post: <T = any>(url: string, data?: any, isToken?: boolean): Promise<T> => {
        return request({
            url,
            method: 'POST',
            data,
            isToken,
        }) as Promise<T>;
    },
    get: <T = any>(url: string, data?: any, isToken?: boolean): Promise<T> => {
        return request({
            url,
            method: 'GET',
            data,
            isToken,
        }) as Promise<T>;
    },
    put: <T = any>(url: string, data?: any, isToken?: boolean): Promise<T> => {
        return request({
            url,
            method: 'PUT',
            data,
            isToken,
        }) as Promise<T>;
    },
    delete: <T = any>(url: string, data?: any, isToken?: boolean): Promise<T> => {
        return request({
            url,
            method: 'DELETE',
            data,
            isToken,
        }) as Promise<T>;
    },
};
