package com.ym.mec.common.controller;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

import com.ym.mec.common.entity.HttpResponseResult;

@ControllerAdvice
public class BaseController {
	
	private final static Logger logger = LoggerFactory.getLogger(BaseController.class);

	public static HttpResponseResult succeed(Object object) {
		return getResponseData(true, HttpStatus.OK, object, "");
	}

	public static HttpResponseResult succeed() {
		return getResponseData(true, HttpStatus.OK, null, "");
	}

	public static HttpResponseResult succeedData(Object obj) {
		return getResponseData(true, HttpStatus.OK, obj, "操作成功");
	}

	public static HttpResponseResult warned(String message) {
		return failed(HttpStatus.MULTI_STATUS, message);
	}

	public static HttpResponseResult failed() {
		return failed("");
	}

	public static HttpResponseResult failed(String msg) {
		return failed(HttpStatus.INTERNAL_SERVER_ERROR, msg);
	}

	public static HttpResponseResult failed(HttpStatus statusCode, String msg) {
		return getResponseData(false, statusCode, null, msg);
	}

	private static HttpResponseResult getResponseData(boolean status, HttpStatus statusCode, Object data, String message) {
		HttpResponseResult obj = new HttpResponseResult();
		obj.setStatus(status);
		obj.setCode(statusCode.value());
		obj.setData(data);
		obj.setMsg(message);
		return obj;
	}
	
	/**
	 * 处理一般异常
	 * 
	 * @param ex
	 * @param request
	 * @return
	 */
	@ExceptionHandler(Exception.class)
	public HttpResponseResult handleException(Exception ex, HttpServletRequest request) {
		Throwable e = ExceptionUtils.getRootCause(ex);
		if (e == null) {
			e = ex;
		}

		logger.error("System Error", e);
		return failed(e.getMessage());
	}

}
