import axios from 'axios'
import {message, notification} from 'ant-design-vue'

axios.defaults.timeout = 30000;
axios.defaults.baseURL = process.env.VUE_APP_BASE_URL;
// axios.defaults.baseURL = ''

// type默认为form，如果要在请求体里传json，则传json，如果要上传文件，传file
function fetch(url = '', params = {}, method = 'get', contentType = 'form', token) {
    contentType === 'form' && (contentType = 'application/x-www-form-urlencoded');
    contentType === 'json' && (contentType = 'application/json; charset=utf-8')
    contentType === 'file' && (contentType = 'multipart/form-data')
    //移除空白参数
    let keyArr = [];
    for (let k in params) {
        let val = params[k];
        if (val === null || val === undefined || val === 'null' || val === ' ') {
            keyArr.push(k);
        }
    }
    keyArr.forEach(x => {
        delete params[x];
    })
    let query = [];
    for (let k in params) {
        query.push(k + '=' + params[k])
    }
    let qs = query.join('&');
    if (method.toLowerCase() === 'get' && query.length > 0) {
        url += (url.indexOf('?') < 0 ? '?' : '&') + qs;
    }
    if (contentType !== 'application/x-www-form-urlencoded' && method !== 'get') {
        qs = params
    }
    let serviceApi = process.env.VUE_APP_SERVICE_API;
    return new Promise((resolve, reject) => {
        axios({
            method: method,
            url: serviceApi+url,
            data: params,
            headers: {
                Authorization: token || window.sessionStorage.getItem('token'),
                menuId: params.menuId,
                'Content-Type': contentType,
            }
        }).then(function (response) {
            if (response.data.code === 'BIZ.TOKEN_EXPIRATION') {
                message.error(response.data.msg);
                // if (process.env.NODE_ENV != "dev") {
                //     window.top.postMessage({messageType: "LOGOUT"}, '*');
                //     return
                // }
            }
            if (response.data.code === 'BIZ.BUSSINESS_EXCEPTION') {
                message.error(response.data.msg);
            }
            if (response.data.code === 'PARAM.EXCEPTION') {
                message.error('系统异常请联系客服！');
            }
            if (response.data.code === 'SYS.UNKNOWN_EXCEPTION') {
                message.error('系统异常请联系客服！');
            }
            resolve(response.data);
        }).catch(function (err) {
            console.log(err)
            reject(err)
        })
    })
}

export default fetch
