import axios from 'axios';
import { notification } from 'ant-design-vue';
import md5 from 'crypto-js/md5';
import { langUtil } from '.';

// 跨域认证信息 header 名
const xsrfHeaderName = 'Authorization';

axios.defaults.timeout = 5000;
axios.defaults.withCredentials = true;
axios.defaults.xsrfHeaderName = xsrfHeaderName;
axios.defaults.xsrfCookieName = xsrfHeaderName;

/**
 * @param {*} info 提示函数
 */
function loadResponseInterceptor({ router }) {
    axios.interceptors.request.use(
        function(config) {
            // 在发送请求之前做些什么
            config.headers = {
                ...config.headers,
                Authorization: getToken(),
                'X-Access-Lang': langUtil.get() || 'zh_CN',
            };
            return config;
        },
        function(error) {
            // 对请求错误做些什么
            return Promise.reject(error);
        },
    );

    // 添加响应拦截器
    axios.interceptors.response.use(
        function(response) {
            const { data } = response;
            // 2xx 范围内的状态码都会触发该函数。
            // 对响应数据做点什么
            if (data.code === 'sys.success') {
                return data.data;
            }

            if (data.code === 'error.system.authc') {
                router.push('/login');
            }
            notification.error({
                message: data.code,
                description: h => h('pre', data.message),
            });

            return Promise.reject(data.message);
        },
        function(error) {
            // 超出 2xx 范围的状态码都会触发该函数。
            // 对响应错误做点什么
            notification.error({
                message: `${error.response.status} ${error.response.statusText}`,
                description: h => h('pre', error.message),
            });
            return Promise.reject(error);
        },
    );
}

// http method
const METHOD = {
    GET: 'get',
    POST: 'post',
    PUT: 'put',
    DELETE: 'delete',
};

/**
 * axios请求
 * @param url 请求地址
 * @param method {METHOD} http method
 * @param params 请求参数
 * @param config token等信息
 * @returns {Promise<AxiosResponse<T>>}
 */
async function request(url, method, params, config) {
    switch (method) {
        case METHOD.GET:
            return axios.get(url, { params, ...config });
        case METHOD.POST:
            return axios.post(url, params, config);
        case METHOD.PUT:
            return axios.put(url, params, config);
        case METHOD.DELETE:
            return axios.delete(url, { params, ...config });
        default:
            return axios.get(url, { params, ...config });
    }
}

/**
 * 解析 url 中的参数
 * @param url
 * @returns {Object}
 */
function parseUrlParams(url) {
    const params = {};
    if (!url || url === '' || typeof url !== 'string') {
        return params;
    }
    const paramsStr = url.split('?')[1];
    if (!paramsStr) {
        return params;
    }
    const paramsArr = paramsStr.replace(/&|=/g, ' ').split(' ');
    for (let i = 0; i < paramsArr.length / 2; i++) {
        const value = paramsArr[i * 2 + 1];
        params[paramsArr[i * 2]] = value === 'true' ? true : value === 'false' ? false : value;
    }
    return params;
}

const TOKEN_KEY = md5('TOKEN').toString();
function getToken() {
    return window.sessionStorage.getItem(TOKEN_KEY) ?? '';
}

function setToken(val) {
    window.sessionStorage.setItem(TOKEN_KEY, val);
}

function clearToken() {
    window.sessionStorage.removeItem(TOKEN_KEY);
}

function checkAuthorization() {
    return !!getToken();
}

function delReq(url, config) {
    return request(url, METHOD.DELETE, config);
}

function getReq(url, params, config) {
    return request(url, METHOD.GET, params, config);
}

function postReq(url, data, config) {
    return request(url, METHOD.POST, data, config);
}

function putReq(url, data, config) {
    return request(url, METHOD.PUT, data, config);
}

export {
    METHOD,
    request,
    parseUrlParams,
    loadResponseInterceptor,
    setToken,
    checkAuthorization,
    clearToken,
    delReq,
    getReq,
    postReq,
    putReq,
};
