package com.uas.eis.exception;

import com.uas.eis.entity.ErrorMessage;
import com.uas.eis.sdk.entity.ApiResult;
import org.apache.log4j.Logger;
import org.springframework.http.HttpStatus;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import javax.servlet.http.HttpServletRequest;


@ControllerAdvice
public class ExceptionHandlerAdvice {

	private final static Logger logger = Logger.getLogger(ExceptionHandlerAdvice.class);
	
	/**
	 * 处理未被发现处理的运行时抛出异常
	 * 
	 * @param ex
	 * @return
	 */
	@ExceptionHandler(RuntimeException.class)
	@ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
	@ResponseBody
	public ModelMap handleUnexpectedServerError(RuntimeException ex, HttpServletRequest request) {
		ModelMap map = new ModelMap();
		//logger.error(ex);
		ex.printStackTrace();
		map.put("code", ErrorMessage.SYS_ILLEGAL.getCode());
		map.put("message", StringUtils.isEmpty(ex.getMessage())?ErrorMessage.SYS_ILLEGAL.getMessage():ex.getMessage());
		map.put("requestId",request.getHeader("RequestId"));
		map.put("data",null);
		return map;
	}


	/**
	 * 处理通过BaseUtil.showError抛出的异常
	 *
	 * @param ex
	 * @return
	 */
	@ExceptionHandler(SystemException.class)
	@ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
	@ResponseBody
	public ModelMap handleSystemError(SystemException ex, HttpServletRequest request) {
		ModelMap map = new ModelMap();
		ApiResult apiResult = ex.getApiResult();
		map.put("code", apiResult.getCode());
		map.put("message",apiResult.getMessage());
		map.put("requestId",apiResult.getRequestId());
		map.put("data",apiResult.getData());
		return map;
	}
	
	/**
	 * 处理通过Api接口抛出的异常
	 * 
	 * @param ex
	 * @return
	 */
	@ExceptionHandler(ApiSystemException.class)
	@ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
	@ResponseBody
	public ModelMap handleApiSystemError(ApiSystemException ex, HttpServletRequest request) {
		ModelMap map = new ModelMap();
		ApiResult apiResult = ex.getApiResult();
		map.put("code", apiResult.getCode());
		map.put("message", apiResult.getMessage());
		map.put("requestId",apiResult.getRequestId());
		map.put("data",apiResult.getData());
		return map;
	}

}
