/** @format */
import axios, {AxiosRequestConfig, AxiosResponse, AxiosError} from 'axios';
import {LOGIN_PATH} from '../const/path';
import message from '../components/message';
import {getLocalStorage, storageResponse} from './webStorage';

let userInfo: {
    token: string;
    uid: string;
    expireTime?: number;
} = {
    token: '',
    uid: '',
};
const HandlingErrors = (error: string) => {
    message.error(error);
    setTimeout(() => {
        window.localStorage.clear();
        location.href = '/';
    }, 1000);
};
/**
 * 获取用户信息和token
 */

function getUserInfoByStorage() {
    const [error, userInfo]: storageResponse = getLocalStorage('userinfo');
    if (error) {
        HandlingErrors(error);
    }
    if (userInfo) {
        return {token: userInfo.token, uid: userInfo.admin_id};
    }
    return {
        token: '',
        uid: '',
    };
}

export const getUserInfo = () => {
    userInfo = getUserInfoByStorage();
    (!userInfo.token || !userInfo.uid) && HandlingErrors('用户信息无效,重新登录');
    userInfo.expireTime && userInfo.expireTime > Date.now() && HandlingErrors('用户信息过期,重新登录');
    return userInfo;
};

let preConfig: AxiosRequestConfig = {};
const xhr = (config: AxiosRequestConfig) => {
    //如果需求出现一个页面针对同一个接口同时进行两次请求，那么只会发出一次
    // if(config.method===preConfig.method&&config.url===preConfig.url){
    //     cancel();
    // }
    // preConfig=config;
    return axios({
        ...config,
        baseURL: '/api/v1',
        headers: {
            ...config.headers,
            ...(LOGIN_PATH === config.url ? {} : getUserInfo()),
        },
        // cancelToken: new CancelToken(function executor(c) {
        //   cancel = c;
        // })
    })
        .then((response: AxiosResponse) => {
            if (response.data.code === 10007) {
                HandlingErrors(response.data.msg);
            }
            return response.data;
        })
        .catch((error: AxiosError) => {
            throw error;
        });
};
export default xhr;
