import qs from 'qs'; 
import axios from 'axios';
import Promise from 'promise-polyfill';

axios.defaults.timeout = 10000; // 超时时间

const DATA_FORM = 'application/x-www-form-urlencoded;charset=UTF-8';
const DATA_JSON = 'application/json;charset=UTF-8';
const isDev = window.location.hostname == "127.0.0.1";
// const dev = process.env.NODE_ENV == 'development';

// console.log("process.env.NODE_ENV = " + process.env.NODE_ENV);

// 根据环境设置baseUrl
// let baseUrl = '';
// if (process.env.NODE_ENV === 'development') {
//     baseUrl = '';
// } else if (process.env.NODE_ENV === 'production') {
//     baseUrl = '';
// }

axios.defaults.baseURL = isDev ? HTTP : '';

console.log("HTTP = " + HTTP);
console.log("MOCK = " + MOCK);
console.log("PROXY = " + PROXY);

// 添加json后缀
function insertExt(url){
    var list = url.split("?");
    if(list.length == 1){
        return url + '.json';
    }
    return list.shift()+ '.json?' + list.join("?");
}


// axios请求拦截
axios.interceptors.request.use(
    config => {
        // 统一拼上固定要传的参数
        let method = config.method;
        if (method === 'post' && config.headers['content-type'] == DATA_FORM){
            
        }
        console.log(config);
        if(isDev && MOCK){
            config.url = insertExt(config.url);
        }
        return config;
    }, 
    error => {
        return Promise.error(error);
    }
);

// axios响应拦截
axios.interceptors.response.use(
    response => {
        if (response.status === 200) {
            return Promise.resolve(response);
        } else {
            return Promise.reject(response);
        }
    }
)

const handleReuslt = (res, resolve, reject) => {
    let {
        data,
        success,
        desc,
        code
    } = res.data;
    resolve(res.data);
    // if (success) {
    //     resolve(res.data);
    // } else {
    //     console.error(res.data);
    //     reject(res.data);
    // }
}

export const get = (url, params, config)=> {
    return new Promise((resolve, reject)=>{
        axios({
            method:'get',
            url:url,
            params: params,
            paramsSerializer: function(params) {
               return qs.stringify(params, {arrayFormat: 'repeat'})
            },
            ...config
        }).then(res => {
            handleReuslt(res, resolve, reject);
        }).catch(err => {
            console.error(err);
            reject(err);
        });
    });
}

export const post = (url, params, config)=> {
    if(isDev && MOCK){
        return get(url, params, config);
    }
    return new Promise((resolve, reject)=>{
        axios({
            method:'post',
            url:url,
            data: params,
            headers: { 'content-type': config && config.isForm ? DATA_FORM : DATA_JSON },
            ...config
        }).then(res => {
            handleReuslt(res, resolve, reject);
        }).catch(err => {
            console.error(err);
            reject(err);
        });
    });
}
