package com.wechat.global;

import java.io.IOException;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;

import com.alibaba.fastjson.JSON;
import com.wechat.common.Constants;
import com.wechat.common.utils.MvcUtil;
import com.wechat.common.utils.StringsUtils;
import com.wechat.global.message.InfoMsg;
import com.wechat.model.responseDto.JsonResp;
import com.wechat.service.CommonService;

/**
 * handle the global runtime exception which did not handled in the code
 * 
 * @author xueh
 */
@ControllerAdvice
public class GlobalExceptionHandler {
	private static final Log logger = LogFactory.getLog(GlobalExceptionHandler.class);

	@Resource
	private CommonService commonService;

	@ExceptionHandler(MethodArgumentNotValidException.class)
	@ResponseStatus(HttpStatus.OK)
	public void processValidationError(MethodArgumentNotValidException argEx, HttpServletRequest request,
			HttpServletResponse response) {
		JsonResp<String> resp;
		BindingResult result = argEx.getBindingResult();
		if (result.hasErrors()) {
			StringBuffer msgBuffer = new StringBuffer();
			String lang = commonService.getLanguage(request);
			List<FieldError> fieldErrors = result.getFieldErrors();
			for (FieldError fieldError : fieldErrors) {
				msgBuffer.append(getMsgByLang(fieldError.getDefaultMessage(), lang) + ";");
			}
			resp = new JsonResp<String>(Constants.VALID_ERROR + "", msgBuffer.toString());
		} else {
			resp = new JsonResp<String>(Constants.VALID_ERROR + "", "");
		}
		String json = JSON.toJSONString(resp, true);
		try {
			MvcUtil.writeJson(request, response, json);
		} catch (IOException e) {
			logger.error(e);
		}
	}

	@ExceptionHandler(Exception.class)
	//@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
	public void handleException(Exception ex, HttpServletRequest request, HttpServletResponse response) {
		ex.printStackTrace();
		String lang = commonService.getLanguage(request);
		JsonResp<String> resp;
		String json = "";
		if (ex instanceof CustomException) {
			response.setStatus(HttpStatus.OK.value());
			CustomException cex = (CustomException) ex;
			resp = new JsonResp<String>(cex.getCode(), getMsgByLang(cex.getMessage(), lang));
			//response.getStatus();
		} else {
			response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
			// resp = new JsonResp<String>(Constants.RESULT_ERROR,
			// InfoMsg.ERROR_SYSTEM_ERROR);
			resp = new JsonResp<String>(InfoMsg.ERROR_SYSTEM_ERROR.getCode(),
					getMsgByLang(InfoMsg.ERROR_SYSTEM_ERROR.getMsg(), lang));
		}
		json = JSON.toJSONString(resp, true);
		logger.error(ex.getMessage());
		try {
			MvcUtil.writeJson(request, response, json);
		} catch (IOException e) {
			logger.error(e);
		}
	}

	/**
	 * 处理消息 区分中英文显示
	 * 
	 * @param msg
	 * @param lang
	 * @return
	 */
	private String getMsgByLang(String msg, String lang) {
		String message = "";
		if (StringsUtils.isEmpty(lang)) {
			message = msg.indexOf("|") > 0 ? msg.split("\\|")[0] : msg;
		} else {
			// 中文
			if (StringsUtils.isEqual("zh", lang)) {
				message = msg.indexOf("|") > 0 ? msg.split("\\|")[0] : msg;
			}
			// 英文
			else if (StringsUtils.isEqual("en", lang)) {
				message = msg.indexOf("|") > 0 ? msg.split("\\|")[1] : msg;
			}else {
				message = msg;
			}
		}
		return message;
	}
}
