package cn.base.util;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang.StringUtils;

public class StringUtil extends StringUtils {

	// 32位UUID
	public static String getUUID() {
		String id = UUID.randomUUID().toString().replaceAll("-", "");
		return id;
	}

	public static Date getDateZeroTime() {
		Calendar c = Calendar.getInstance();// 可以对每个时间域单独修改
		int year = c.get(Calendar.YEAR);
		int month = c.get(Calendar.MONTH)+1;
		int date = c.get(Calendar.DAY_OF_MONTH);
		String strDate = year + "-" + month + "-" + date + " 00:00:00";
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date newDate = null;
		try {
			newDate = sdf.parse(strDate);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return newDate;
	}
	
	public static void main(String[] args) {
		Date date = getDateZeroTime();
		System.out.println(date);
	}

	// 车辆号牌匹配处理
	public static String getPlateNo(String plateNo) {
		if (plateNo != null && !plateNo.equals("")) {
			if (plateNo.indexOf("*") != -1 || plateNo.indexOf("?") != -1) {
				plateNo = plateNo.replace('?', '_').replace('*', '%').toUpperCase();
				plateNo = " plateNo like '" + plateNo + "'";
			} else {
				plateNo = " plateNo = '" + plateNo.toUpperCase() + "'";
			}
			return plateNo;
		}
		return "";
	}

	// 车辆排除牌号处理
	public static String getNoBrandId(String noBrandId) {
		if (noBrandId != null && !noBrandId.equals("")) {
			if (noBrandId.indexOf("*") != -1 || noBrandId.indexOf("?") != -1) {
				noBrandId = noBrandId.replace('?', '_').replace('*', '%').toUpperCase();
				noBrandId = " plateNo not like '" + noBrandId + "'";
			} else {
				noBrandId = " plateNo <> '" + noBrandId.toUpperCase() + "'";
			}
			return noBrandId;
		}
		return "";
	}

	/**
	 * 判断字符串str是否为null或""
	 * 
	 * @param str
	 * @return boolean
	 */
	public static boolean isEmpty(String str) {
		return str == null || str.length() == 0;
	}

	public static boolean isNotEmpty(String str) {
		return !isEmpty(str);
	}

	/**
	 * 判断字符串str是否为null、""和" "
	 * 
	 * @param str
	 * @return boolean
	 */
	public static boolean isBlank(String str) {
		int strLen;
		if (str == null || (strLen = str.length()) == 0) {
			return true;
		}
		for (int i = 0; i < strLen; i++) {
			if ((Character.isWhitespace(str.charAt(i)) == false)) {
				return false;
			}
		}
		return true;
	}

	public static String doNullOfStr(Object oTag) {
		if (oTag == null || ("null").equals(oTag))
			return "";
		else
			return oTag.toString();
	}

	/**
	 * 字符串排序
	 * 
	 * @param str
	 * @return String
	 */
	public static String sortString(String str) {
		List<Character> slist = new ArrayList<Character>();
		for (int i = 0; i < str.length(); i++) {
			slist.add(str.charAt(i));
		}
		Collections.sort(slist);
		String strs = "";
		for (int j = 0; j < slist.size(); j++) {
			strs += slist.get(j).toString().trim();
		}
		return strs;
	}

	/**
	 * 处理html中的img标签,%%number,%%,input标签,10-01-04
	 * 
	 * @author sunxiaosong
	 * @return String
	 */
	public static String dealWithImg(String htmlStr) {
		if (!StringUtils.isEmpty(htmlStr)) {
			// 去掉<img/>,%%number,%%,<input/>标签
			htmlStr = htmlStr.replaceAll("<img.*/>", "这里是张图片").replaceAll("%%[0-9]{1,}", "").replaceAll("%%", "").replaceAll("<input.*?/>", "");
		}
		return htmlStr;
	}

	public static boolean isNotBlank(String str) {
		return !isBlank(str);
	}

	public static final String trim(String str) {
		return ((str == null) ? str : str.trim());
	}

	public static String clean(String str) {
		return str == null ? "" : str.trim();
	}

	public static final String emptyToDefault(String value, String defaultValue) {
		return (((value != null) && (value.length() > 0)) ? value : defaultValue);
	}

	public static final String nullToEmpty(String value) {
		return ((value == null) ? "" : value);
	}

	/**
	 * 字符串转换编码
	 * 
	 * @param value
	 * @param from
	 * @param to
	 * @return String
	 */
	public static final String changeEncode(String value, String from, String to) {
		if (isEmpty(value))
			return "";
		try {
			String str = new String(value.getBytes(from), to);
			return str;
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			return "";
		}
	}

	/**
	 * 字符串编码由ISO8859-1转化成UTF-8
	 * 
	 * @param value
	 * @return String
	 */
	public static final String toUtf8(String value) {
		return changeEncode(value, "ISO8859-1", "utf-8");
	}

	/**
	 * 转码
	 * 
	 * @param value
	 * @param encode
	 * @return String
	 */
	public static final String encode(String value, String encode) {
		if (isEmpty(value))
			return "";
		try {
			String str = URLEncoder.encode(value, encode);
			return str;
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			return "";
		}
	}

	/**
	 * 解码
	 * 
	 * @param value
	 * @param encode
	 * @return String
	 */
	public static final String decode(String value, String encode) {
		if (isEmpty(value))
			return "";
		try {
			String str = URLDecoder.decode(value, encode);
			return str;
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			return "";
		}
	}

	/**
	 * 转码成UTF-8
	 * 
	 * @param value
	 * @return String
	 */
	public static final String encode(String value) {
		return encode(value, "UTF-8");
	}

	/**
	 * 以UTF-8进行解码
	 * 
	 * @param value
	 * @return String
	 */
	public static final String decode(String value) {
		return decode(value, "UTF-8");
	}
	// 判断是否有中文
	public static boolean hasFullSize(String inStr) {
		if (inStr.getBytes().length != inStr.length()) {
			return true;
		}
		return false;
	}
	public static String getChineseEncoding(String url) {
		String encodeStr = "";
		if (url != null) {
			try {
				for (int i = 0; i < url.length(); i++) {
					if (hasFullSize(url.substring(i, i + 1)))
						encodeStr += URLEncoder.encode(url.substring(i, i + 1), "utf-8");
					else
						encodeStr += url.substring(i, i + 1);
				}
			} catch (Exception e) {
			}
		}
		return encodeStr;
	}
	// 把字符串转成utf8编码，保证中文文件名不会乱码
	public static String toUtf8String(String s) {
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < s.length(); i++) {
			char c = s.charAt(i);
			if (c >= 0 && c <= 255) {
				sb.append(c);
			} else {
				byte[] b;
				try {
					b = Character.toString(c).getBytes("utf-8");
				} catch (Exception ex) {
					b = new byte[0];
				}
				for (int j = 0; j < b.length; j++) {
					int k = b[j];
					if (k < 0)
						k += 256;
					sb.append("%" + Integer.toHexString(k).toUpperCase());
				}
			}
		}
		return sb.toString();
	}
	
