package com.wechat.common.utils;

import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.sql.Date;
import java.sql.Time;
import java.sql.Timestamp;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.List;

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

import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.servlet.ModelAndView;

import com.wechat.common.utils.view.JSONView;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
/**
 * springMVC返回值工具类
 * 

 */
@SuppressWarnings("all")
public class MvcUtil {
	private static final JSONView jsonLibView = new JSONView();
	private static final SimpleDateFormat FORMAT_DATE = new SimpleDateFormat(
			"yyyy-MM-dd");
	private static final SimpleDateFormat FORMAT_TIME = new SimpleDateFormat(
			"hh:mm:ss");
	private static final SimpleDateFormat FORMAT_TIMESTAMP = new SimpleDateFormat(
			"yyyy-MM-dd hh:mm:ss");

	public MvcUtil() {
	}

	public static ModelAndView jsonObjectModelAndView(JSONObject jsonObject) {
		return new ModelAndView(jsonLibView, "jsonObject", jsonObject);
	}

	public static ModelAndView jsonArrayModelAndView(JSONArray jsonArray) {
		return new ModelAndView(jsonLibView, "jsonArray", jsonArray);
	}

	public static boolean checkBindingResult(BindingResult bindingResult,
			JSONObject returnObject) {
		if (bindingResult.hasErrors()) {
			if (bindingResult.hasFieldErrors()) {
				List list = bindingResult.getFieldErrors();
				JSONObject errors = new JSONObject();
				for (int i = 0; i < list.size(); i++) {
					FieldError fieldError = (FieldError) list.get(i);
					errors.element(fieldError.getField(), fieldError
							.getRejectedValue().toString());
				}

				returnObject.element("errors", errors);
			}
			if (bindingResult.hasGlobalErrors()) {
				List list = bindingResult.getGlobalErrors();
				String errorMessage = "";
				for (int i = 0; i < list.size(); i++) {
					ObjectError fieldError = (ObjectError) list.get(i);
					if (i > 0)
						errorMessage = (new StringBuilder(String
								.valueOf(errorMessage))).append("; ")
								.toString();
					errorMessage = (new StringBuilder(String
							.valueOf(errorMessage))).append(
							fieldError.getDefaultMessage()).toString();
				}

				returnObject.element("errorMessage", errorMessage);
			}
			return false;
		} else {
			return true;
		}
	}

	public static void main(String[] args) {
		Object obj=(Object)"120";
		System.out.println(toJsonString(obj));
	}
	public static String toJsonString(Object obj) {
		if (obj != null){
			if(obj instanceof Double ||obj instanceof BigDecimal){
				DecimalFormat df = new DecimalFormat("#0.00");
				return df.format(Double.parseDouble(obj.toString()));
			}else{
				return obj.toString();
			}
		}
			
		else
			return null;
	}

	public String toJsonString(Date obj) {
		if (obj != null)
			return FORMAT_DATE.format(obj);
		else
			return null;
	}

	public String toJsonString(Time obj) {
		if (obj != null)
			return FORMAT_TIME.format(obj);
		else
			return null;
	}

	public static String toJsonString(Timestamp obj) {
		if (obj != null)
			return FORMAT_TIMESTAMP.format(obj);
		else
			return null;
	}

	public static Long parseLong(HttpServletRequest request, String paramName) {
		Long result = null;
		String s = request.getParameter(paramName);
		if (s != null && !"".equals(s))
			result = Long.valueOf(Long.parseLong(s));
		return result;
	}

	public static String toBigString(Object obj) {
		if (obj != null)
			return obj.toString();
		else
			return "0.00";
	}

	public static String toBigString2(Object obj) {
		if (obj != null && !"".equals(obj.toString()))
			return new BigDecimal(obj.toString()).setScale(2, RoundingMode.HALF_UP).toString();
		else
			return "";
	}
	
	public static void writeJson(HttpServletRequest request, HttpServletResponse response, String json)
			throws IOException {
		response.setContentType("text/html;charset=utf-8");
		String clientOrigin = request.getHeader("origin");
		PrintWriter out = response.getWriter();
		response.setHeader("Cache-control", "no-cache, no-store");
		response.setHeader("Pragma", "no-cache");
		response.setHeader("Expires", "-1");
		response.setHeader("Access-Control-Allow-Methods", "POST");
		response.setHeader("Access-Control-Allow-Origin", clientOrigin);
		response.setHeader("Access-Control-Allow-Headers", "Content-Type");
		response.setHeader("Access-Control-Max-Age", "86400");

		out.println(json);
		out.close();
	}
	
}
