import fetch from 'isomorphic-fetch';
import Message from 'antd/lib/message';

function _handleFetch(url, method, options) {
	var obj = Object.assign({
		mode: 'cors',
		method: method
	}, options);

	return fetch(url, obj)
		.then((response) => {
			switch(response.status) {
				case 200:
				case 201:
					return response.json();
				case 212:
					Message.error('登陆状态已失效,请重新登陆!', 2, function() {
						window.location.href= `${window.location.origin}/login`;
					});
					return response;
				case 401:
					window.location.href= `${window.location.origin}/login`;
					return response;
				default:
					let err = new Error(response.statusText);
					err.response = response;
					throw err;
			}
		})
		.catch(err => err);
}

const request = {
	get: function(url) {
		return _handleFetch(url, 'GET', {});
	},
	post: function(url, data) {
		return _handleFetch(url, 'POST', {
			body: JSON.stringify(data)
		});
	},
	put: function(url, data) {
		return _handleFetch(url, 'PUT', {
			body: JSON.stringify(data)
		});
	},
	delete: function(url) {
		return _handleFetch(url, 'DELETE', {});
	}
}

export default request;