var urlencode = require('urlencode');
exports = module.exports = function (logger, rest, settings) {
	function getOptions(url, type) {
		var catalog = url.substring(1, url.indexOf('/', 1));
		var pathUrl = url.substring(url.indexOf('/', 1));
		var fullPath = '/' + catalog + settings.restful.version + pathUrl;
		return {
			'host': settings.restful.host, //后台请求地址
			'port': settings.restful.port,
			'path': fullPath,
			'method': type,
			'agent': false,
			'headers': {
				"Accept": "application/json",
				"Content-Type": "application/json",
				'User-Agent': 'Request for Express'
			}
		};
	}

	function addToken(options, req) {
		if (req.session.passport && req.session.passport.user && req.session.passport.user && req.session.passport.user.token) {
			options.headers['Authorization'] = "Bearer " + req.session.passport.user.token;
		}
		return options;
	}

	function addParams(options, req) {
		var postData = !req.body ? '' : JSON.stringify(req.body || {});
		// options.headers['Content-Length'] = postData.length;
		options.params = postData;
	}

	function addContentLength(options) {
		if (options.params) {
			options.headers['Content-Length'] = options.params.length;
		}
	}

	function encodeUrl(url) {
		return urlencode(url);
	}

	function encodePamars(params) {
		var temp = [];
		for (var i = 0; i < params.length; i++) {
			var param = params[i];
			var tempParam = param.split("=")
			tempParam[1] = urlencode.decode(tempParam[1], 'utf8');
			tempParam[1] = tempParam[1].replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
			console.log(tempParam[1]);
			if (i < (params.length - 1)) {
				if (/[:&+/?%#=]/g.test(tempParam[1])) {
					temp.push(tempParam[0] + "=" + encodeUrl(tempParam[1]) + "&");
				} else {
					temp.push(tempParam[0] + "=" + tempParam[1] + "&");
				}
			} else {
				if (/[:&+/?%#=]/g.test(tempParam[1])) {
					temp.push(tempParam[0] + "=" + encodeUrl(tempParam[1]));
				} else {
					temp.push(tempParam[0] + "=" + tempParam[1]);
				}
			}
		}
		return temp.join("");
	}

	function handlePamars(url) {
		var tempUrl = url;
		// if(url.indexOf("?")!=-1){
		// 	var temp=url.split("?");
		// 	var params=""; 
		// 	if(temp[1]&&temp[1].indexOf("&")!=-1){
		// 		params=encodePamars(temp[1].split("&"));
		// 	}else{
		// 		params=encodePamars([temp[1]]);
		// 	}
		// 	return temp[0]+"?"+params;
		// }else {
		// 	return tempUrl;
		// } 
		return tempUrl;
	}

	function splitServiceFromUrl(url) {
		var catalog = url.substring(1, url.indexOf('/', 1));
		var pathUrl = url.substring(url.indexOf('/', 1));
		var fullPath = settings.restful.url + catalog + settings.restful.version + pathUrl;
		return fullPath
	}

	function splitUrl(fullUrl) {
		if(settings.prefix&&settings.prefix.length>1){
			fullUrl=fullUrl.substring(settings.prefix.length-1);
		}
		var url = fullUrl.substring(4);
		return url;
	}

	function searchService(services, name) {
		if (services[name]) {
			console.log(services[name]);
			return false;
		} else {
			return true;
		}
	}

	function checkReq(req, res) {
		var flag = true;
		// if(flag&&req.headers&&!req.headers['service-catalog']){
		// 	res.status(400);
		// 	res.send({"errors":{},"message":"缺少必要请求参数,服务目录名称是必填项"}); 
		// 	flag=false;
		// }
		// if(flag&&req.session.passport&&req.session.passport.user&&!req.session.passport.user.service_catalog){
		// 	res.status(404);
		// 	res.send({"errors":{},"message":"服务目录未加载,请重新登录"}); 
		// 	flag=false;
		// }
		// if(flag&&searchService(req.session.passport.user.service_catalog,req.headers['service-catalog'])){
		// 	res.status(404);
		// 	res.send({"errors":{},"message":"服务目录未查询到请求服务,请确认参数正确"}); 
		// 	flag=false; 
		// }
		return flag;
	}

	function checkJson(req) {
		if (req.headers && req.headers['content-type'] == 'application/json') {
			return true;
		} else {
			return false;
		}
	}

	function get(req, res, next) {
		var url = splitUrl(req.originalUrl);
		var options = getOptions(url, 'GET');
		addToken(options, req);
		function _success(data, response) {
			logger.info('back data:', data);
			if (response.statusCode >= 400 || !data) {
				logger.error(options, data);
				res.send(data);
			} else {
				res.send(data);
			}
		}
		function _fail(err) {
			logger.error(options, err);
			res.send(err);
		}
		rest.restClient(options, _success, _fail);
	}

	function post(req, res, next) {
		var url = splitUrl(req.originalUrl);
		var options = getOptions(url, 'POST');
		addToken(options, req);
		addParams(options, req);
		function _success(data, response) {
			logger.info('back data:', data);
			if (response.statusCode >= 400) {
				logger.error(options, data);
				res.send(data);
			} else if (!data || 'null' == data || "null\n" == data || '{}' == data) {
				res.send({
					code: 200,
					message: '操作成功!'
				});
			} else {
				res.send(data);
			}
		}
		function _fail(err) {
			logger.error(options, err);
			res.send(err);
		}
		rest.restClient(options, _success, _fail);
	}

	function put(req, res, next) {
		var url = splitUrl(req.originalUrl);
		var options = getOptions(url, 'PUT');
		addToken(options, req);
		addParams(options, req);
		function _success(data, response) {
			logger.info('back data:', data);
			if (response.statusCode >= 400) {
				logger.error(options, data);
				res.send(data);
			} else if (!data || 'null' == data || "null\n" == data || '{}' == data) {
				res.send({
					code: 200,
					message: '操作成功!'
				});
			} else {
				res.send(data);
			}
		}
		function _fail(err) {
			logger.error(options, err);
			res.send(err);
		}
		rest.restClient(options, _success, _fail);
	}

	function patch(req, res, next) {
		var url = splitUrl(req.originalUrl);
		var options = getOptions(url, 'PATCH');
		addToken(options, req);
		addParams(options, req);
		function _success(data, response) {
			logger.info('back data:', data);
			if (response.statusCode >= 400) {
				logger.error(options, data);
				res.send(data);
			} else if (!data) {
				res.send({
					code: 200,
					message: '操作成功!'
				});
			} else {
				res.send(data);
			}
		}
		function _fail(err) {
			logger.error(options, err);
			res.send(err);
		}
		rest.restClient(options, _success, _fail);
	}

	function head(req, res, next) {
		var url = splitUrl(req.originalUrl);
		var options = getOptions(url, 'HEAD');
		addToken(options, req);
		addParams(options, req);
		function _success(data, response) {
			logger.info('back data:', data);
			if (response.statusCode >= 400) {
				logger.error(options, data);
				res.send(data);
			} else if (!data) {
				res.send({
					code: 200,
					message: '操作成功!'
				});
			} else {
				res.send(data);
			}
		}
		function _fail(err) {
			logger.error(options, err);
			res.send(err);
		}
		rest.restClient(options, _success, _fail);
	}

	function del(req, res, next) {
		var url = splitUrl(req.originalUrl);
		var options = getOptions(url, 'DELETE');
		addToken(options, req);
		addParams(options, req);
		addContentLength(options);
		function _success(data, response) {
			logger.info('back data:', data);
			if (response.statusCode >= 400) {
				logger.error(options, data);
				res.send(data);
			} else if (!data || (data && !data.message)) {
				res.send({
					code: 200,
					action: "delete",
					message: '删除成功'
				});
			} else {
				res.send(data);
			}
		}
		function _fail(err) {
			logger.error(options, err);
			res.send(err);
		}
		rest.restClient(options, _success, _fail);
	}

	return {
		'get': get,
		'post': post,
		'put': put,
		'patch': patch,
		'head': head,
		'delete': del
	};
};

exports['@singleton'] = true;
exports['@require'] = ['igloo/logger', 'utils/rest', 'igloo/settings'];