import ajax from 'uni-ajax'
import {getToken} from '../util/auth';
import website from '@/config/index';
import {Base64} from 'js-base64';
import {toSerialize} from "js-fast-way"
import {getAppApiUrl} from '@/config/envApi';

// 创建请求实例
const instance = ajax.create({
    baseURL: getAppApiUrl(),
    timeout: 1800000,
    validateStatus: function (status) {
        return status >= 200 && status <= 500;
    },
    //跨域请求，允许保存cookie
    withCredentials: true,
})

//http request拦截
instance.interceptors.request.use(config => {
    const meta = (config.meta || {});
    const isToken = meta.isToken === false;
    config.header = {...config.headers}
    config.header['Authorization'] = `Basic ${Base64.encode(`${website.clientId}:${website.clientSecret}`)}`;
    //让每个请求携带token
    const token = getToken()
    if (token && !isToken) {
        config.header['Blade-Auth'] = 'bearer ' + token
    }
    //headers中配置text请求
    if (config.text === true) {
        config.header["Content-Type"] = "text/plain";
    }
    //headers中配置serialize为true开启序列化
    if (config.method === 'post' && meta.isSerialize === true) {
        config.data = toSerialize(config.data);
    }
    //#ifdef APP-PLUS
    config.url = config.url.replace(/^\/api/, '/');
    //#endif
    config.metadata = { startTime: new Date() }
    return config
}, error => {
    return Promise.reject(error)
});

//http response 拦截
instance.interceptors.response.use(res => {
    //响应时间
    res.config.metadata.endTime = new Date()
    //获取状态码
    const status = res?.data?.code || res.statusCode
    //如果是401则跳转到登录页面
    if (status === 401) {
        uni.showToast({
            title: '身份失效',
            icon: 'none'
        });
        uni.redirectTo({
            url: '/pages/login/login'
        });
    }
    // 如果请求为非200否者默认统一处理
    if (status !== 200) {
        return Promise.reject(res)
    }
    return res;
}, error => {
    return Promise.reject(new Error(error));
});

export default instance;