	public static boolean checkEmpty(Object pObj) {
		if (pObj == null)
			return true;
		if (pObj.equals(""))
			return true;
		if (pObj instanceof String) {
			if (((String) pObj).length() == 0) {
				return true;
			}
		} else if (pObj instanceof Collection) {
			if (((Collection) pObj).size() == 0) {
				return true;
			}
		} else if (pObj instanceof Map) {
			if (((Map) pObj).size() == 0) {
				return true;
			}
		}
		return false;
	}
	
	/**
	 * 判断对象是否Empty(null或元素为0)<br>
	 * 实用于对如下对象做判断:String Collection及其子类 Map及其子类
	 * @param pObj 待检查对象
	 * @return boolean 返回的布尔值
	 */
	public static boolean isEmpty(Object pObj) {
		if (pObj == null)
			return true;
		if (pObj == "")
			return true;
		if (pObj instanceof String) {
			if (((String) pObj).length() == 0) {
				return true;
			}
		} else if (pObj instanceof Collection) {
			if (((Collection) pObj).size() == 0) {
				return true;
			}
		} else if (pObj instanceof Map) {
			if (((Map) pObj).size() == 0) {
				return true;
			}
		}
		return false;
	}
	/**
     * 利用正则表达式判断字符串是否是数字,""不为数字
     * @param str
     * @return
     */
    public static boolean isNumeric(String str){
    	if(StringUtils.isEmpty(str)){
    		return false;
    	}
	    Pattern pattern = Pattern.compile("[0-9]*");
	    Matcher isNum = pattern.matcher(str);
	    if( !isNum.matches() ){
	       return false;
	    }
	    return true;
    }
    /**
     * 将数字字符串转换为整型
     * @param str
     * @return
     */
    public static Integer str2Numeric(String str){
    	if(StringUtils.isEmpty(str)||"null".equals(str)){
    		return 0;
    	}
    	if(str.lastIndexOf(".")!=-1){
    		str = str.substring(0, str.lastIndexOf("."));
    	}
    	Pattern pattern = Pattern.compile("[0-9]*");
    	Matcher isNum = pattern.matcher(str);
    	if( !isNum.matches() ){
    		return 0;
    	}
    	return Integer.valueOf(str);
    }
    public static Double str2Double(String str){
    	if(StringUtils.isEmpty(str)||"null".equals(str)){
    		return 0.0;
    	}
    	Pattern pattern = Pattern.compile("[0-9]*.*");
    	Matcher isNum = pattern.matcher(str);
    	if( !isNum.matches() ){
    		return 0.0;
    	}
    	return Double.valueOf(str);
    }
    /**
     * 字符串转换
     */
    public static String transEmpty(String str){
		if("null".equals(str)|| StringUtils.isEmpty(str)){
			return "";
		}
		return str;
	}
}
