import Axios from 'axios';
import Vue from 'vue';
import Configs from '../../config';

const vm = new Vue();

const fetch = async config => {
    const {
        baseUrl, method, params, independent, url, ...other
    } = config;
    const timestamp = new Date().getTime();
    // 创建axios实例
    const axiosIns = Axios.create();
    const headers = {
        from: 'Y',
        Authorization: 
            // eslint-disable-next-line max-len
            'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyLWtleSI6IjExNzA2NTg4MTIxNTg2OTMzNzgiLCJpc3MiOiJndWFoby5jb20iLCJleHAiOjE1NzM3ODcyOTB9.pfNU2IAehBuMKOfXA1-Wo8KoHJzPzuIHBsPlozL271o'
    };

    const Osses = Configs.baseOss;
    let cfgBase = Configs.baseUrl;
    if (Osses) {
        Object.keys(Osses).forEach(key => {
            const reg = new RegExp(`^${key}`);
            if (url.match(reg)) {
                // url = url.replace(reg, '');
                cfgBase = Osses[key];
            }
        });
    }
    let options = {
        headers,
        baseURL: baseUrl || cfgBase,
        timeout: 1 * 60 * 1000,
        url,
        ...other
    };
    if (method === 'post') {
        options = Object.assign(
            options,
            {
                method: 'post',
                data: params
            }
        );
    } else {
        options = Object.assign(
            options,
            {
                method: 'get',
                params: {
                    ...params,
                    timestamp
                }
            }
        );
    }
    const response = await axiosIns(options).then(res => {
        // console.log('resresresresres', res);
        const { code, message } = res.data;
        if (String(code) !== '0') { // code不为0视为错误
            vm.$message({
                message: message || '业务逻辑异常',
                type: 'error'
            });
            return false;
        }
        return res.data;
    }).catch(error => {
        if (!Axios.isCancel(error)) {
            vm.$message.error('系统异常');
            return false;
        }
        return false;
    });
    return response;
};

export default fetch;
