import HttpRequest from './http';
import { merge } from 'lodash-es';
import { getToken } from '../auth';
import { CLIENT_ID } from '@/enums/cacheEnums';
import { RequestCodeEnum, RequestMethodsEnum } from '@/enums/requestEnums';
import { clearToken } from '@/utils/auth'
import { useUserStore } from '@/stores/user'
import { useMessage } from '../message';
const message = useMessage();

const requestHooks = {
    // 请求拦截器
    requestInterceptorsHook(options, config) {
        // console.log("request=>config=>",config)
        const { urlPrefix, baseUrl, withToken, isAuth } = config;
        options.header = options.header ? options.header:{};
        if (urlPrefix) {
            options.url = `${urlPrefix}${options.url}`;
        }
        if (baseUrl) {
            options.url = `${baseUrl}${options.url}`;
        }
        const token = getToken(); //console.log("token=>",token)
        // if (withToken && !options.header.token) {
            options.header.token = "Bearer "+ token;
            options.header.Authorization = "Bearer "+ token;
        // }
        // console.log("request=>",options)
        return options;
    },
    // 响应拦截器
    responseInterceptorsHook(response, config) {
        // console.log("response=>",response)
        // console.log("response=>config=>",config)
        const { isTransformResponse, isReturnDefaultResponse, isAuth } = config;
        if (isReturnDefaultResponse) {
            return response;
        }
        // const { logout, isLogin } = useUserStore();
        const { code, data, msg, show } = response.data;
        switch (code) {
            case RequestCodeEnum.SUCCESS:
                msg && show && message.toast(msg);
                if (!isTransformResponse) {
                    return response.data;
                }else{
                    return data;
                }
            case RequestCodeEnum.FAILED:
                message.toast(msg);
                return Promise.reject(msg);
            case RequestCodeEnum.TOKEN_INVALID:
                message.toast('登录状态已过期，请重新登录！');
                // console.log(isAuth,isLogin)
                // if (isAuth && isLogin) {
					clearToken();
					uni.reLaunch({ url: '/pages/login/login' })
                // }
                
                return Promise.reject();

            default:
                if(msg)
                    message.alert(msg)
                else
                    message.alert("网络连接失败，请稍后再试！")
                // return data;
                return Promise.reject(msg);
        }
    },
    // 响应异常拦截器
    responseInterceptorsCatchHook(options, err) {
        if (options.method.toUpperCase() == RequestMethodsEnum.POST) {
            console.log('请求失败:', err, options);
        }
        return Promise.reject();
    }
};

// 默认配置
const defaultOptions = {
    requestOptions: {// 请求配置
        timeout: 10 * 1000,
        header: { 
            version: '1.0.0',
            clientId:`${CLIENT_ID || 2}`, // clientId传2
        }
    },
    baseUrl: `${import.meta.env.VITE_APP_BASE_URL || ''}`,// 基础 URL
    isReturnDefaultResponse: false,// 是否返回默认响应
    isTransformResponse: true, // 是否转换响应
    urlPrefix: '',// url 前缀
    ignoreCancel: true,// 忽略重复请求取消
    withToken: true,// 携带 Token
    isAuth: false,// 接口是否鉴权
    retryCount: 2,// 重试次数
    retryTimeout: 300, // 重试超时
    requestHooks: requestHooks,// 请求 Hook
    sslVerify: false // 设置为false，不验证 ssl 证书
};

function createRequest(opt) {
    return new HttpRequest(
        merge(defaultOptions, opt || {})
    );
}
const request = createRequest();
export default request;