package com.keao.edu.common.controller;

import com.keao.edu.common.entity.HttpResponseResult;
import com.keao.edu.common.exception.BizException;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

import javax.servlet.http.HttpServletRequest;

@ControllerAdvice
public class BaseController {

	private final static Logger logger = LoggerFactory.getLogger(BaseController.class);

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

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

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

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

	public static <T> HttpResponseResult<T> failed() {
		return failed("");
	}

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

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

	private static <T> HttpResponseResult<T> getResponseData(boolean status, HttpStatus statusCode, T data, String message) {
		HttpResponseResult<T> obj = new HttpResponseResult<T>();
		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<String> handleException(Exception ex, HttpServletRequest request) {
		Throwable e = ExceptionUtils.getRootCause(ex);
		if (e == null) {
			e = ex;
		}
		logger.error("System Error", ex);
		// return failed(e.getMessage());
		if (e instanceof BizException) {
			return failed(e.getMessage());
		} else if (e instanceof AccessDeniedException) {
			return failed("禁止访问");
		}
		return failed("系统繁忙");
	}

}
