package com.ylcm.sys.common;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.security.MessageDigest;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

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

import org.apache.commons.lang.StringUtils;

import com.ylcm.sys.domain.User;

import net.sf.json.JSONObject;

/**
 * 其他非业务相关普通工具类
 * 
 * @author Jump
 * 
 */
public class Util {

	public static boolean emailFormat(String email) {
		boolean tag = true;
		final String pattern1 = "^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
		final Pattern pattern = Pattern.compile(pattern1);
		final Matcher mat = pattern.matcher(email);
		if (!mat.find()) {
			tag = false;
		}
		return tag;
	}

	// 去除a链接，保留文字
	public static String removeLinkTags(String content) {
		if (content != null && !("").equals(content)) {
			Pattern p = Pattern.compile("<a.*?/a>");
			Matcher m = p.matcher(content);
			while (m.find()) {
				Matcher href = Pattern.compile("href=.*? ").matcher(m.group());
				while (href.find()) {
					String url = href.group().replaceAll("href=|\"|>", "");
					content = content.replaceAll(m.group(), url);
				}
			}
		}
		return content;
	}

	/**
	 * 统计字串在源字符串中出现的次数
	 * 
	 * @param origStr
	 *            源字符串
	 * @param subStr
	 *            子串
	 * @return 字串出现的次数
	 */
	public static int countSubStr(String origStr, String subStr) {
		int count = 0;
		if (origStr != null && !("").equals(origStr) && subStr != null
				&& !("").equals(subStr)) {
			int index = 0;
			while ((index = origStr.indexOf(subStr, index)) != -1) {
				count++;
				index += subStr.length();
			}
		}
		return count;
	}

	public static int[] showPage(int page, int lastpage) {
		int k[];
		if (lastpage <= 10) {
			k = new int[lastpage];
			for (int i = 0; i < lastpage; i++) {
				k[i] = i + 1;
			}
		} else if (page + 10 > lastpage) {
			k = new int[10];
			for (int i = 0; i < 10; i++) {
				k[i] = lastpage - 10 + i + 1;
			}
		} else if (page + 10 <= lastpage && page < 7) {
			k = new int[10];
			for (int i = 0; i < 10; i++) {
				k[i] = i + 1;
			}
		} else if (page + 10 <= lastpage && page >= 7) {
			k = new int[10];
			for (int i = 0; i < 10; i++) {
				k[i] = page - 5 + i;
			}
		} else {
			k = new int[10];
		}
		return k;
	}

	@SuppressWarnings("rawtypes")
	public static boolean isNull(Object argObj) {

		if (argObj == null) {
			return true;
		}

		if (argObj instanceof String) {

			if (((String) argObj).trim().equals("")
					|| ((String) argObj).trim().equals(" ")
					|| ((String) argObj).trim().equals("null")) {
				return true;
			}
		}

		if (argObj instanceof Collection) {

			if (((Collection) argObj).size() == 0) {
				return true;
			}
		}

		if (argObj instanceof Map) {

			if (((Map) argObj).size() == 0) {
				return true;
			}
		}

		return false;
	}

	public static boolean isNotNull(Object argObj) {
		return !Util.isNull(argObj);
	}

	// 获取数组不同数据
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public static List getNoNum(String[] a, String[] b) {
		List list = new ArrayList();
		if (Util.isNull(b)) {
			for (int i = 0; i < a.length; i++) {
				list.add(a[i]);
			}
		} else {
			String[] la = a;
			String[] lb = b;
			for (int i = 0; i < la.length; i++) {
				boolean boo = false;
				for (int j = 0; j < lb.length; j++) {
					if (la[i].equals(lb[j])) {
						boo = true;
						break;
					}
				}
				if (!boo) {
					list.add(la[i]);
				}
			}
		}
		return list;
	}

	/**
	 * 获取客户端IP
	 * 
	 * @param request
	 * @return
	 */
	public static String getIpAddr(HttpServletRequest request) {
		String ip = request.getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		return ip;
	}

