package org.linlinjava.jz.hm.exception;

import org.linlinjava.jz.hm.util.HmResponseUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;


import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

@ControllerAdvice
public class ExceptionAdvice {

//	@Autowired
//	RedisTemplate redisTemplate;

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

	/**
	 * 应用到所有@RequestMapping注解方法，在其执行之前初始化数据绑定器
	 * 
	 * @param binder
	 */
	@InitBinder
	public void initBinder(WebDataBinder binder) {
	}

	/**
	 * 把值绑定到Model中，使全局@RequestMapping可以获取到该值
	 * 
	 * @param model
	 */
	// @ModelAttribute
	// public void addAttributes(Model model) {
	// model.addAttribute("author", "Magical Sam");
	// }

	/**
	 * 全局异常捕捉处理
	 * 
	 * @param ex
	 * @return
	 */
	// @RequestMapping
	@ResponseBody
	@ExceptionHandler({ Error.class, Exception.class, Throwable.class })
	public Object errorHandler(HttpServletRequest request, Exception ex) {
		ex.printStackTrace();
		// logger.info("sys_exception:" + ex.getMessage() + "/n" + ex.toString());

//		String url = request.getRequestURI();
//		if (!(url.indexOf("find") != -1 || url.indexOf("select") != -1)) {// 重复提交校验 urlRequestConfig.comperUrl(url)
//			String token = request.getHeader("token");
//			if (null == token) {
//				token = request.getParameter("token");
//			}
//			if (token != null) {
//				try {
//					redisTemplate.delete(token + url);
//				} catch (Exception e) {
//				}
//			}
//		}

		if (ex instanceof LoginException) {
			// return new ResponseEntity<Map<String, Object>>(obj, HttpStatus.UNAUTHORIZED);
			return HmResponseUtil.fail("请登录", "401");// 登录过时或未登录
		}

		if (ex instanceof PromiseException) {
			return HmResponseUtil.fail("没有操作权限", "400");// 没权限
		}

		if (ex instanceof MethodArgumentNotValidException) {// 业务校验不通过
			MethodArgumentNotValidException exmessage = (MethodArgumentNotValidException) ex;
			return HmResponseUtil.fail("501",exmessage.getBindingResult().getFieldError().getDefaultMessage());
		}
		if (ex instanceof UnsupportException) {// 业务异常
			return HmResponseUtil.fail("501",ex.getMessage());
		}

		if (ex instanceof BusinessException) {// 业务异常
			return HmResponseUtil.fail("502",ex.getMessage());
		}
		if (ex instanceof RuntimeException) {// 业务异常
			return HmResponseUtil.fail("502",ex.getMessage());
		}

//		Map<String, Object> obj = new HashMap<String, Object>();
//		obj.put("errno", 502);// 其他错误
//		obj.put("data", ex.toString() + "---" +getErrorMsg(ex));
//		obj.put("requesturl", request.getRequestURI());
		return HmResponseUtil.fail("502",request.getRequestURI()+"---"+ex.toString() + "---" +getErrorMsg(ex));
		
//		return obj;
	}

	public String getErrorMsg(Exception ex) {
		StringBuilder sbException = new StringBuilder();
		int i = 0;
		for (StackTraceElement ele : ex.getStackTrace()) {
			sbException
					.append(ele.getClassName() + ele.getMethodName() + ele.getFileName() + ele.getLineNumber() + "\n");
			if (i > 4) {
				break;
			}
			i++;
		}
		return sbException.toString();
	}

}