import env from "@/config"
import {useUserStore} from "@/hooks/useUserStore";
import {useEnvStore} from "@/hooks/useEnvStore"
import {useUserStore as useUserStoreNew} from "@/store/userStore"

/**
 * 请求拦截
 * @param {Object} http
 */
export const requestInterceptors = (vm) => {
    uni.$uv.http.interceptors.request.use((config) => { // 可使用async await 做异步操作
        const {token, isAgreeProtocol} = useUserStore()
        // 'NoToken' url 自动适配
        if (config.custom?.autoFitNoToken && (!token.value || config.custom?.withoutToken)) {
            config.url = config.url + 'NoToken'
        }
        // 初始化请求拦截器时，会执行此方法，此时data为undefined，赋予默认{}
        config.data = config.data || {}
        config.header = config.header || {}
        // 补充header信息
        config.header['X-Requested-With'] = 'XMLHttpRequest';
        config.header['type'] = env.identifier
        const userStore = useUserStoreNew();
        const examType = userStore.getExamType;
        const location = userStore.getLocation;
        if (examType) {
          config.header['examType'] = examType;
        }
        if (location) {
          config.header['location'] = encodeURIComponent(location);
        }
        if (isAgreeProtocol.value) {
            // NOTE: 这里在明确用户同意协议后才访问系统信息，否则有可能提前出现权限询问，导致平台审核被拒！
            const {systemInfo} = useEnvStore()
            for (const [key, value] of Object.entries(systemInfo.value)) {
                config.header[key] = value
            }
        }
        // 可以在此通过vm引用vuex中的变量，具体值在store.state中
        if (!config.custom?.withoutToken && token.value) {
            config.header['Authorization'] = `Bearer ${token.value}`
        }
        return config
    }, (config) => // 可使用async await 做异步操作
        Promise.reject(config))
}
