package com.mrkj.ygl.util;

import java.io.IOException;
import java.security.MessageDigest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;
import org.codehaus.jackson.map.ObjectMapper;

public class MrksUtils {

	public static String getEasyUIDataGridModel(List<Map<String, String>> model,Long count) throws Exception{
		Map<String, Object> resultMap = new HashMap<String, Object>();
		ObjectMapper om = new ObjectMapper();
		resultMap.put("rows", model);
		resultMap.put("total", count);
		return om.writeValueAsString(resultMap);
	}
	
	public static void responseWriteJson(HttpServletResponse resp,String result){
		resp.setCharacterEncoding("UTF-8");
		resp.setContentType("application/json; charset=utf-8");
		try {
			resp.getWriter().print(result);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	
	/**
	 * 根据 ans_id 获取答案
	 * @param ans_id
	 * @return
	 */
	public static int statistics (String ...ans_id){		//String...为动态参数,等同于数组
		//String与StringBuffer都可以存储和操作字符串，StringBuffer操作字符串要比String性能好
		StringBuffer sb = new StringBuffer("");
		for (String id : ans_id){
			sb.append(id);						//使用StringBuffer拼接字符串
		}
		char[] cArr = sb.toString().toCharArray();		//把字符串转换为char数组
		int result = 0;			//记录字符串总和	
		for (char c : cArr){
			result += c+0;				//求char数组总和
		}
		return result;			//返回求得的char数组总和
	}

	public static String md5(String str) {
		try {
			//使用Java.security.MessageDigest类实现了MD5算法
			MessageDigest md = MessageDigest.getInstance("MD5");
			//固定写法首先调用update更新
			md.update(str.getBytes());
			//更新后的Byte数组
			byte b[] = md.digest();
			int i;
			StringBuffer buf = new StringBuffer("");
			//固定算法
			for (int offset = 0; offset<b.length; offset++) {
				i = b[offset];
				if (i< 0)
					i += 256;
				if (i< 16)
					buf.append("0");
				buf.append(Integer.toHexString(i));
			}
			str = buf.toString();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return  str;
	}

	public static String TrasformDateToString (Date date){
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
		
		if (date != null){
			return sdf.format(date);
		}else{
			return null;
		}
	}
	
	public static String TrasformGetimeToString (Long date){
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
		
		if (date != null){
			return sdf.format(new Date(date));
		}else{
			return null;
		}
	}
}