	/**
	 * 过滤html标签
	 * 
	 * @param inputString
	 * @return
	 */
	public static String html2Text(String inputString) {
		String htmlStr = inputString; // 含html标签的字符串
		String textStr = "";
		java.util.regex.Pattern p_script;
		java.util.regex.Matcher m_script;
		java.util.regex.Pattern p_style;
		java.util.regex.Matcher m_style;
		java.util.regex.Pattern p_html;
		java.util.regex.Matcher m_html;
		java.util.regex.Pattern p_html1;
		java.util.regex.Matcher m_html1;

		try {
			String regEx_script = "<[\\s]*?script[^>]*?>[\\s\\S]*?<[\\s]*?\\/[\\s]*?script[\\s]*?>"; // 定义script的正则表达式{或<script[^>]*?>[\\s\\S]*?<\\/script>
			String regEx_style = "<[\\s]*?style[^>]*?>[\\s\\S]*?<[\\s]*?\\/[\\s]*?style[\\s]*?>"; // 定义style的正则表达式{或<style[^>]*?>[\\s\\S]*?<\\/style>
			String regEx_html = "<[^>]+>"; // 定义HTML标签的正则表达式
			String regEx_html1 = "<[^>]+";

			p_script = Pattern.compile(regEx_script, Pattern.CASE_INSENSITIVE);
			m_script = p_script.matcher(htmlStr);
			htmlStr = m_script.replaceAll(""); // 过滤script标签

			p_style = Pattern.compile(regEx_style, Pattern.CASE_INSENSITIVE);
			m_style = p_style.matcher(htmlStr);
			htmlStr = m_style.replaceAll(""); // 过滤style标签

			p_html = Pattern.compile(regEx_html, Pattern.CASE_INSENSITIVE);
			m_html = p_html.matcher(htmlStr);
			htmlStr = m_html.replaceAll(""); // 过滤html标签

			p_html1 = Pattern.compile(regEx_html1, Pattern.CASE_INSENSITIVE);
			m_html1 = p_html1.matcher(htmlStr);
			htmlStr = m_html1.replaceAll(""); // 过滤html标签
			textStr = htmlStr;

		} catch (Exception e) {
			System.err.println("Html2Text: " + e.getMessage());
		}

		return textStr;// 返回文本字符串
	}

	/**
	 * 验证 <\/br>
	 * 
	 * @param content
	 * @return
	 */
	public static boolean isBlank(String content) {
		boolean isBlank = StringUtils.isBlank(content);

		if (!isBlank) {
			content = content.trim();
			isBlank = content.equals("<br>");
		}

		return isBlank;
	}

	// 特殊字符过滤
	public static String SpecialCharactersFilter(String content) {
		String filterCharacters = "[!@#$%^&*()_+-=,. /?']";
		content = content.replaceAll(filterCharacters, "");

		return content;
	}

	/**
	 * 比当今时间大，返回1 比当今时间小，返回-1 跟当今时间相同，返回0
	 * 
	 * @param date
	 *            起始时间
	 * @param keepTime单位
	 *            ：秒，持续时间
	 * @return
	 */
	public static int compareWithCurrentTime(Date date, int keepTime) {
		// 秒转为毫秒
		keepTime *= 1000;
		Calendar c = Calendar.getInstance();
		c.setTime(date);
		int i = 0;
		long l = c.getTimeInMillis() + keepTime - System.currentTimeMillis();
		if (l > 0) {
			i = 1;
		} else if (l < 0) {
			i = -1;
		} else {
			i = 0;
		}

		return i;
	}

