import fetch from 'isomorphic-fetch';
// import cookie from 'js-cookie';

const errorMessages = (res) => `${res.status} ${res.statusText}`;

function check401(res) {
    if (res.status === 401) {
        location.href = '/login';
        //console.log('401');
    }
    return res;
}

function check404(res) {
    if (res.status === 404) {
        // location.href='/404';
        return Promise.reject(errorMessages(res));
    }
    return res;
}

function jsonParse(res) {

    return res.json().then(json => ({...res, json})).catch(err=> ({...res, json:{status:0, message: '数据加载错误!'}}));

}

function errorMessageParse(res) {
    const {status, msg, message, result} = res.json;
    if (status != 1) {
        return Promise.reject(msg || message);
    }
    return result;
}

function xFetch(url, options) {
    const opts = {...options};
    let user;
    try {
        user = JSON.parse(sessionStorage.getItem('user')) || {};
    } catch (ex) {
        user = {};
    }
    opts.headers = {
        ...opts.headers,
        authorization: user.token || '',
    };
    if (opts.method != 'GET') {
        opts.headers['content-type'] = 'application/x-www-form-urlencoded';
    }


    return fetch(url, opts)
        .then(check401)
        .then(check404)
        .then(jsonParse)
        .then(errorMessageParse);
}

export default xFetch;
