package com.wechat.global;

import javax.servlet.http.Cookie;

import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.web.bind.annotation.ControllerAdvice;

import com.wechat.common.Constants;
import com.wechat.common.utils.StringsUtils;
import com.wechat.model.responseDto.ResultEntity;

@ControllerAdvice
public class ResponseAdvice implements org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice<Object> {

	@Override
	public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
		return true;
	}

	@Override
	public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType,
			Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request,
			ServerHttpResponse response) {
		if(body instanceof ResultEntity) {
			@SuppressWarnings("unchecked")
			ResultEntity<Object> entity = (ResultEntity<Object>)body;
			String msg = entity.getMsg();
			Cookie[] cookies = ((ServletServerHttpRequest) request).getServletRequest().getCookies();
			String lang = "";
			if (cookies == null) {
				lang = "zh";
			}else {
				for (Cookie cookie : cookies) {
					if (cookie.getName().equalsIgnoreCase(Constants.LANGUAGE)) {
						lang = cookie.getValue();
					}
				}
				if(StringsUtils.isEmpty(lang)) {
					lang = "zh";
				}
			}
			entity.setMsg(getMsgByLang(msg,lang));
		}
		return body;
	}
	/**
	 * 处理消息 区分中英文显示
	 * 
	 * @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;
	}
}