	/**
	 * 获取每月多少天
	 * 
	 * @param year
	 * @param month
	 * @return
	 */
	public static int getDayCount(int year, int month) {
		int result = 0;
		if (1 == month || 3 == month || 5 == month || 7 == month || 8 == month
				|| 10 == month || 12 == month) {
			result = 31;
		} else if (4 == month || 6 == month || 9 == month || 11 == month) {
			result = 30;
		} else if (2 == month) {
			if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) {
				result = 29;
			} else {
				result = 28;
			}
		}
		return result;
	}

	/**
	 * 截取字符串，超出部分用省略号代替
	 * 
	 * @param content
	 *            内容
	 * @param len
	 *            长度
	 * @return 截取后的长度
	 */
	public static String getSubStrLen(String content, int len) {
		if (content != null && !("").equals(content.trim())) {
			if (content.length() > len) {
				String subStr = content.substring(0, len - 1);
				content = subStr.concat("...");
			}
		}
		return content;
	}

	/**
	 * 判断是否有js、sql注入，存在，返回true 没有js和sql注入，进行html文本去除，若去除结果为空，返回true
	 * 否则返回false，证明内容很正常，尽情的插入吧！！！
	 * 
	 * @param content
	 * @return
	 */
	public static boolean isInputIllegal(String content) {
		boolean isIllegal = false;
		// 允许内容为空
		if (StringUtils.isBlank(content))
			isIllegal = false;
		// 去除html标签后与原内容不相同，说明包含html标签，属于不合法内容
		if (content.length() != html2Text(content).length())
			isIllegal = true;

		return isIllegal;
	}

	/**
	 * Filter the specified string for characters that are sensitive to HTML
	 * interpreters, returning the string with these characters replaced by the
	 * corresponding character entities.
	 * 
	 * @param value
	 *            The string to be filtered and returned
	 */
	public static String filter(String value) {

		if (value == null || value.length() == 0) {
			return value;
		}

		StringBuilder result = null;
		String filtered = null;
		for (int i = 0; i < value.length(); i++) {
			filtered = null;
			switch (value.charAt(i)) {
			case '<':
				filtered = "&lt;";
				break;
			case '>':
				filtered = "&gt;";
				break;
			case '&':
				filtered = "&amp;";
				break;
			case '"':
				filtered = "&quot;";
				break;
			case '\'':
				filtered = "&#39;";
				break;
			}

			if (result == null) {
				if (filtered != null) {
					result = new StringBuilder(value.length() + 50);
					if (i > 0) {
						result.append(value.substring(0, i));
					}
					result.append(filtered);
				}
			} else {
				if (filtered == null) {
					result.append(value.charAt(i));
				} else {
					result.append(filtered);
				}
			}
		}

		return result == null ? value : result.toString();
	}

	public static String regexpFilter(String s) {
		if (s == null) {
			return "";
		}

		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < s.length(); i++) {
			char c = s.charAt(i);
			switch (c) {
			case '(':
				sb.append("\\(");
				break;
			case ')':
				sb.append("\\)");
				break;
			case '*':
				sb.append("\\*");
				break;
			case '?':
				sb.append("\\?");
				break;
			case '+':
				sb.append("\\+");
				break;
			case '.':
				sb.append("\\.");
				break;
			case '^':
				sb.append("\\^");
				break;
			case '[':
				sb.append("\\[");
				break;
			case ']':
				sb.append("\\]");
				break;
			case '\\':
				sb.append("\\\\");
				break;
			case '|':
				sb.append("\\|");
				break;
			case '{':
				sb.append("\\{");
				break;
			case '}':
				sb.append("\\}");
				break;
			case '/':
				sb.append("\\/");
				break;
			default:
				sb.append(c);
			}
		}
		return sb.toString();
	}

	// 去除空格啊之类的图标
	public static String replaceHtmlChar(String content) {
		HashMap<String, String> map = new HashMap<String, String>();
		map.put("&nbsp;", " ");
		map.put("&mdash;", "—");
		map.put("&ldquo;", "“");
		map.put("&rdquo;", "”");
		for (String key : map.keySet()) {
			content = content.replace(key, map.get(key));
		}
		return content;
	}

	public static String string2Json(String s) {
		if (s == null) {
			return "";
		}

		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < s.length(); i++) {
			char c = s.charAt(i);
			switch (c) {
			case '\"':
				sb.append("\\\"");
				break;
			case '\\':
				sb.append("\\\\");
				break;
			// case '/':
			// sb.append("\\/");
			// break;
			case '\b':
				sb.append("\\b");
				break;
			case '\f':
				sb.append("\\f");
				break;
			case '\n':
				sb.append("\\n");
				break;
			case '\r':
				sb.append("\\r");
				break;
			case '\t':
				sb.append("\\t");
				break;
			default:
				sb.append(c);
			}
		}
		return sb.toString();
	}

	public static boolean isCurrentUserType(HttpServletRequest request,
			String compTo) {
		String currentType = (String) request.getSession().getAttribute(
				"userType");
		return compTo.equals(currentType);
	}

	/**
	 * 获得域名 http:// 和 /之间的部分
	 * 
	 * @param baseUrl
	 * @return
	 */
	public static String getDomain(String baseUrl) {
		String domain = "";

		if (!StringUtils.isBlank(baseUrl)) {
			Pattern pattern = Pattern
					.compile("((?:http[s]?):\\/\\/)([^:\\/\\s]+|\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3})(:\\d+)?\\/");
			Matcher matcher = pattern.matcher(baseUrl);
			if (matcher.find()) {
				domain = matcher.group(2);
			}
		}

		return domain;
	}

	/**
	 * sql转义
	 * 
	 * @param value
	 *            The string to be filtered and returned
	 */
	public static String sqlEscape(String value) {

		if (Util.isNull(value)) {
			return value;
		}
		return value.replaceAll("\\\\", "").replaceAll("'", "''")
				.replaceAll("/", "\\/").replaceAll("%", "\\%")
				.replaceAll("_", "\\_").replace("*", "\\*").replace("?", "\\?");
	}

	/**
	 * spifix转义
	 * 
	 * @param value
	 *            The string to be filtered and returned
	 */
	public static String spEscape(String value) {

		if (Util.isNull(value)) {
			return value;
		}
		return value.replace("$", "").replace("^", "");
	}

	/**
	 * 获取字符串的长度，中文占一个字符,英文数字占半个字符，向下取整(同新浪)
	 * 
	 * @param value
	 *            指定的字符串
	 * @return 字符串的长度
	 */
	public static int countWords(String value) {
		double valueLength = 0;
		String chinese = "[\u4e00-\u9fa5]";
		// 获取字段值的长度，如果含中文字符，则每个中文字符长度为2，否则为1
		for (int i = 0; i < value.length(); i++) {
			// 获取一个字符
			String temp = value.substring(i, i + 1);
			// 判断是否为中文字符
			if (temp.matches(chinese)) {
				// 中文字符长度为1
				valueLength += 1;
			} else {
				// 其他字符长度为0.5
				valueLength += 0.5;
			}
		}
		// 进位取整
		return (int) Math.floor(valueLength);
	}

	// 判断整型
	public static boolean isNumeric(String str) {
		return str.matches("[//d]+");
	}

	// 判断字母
	public static boolean isEnLetters(String input) {
		Matcher m = Pattern.compile("[a-z]+", Pattern.CASE_INSENSITIVE)
				.matcher(input);
		return m.matches();
	}

	public static void ajax(HttpServletResponse response, String outString) {
		PrintWriter out = null;

		response.setHeader("content-type", "text/html");
		response.setCharacterEncoding("UTF-8");

		try {

			out = response.getWriter();
			out.write(outString);

		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (out != null) {
				out.flush();
				out.close();
			}
		}

	}

	public static void jsonAjax(HttpServletResponse response, String outString) {
		PrintWriter out = null;

		response.setHeader("content-type", "json/javascript");
		response.setCharacterEncoding("UTF-8");

		try {

			out = response.getWriter();
			out.write(outString);

		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (out != null) {
				out.flush();
				out.close();
			}
		}

	}

	/**
	 * 1. byte(8位有符号)的取值范围是 -128-127, char(16位无符号)的取值范围是0-65535;<BR>
	 * 2.如果一个byte对应的十六进制数只有一位前面要用0填充，因为MD5是32位的，达到统一的格式<BR>
	 * 3.0x是十六进制的标示，比如：0xFF表示8位的二进制1111 1111;0x00FF表示16位的二进制0000 0000 1111 1111
	 * */
	public static String getMD5(String str) {
		MessageDigest messageDigest = null;
		try {
			messageDigest = MessageDigest.getInstance("MD5");
			messageDigest.reset();
			messageDigest.update(str.getBytes("UTF-8"));
			byte[] byteArray = messageDigest.digest();
			StringBuffer md5StrBuff = new StringBuffer();
			for (int i = 0; i < byteArray.length; i++) {
				if (Integer.toHexString(0xFF & byteArray[i]).length() == 1)
					md5StrBuff.append("0").append(
							Integer.toHexString(0xFF & byteArray[i]));
				else
					md5StrBuff.append(Integer.toHexString(0xFF & byteArray[i]));
			}
			return md5StrBuff.toString();
		} catch (Exception e) {
			e.printStackTrace();
			return "";
		}
	}

	public static String friendlyNumber(int number) {

		if (number < 10000) {
			return String.valueOf(number);
		} else {
			int nn = number / 10000;
			return nn + "万+";
		}
	}

	public static String getRadomNum(int length) {
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < length; i++) {
			sb.append((int) (10 * (Math.random())));
		}
		return sb.toString();
	}

	/**
	 * 获取定长位数随机数字
	 * 
	 * @param length
	 *            位数
	 * @return 定长位数随机字符
	 */
	public static String getRandomMath(int length) { // length表示生成字符串的长度
		String base = "0123456789";
		Random random = new Random();
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < length; i++) {
			int number = random.nextInt(base.length());
			sb.append(base.charAt(number));
		}
		return sb.toString();
	}

	public static void main(String[] args) {
		// System.out.println(Util.sqlEscape("\\ x *sd"));
		// System.out.println(Util.sqlEscape("\\sd ''"));
		// System.out.println(Util.sqlEscape("? ''"));

		// for(int i=0; i<10; i++){
		// System.out.println(Util.getRadomNum(10));
		// }
		String str = "<dl class='comment_item comment_topic' id='comment_item_3720667'><dt class='comment_head' floor='1'>1楼 <span class='user'><a class='username' href='/li852617008' target='_blank'>li852617008</a> <span class='ptime'>2014-04-09 17:28发表</span>  <a href='#reply' class='cmt_btn reply' title='回复'>[回复]</a> <span class='comment_manage' style='display: none;' commentid='3720667' username='li852617008'> <a href='#quote' class='cmt_btn quote' title='引用'>[引用]</a> <a href='#report' class='cmt_btn report' title='举报'>[举报]</a></span></span></dt><dd class='comment_userface'><a href='/li852617008' target='_blank'><img src='http://avatar.csdn.net/C/5/E/3_li852617008.jpg' width='40' height='40'></a></dd><dd class='comment_body'>学习中</dd></dl>";
		System.out.println(Util.getImgSmallImgFromHtml(str));
        System.out.println(Util.isNumericKeepOneDecimal("2.2"));
	}

	/**
	 * 解析url参数到map
	 * 
	 * @param map
	 * @param data
	 * @param encoding
	 * @throws UnsupportedEncodingException
	 */
	@SuppressWarnings("rawtypes")
	public static void parseParameters(Map map, String data, String encoding)
			throws UnsupportedEncodingException {
		if ((data == null) || (data.length() <= 0)) {
			return;
		}

		byte[] bytes = null;
		try {
			if (encoding == null)
				bytes = data.getBytes();
			else
				bytes = data.getBytes(encoding);
		} catch (UnsupportedEncodingException uee) {
		}
		parseParameters(map, bytes, encoding);
	}

	@SuppressWarnings("rawtypes")
	public static void parseParameters(Map map, byte[] data, String encoding)
			throws UnsupportedEncodingException {
		if ((data != null) && (data.length > 0)) {
			int ix = 0;
			int ox = 0;
			String key = null;
			String value = null;
			while (ix < data.length) {
				byte c = data[(ix++)];
				switch ((char) c) {
				case '&':
					value = new String(data, 0, ox, encoding);
					if (key != null) {
						putMapEntry(map, key, value);
						key = null;
					}
					ox = 0;
					break;
				case '=':
					if (key == null) {
						key = new String(data, 0, ox, encoding);
						ox = 0;
					} else {
						data[(ox++)] = c;
					}
					break;
				case '+':
					data[(ox++)] = 32;
					break;
				case '%':
					data[(ox++)] = (byte) ((convertHexDigit(data[(ix++)]) << 4) + convertHexDigit(data[(ix++)]));

					break;
				default:
					data[(ox++)] = c;
				}
			}

			if (key != null) {
				value = new String(data, 0, ox, encoding);
				putMapEntry(map, key, value);
			}
		}
	}

	@SuppressWarnings("unchecked")
	private static void putMapEntry(@SuppressWarnings("rawtypes") Map map,
			String name, String value) {
		String[] newValues = null;
		String[] oldValues = (String[]) (String[]) map.get(name);
		if (oldValues == null) {
			newValues = new String[1];
			newValues[0] = value;
		} else {
			newValues = new String[oldValues.length + 1];
			System.arraycopy(oldValues, 0, newValues, 0, oldValues.length);
			newValues[oldValues.length] = value;
		}
		map.put(name, newValues);
	}

	private static byte convertHexDigit(byte b) {
		if ((b >= 48) && (b <= 57))
			return (byte) (b - 48);
		if ((b >= 97) && (b <= 102))
			return (byte) (b - 97 + 10);
		if ((b >= 65) && (b <= 70))
			return (byte) (b - 65 + 10);
		return 0;
	}

	// 获取img标签正则
	private static final String IMGURL_REG = "<img.*src=(.*?)[^>]*?>";
	// 获取src路径的正则
	private static final String IMGSRC_REG = "http:\"?(.*?)(\"|>|\\s+)";

	public static Map<String, String> getImgSmallImgFromHtml(String html) {
		Map<String, String> map = new HashMap<String, String>();
		StringBuilder image = new StringBuilder("");
		StringBuilder smallImage = new StringBuilder("");
		List<String> imgUrls = Util.getImageUrl(html);
		List<String> imgSrcs = Util.getImageSrc(imgUrls);
		String httpTestPrefix = "http://img.baobei762.com/image_test/upload/";
		String httpPrefix = "http://img.baobei762.com/images/upload/";// 如果是正式环境

		for (String src : imgSrcs) {
			src = src.replace(httpTestPrefix, "").replace(httpPrefix, "");
			// 外链不加入
			if (!src.startsWith("http")) {
				image.append(",").append(src);
				smallImage.append(",").append(src).append("@!headimg");
			}
		}
		if (image.toString().startsWith(",")) {
			image.deleteCharAt(0);
			smallImage.deleteCharAt(0);
		}
		map.put("image", image.toString());
		map.put("smallImage", smallImage.toString());
		return map;
	}

	/***
	 * 获取ImageUrl地址
	 * 
	 * @param HTML
	 * @return
	 */
	public static List<String> getImageUrl(String HTML) {
		Matcher matcher = Pattern.compile(IMGURL_REG).matcher(HTML);
		List<String> listImgUrl = new ArrayList<String>();
		while (matcher.find()) {
			listImgUrl.add(matcher.group());
		}
		return listImgUrl;
	}

	/***
	 * 获取ImageSrc地址
	 * 
	 * @param listImageUrl
	 * @return
	 */
	public static List<String> getImageSrc(List<String> listImageUrl) {
		List<String> listImgSrc = new ArrayList<String>();
		for (String image : listImageUrl) {
			Matcher matcher = Pattern.compile(IMGSRC_REG).matcher(image);
			while (matcher.find()) {
				listImgSrc.add(matcher.group().substring(0,
						matcher.group().length() - 1));
			}
		}
		return listImgSrc;
	}

	/**
	 * jsonObject 有key，且对应的value不为空
	 * 
	 * @param jsonObject
	 * @param key
	 * @return
	 */
	public static boolean containAndNotBlank(JSONObject jsonObject, String key) {
		boolean isNotBlank = false;

		if (jsonObject.containsKey(key)) {
			if (!StringUtils.isBlank(jsonObject.getString(key))) {
				isNotBlank = true;
			}
		}

		return isNotBlank;
	}

	/**
	 * 根据经纬度计算两点之间距离
	 * 
	 * @param lat1
	 *            - start纬度
	 * @param lng1
	 *            - start经度
	 * @param lat2
	 *            - end纬度
	 * @param lng2
	 *            - end经度
	 * @return km(四舍五入)
	 */
	public static double getDistance(double lat1, double lng1, double lat2,
			double lng2) {
		double r1 = (Math.PI / 180) * lat1;
		double r2 = (Math.PI / 180) * lat2;

		double lon1 = (Math.PI / 180) * lng1;
		double lon2 = (Math.PI / 180) * lng2;

		// 地球半径
		double R = 6378.1;

		double d = Math.acos(Math.sin(r1) * Math.sin(r2) + Math.cos(r1)
				* Math.cos(r2) * Math.cos(lon2 - lon1))
				* R;
		return new BigDecimal(d).setScale(4, BigDecimal.ROUND_HALF_UP)
				.doubleValue();
	}

	/**
	 * 检测邮箱地址是否合法
	 * 
	 * @param email
	 * @return true合法 false不合法
	 */
	public static boolean isEmail(String email) {
		if (null == email || "".equals(email))
			return false;
		// Pattern p = Pattern.compile("\\w+@(\\w+.)+[a-z]{2,3}"); //简单匹配
		Pattern p = Pattern
				.compile("\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*");// 复杂匹配
		Matcher m = p.matcher(email);
		return m.matches();
	}

	/**
	 * 判断是否存在交集
	 * @param arr1
	 * @param arr2
	 * @return
	 */
	public static boolean hasIntersect(Object[] arr1, Object[] arr2){
		boolean bool = false;
		if (isNotNull(arr1) && isNotNull(arr2)) {
			List<Object> list = new ArrayList<Object>();
			for (Object object : arr1) {
				list.add(object);
			}
			
			/*判断list中是否包含了arr2的元素*/
			for (Object o : arr2) {
				if (list.contains(o)) {
					bool = true;
					break;
				}
			}
		}
		return bool;
	}

    /**
     * 如果为空，返回空字符
     * */
    public static String getStringByObject(Object source){
        if (Util.isNull(source)){
            return "";
        } else {
            return source.toString();
        }
    }
    
    /**
     * 如果为空，返回 null
     * */
    public static String getNullOrStringByObject(Object source) {
        if (Util.isNull(source)) {
            return null;
        } else {
            return source.toString();
        }
    }

    /**
     * 如果为空，返回 0
     * */
    public static Integer getIntegerByObject(Object source){
        if (Util.isNull(source)){
            return 0;
        } else {
            try {
                double double2 = getDoubleByObject(source);
                // 四舍五入后保留整数
                int int2 = (int) Math.round(double2);
                return int2;
            } catch (Exception e) {
                return 0;
            }
        }
    }

    /**
     * 如果为空，返回 null
     * */
    public static Integer getNullOrIntegerByObject(Object source){
        if (Util.isNull(source)){
            return null;
        } else {
            try {
                double double2 = getDoubleByObject(source);
                // 四舍五入后保留整数
                int int2 = (int) Math.round(double2);
                return int2;
            } catch (Exception e) {
                return null;
            }
        }
    }
    
    /**
     * 保留两位小数（如果为空，返回 0.0）
     * */
    public static Double getDoubleByObject(Object source){
        if (Util.isNull(source)){
            return 0.0;
        } else {
            try {
                double db = Double.parseDouble(source.toString());
                BigDecimal b = new BigDecimal(db);
                return b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
            } catch (Exception e) {
                return 0.0;
            }
        }
    }
    
    /**
     * 保留两位小数（如果为空，返回 null）
     * */
    public static Double getNullOrDoubleByObject(Object source) {
        if (Util.isNull(source)){
            return null;
        } else {
            try {
                double db = Double.parseDouble(source.toString());
                BigDecimal b = new BigDecimal(db);
                return b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
            } catch (Exception e) {
                return null;
            }
        }
    }

	/**
	 * 保留 newScale 位小数
	 * @param data 原数据
	 * @param newScale 保留小数位
	 */
	public static float newScale(Float data, int newScale){
		if (data == null) {
			return 0;
		}
		return new BigDecimal("" + data).setScale(newScale, BigDecimal.ROUND_HALF_UP).floatValue();
	}
    
    /**
     * 返回当前登录人UID，未登录返回-1
     * @param request
     * @return
     */
    public static int getLoginUserId(HttpServletRequest request){
        Object u = request.getSession().getAttribute("manager");
        if( null != u){
            User user = (User) u;
            return user.getUid();
        }else{
            return -1;
        }
    }
    
    /**
     * str2在str1中是否存在
     * */
    public static boolean exist(String str1, String str2) {
        if (isNotNull(str1) && isNotNull(str2)) {
            if (str1.indexOf(str2) >= 0 || str1.equals(str2) || str1.equalsIgnoreCase(str2)) {
                return true;
            }
        }
        return false;
    }
    
    /**
     * 将数组转为字符串，由“,”拼接。数组为空时，返回null
     * */
    public static String arrToString(String[] arr) {
        if (isNotNull(arr)) {
            String result = "";
            for (String str : arr) {
                result += ("," + str);
            }
            // 去掉第一个“,”
            return result.substring(1, result.length());
        } else {
            return null;
        }
    }
    
    public static String getExcelDate(String date){
        Date time = null;
        String d = date;
        try {
            if(Util.isNotNull(date)){
            	if(date.contains("-")) {
            		time  = new SimpleDateFormat("yyyy-MM-dd").parse(date);
            	}else if(date.contains("/")) {
            		time  = new SimpleDateFormat("yyyy/MM/dd").parse(date);
            	}else if(date.contains("CST")){
            		time  = new SimpleDateFormat("E MMM dd HH:mm:ss z yyyy",Locale.US).parse(date);
            	}else if(date.contains("年") && date.contains("月") && date.contains("日")){
            	    time  = new SimpleDateFormat("yyyy年MM月dd日").parse(date);
            	}
            }
            if(Util.isNotNull(time)){
                d = new SimpleDateFormat("yyyy-MM-dd").format(time);
            }
        } catch (ParseException e) {
            System.err.println("时间转换异常"+e.getMessage());
        }
        return d;
    }
    
    
	/**
	 * 手机号有效性验证
	 * @param phone
	 * @return
	 */
	public static boolean mobileValidt(String phone){
		boolean bool = true;
		final String pattern1 = "^1\\d{10}$";
		final Pattern pattern = Pattern.compile(pattern1);
		final Matcher mat = pattern.matcher(phone);
		if (!mat.find()) {
			bool = false;
		}
		return bool;
	}
	
	/**
	 * 判断是否是数字
	 * @param str
	 * @param isInteger			是否是整数
	 * @return
	 */
	public static boolean isNumeric(String str, boolean isInteger){ 
		String regex = isInteger ? "\\d+":"(\\d+\\.\\d+)|\\d+";
		Pattern pattern = Pattern.compile(regex); 
		Matcher isNum = pattern.matcher(str);
		if( !isNum.matches() ){
			return false; 
		} 
		return true; 
	}
	
	/**
	 * 判断是否是数字，仅保留一位小数
	 * @param str
	 * @param isInteger			是否是整数
	 * @return
	 */
	public static boolean isNumericKeepOneDecimal(String str){ 
		String regex = "^(([1-9][0-9]*)+|0)(\\.[0-9]{0,1})?$";
		Pattern pattern = Pattern.compile(regex); 
		Matcher isNum = pattern.matcher(str);
		if(!isNum.matches()){
			return false; 
		} 
		// 判断最后一位是"."
	    int index = str.indexOf(".");
        if ((index > -1 ? index + 1 : -1) == str.length()){
            return false;
        }
		return true; 
	}
}
