package org.ts.ddcs.tool;


import org.ts.ddcs.log.LogHelper;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.*;

public class StringUtil {

	private StringUtil() {

	}

	/**
	 * @param str
	 *            xxx,xxx,xxx
	 * @return Collection - String
	 */
	public static Collection SimpleStringToCollection(String str) {

		Collection list = new ArrayList();
		StringTokenizer st = new StringTokenizer(str, ",");
		while (st.hasMoreTokens()) {
			list.add(st.nextToken());
		}
		return list;
	}

	public static Collection SimpleStringToCollection(String str,
			String delimChar) {

		Collection list = new ArrayList();
		StringTokenizer sToken = new StringTokenizer(str, delimChar);
		while (sToken.hasMoreTokens()) {
			list.add(sToken.nextToken());
		}
		return list;
	}

	/**
	 * @param str
	 *            "xx|xx,xx|xx" or "x,x" or ...
	 * @return Collection - Collection - String
	 */
	public static Collection StringToCollection(String str) {

		Collection result = new ArrayList();
		Collection colRecord = null;
		StringTokenizer stFirst = new StringTokenizer(str, ",");
		StringTokenizer stSecond = null;
		String record = null;
		String column = null;
		while (stFirst.hasMoreTokens()) {
			colRecord = new ArrayList();
			record = stFirst.nextToken();
			stSecond = new StringTokenizer(record, "|");
			while (stSecond.hasMoreTokens()) {
				column = stSecond.nextToken();
				colRecord.add(column);
			}
			result.add(colRecord);
		}

		Iterator it = result.iterator();
		while (it.hasNext()) {
			colRecord = (Collection) it.next();
			Iterator iter = colRecord.iterator();
			while (iter.hasNext())
				System.out.print(iter.next().toString() + " ");
			System.out.println();
		}
		return result;
	}

	/**
	 * @param str
	 *            xxx,xxx,xxx
	 * @return String[]
	 */
	public static String[] StringToArray(String str) {

		if (str == null || str.equals(""))
			return null;

		Collection list = new ArrayList();
		StringTokenizer st = new StringTokenizer(str, ",");
		while (st.hasMoreTokens()) {
			list.add(st.nextToken());
		}

		return (String[]) list.toArray(new String[list.size()]);
	}

	/**
	 * @param str
	 *            xxx,xxx,xxx
	 * @return String[]
	 */
	public static String[] StringToArray(String str, String token) {

		if (str == null || str.equals(""))
			return null;

		Collection list = new ArrayList();
		StringTokenizer st = new StringTokenizer(str, token);
		while (st.hasMoreTokens()) {
			list.add(st.nextToken());
		}

		return (String[]) list.toArray(new String[list.size()]);
	}

	public static String leftFill(String src, int len, char fillChar) {

		if (src == null || len < src.length())
			return src;

		String result = src;
		for (int i = src.length(); i < len; i++) {
			result = String.valueOf(fillChar) + result;
		}

		return result;
	}

	public static String rightFill(String src, String encoding, int len,
			char fillChar) throws UnsupportedEncodingException {

		int length = src.getBytes(encoding).length;
		if (src == null || len < length)
			return src;

		String result = src;
		for (int i = length; i < len; i++) {
			result += String.valueOf(fillChar);
		}

		return result;
	}

	public static String rightFill(String src, int len, char fillChar) {

		if (src == null || len < src.length())
			return src;

		String result = src;
		for (int i = src.getBytes().length; i < len; i++) {
			result += String.valueOf(fillChar);
		}

		return result;
	}

	public static String replace(String source, String oldString,
			String newString) {

		return replaceAll(source, oldString, newString);
	}

	public static String subString(String src, int index, int len,
			String charset) {

		if (src == null) {
			return src;
		}

		String result = "";
		try {
			int subTotal = 0;

			for (int i = 0; i < src.length(); i++) {
				String subStr = src.substring(index, index + 1);
				subTotal += subStr.getBytes(charset).length;
				result += subStr;

				if (subTotal >= len) {
					if (index < src.length()) {
						result += "...";
					}
					break;
				}

				index++;
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return result;
	}

	public static String replaceAll(String source, String from, String to) {

		if (source == null || source.equals(""))
			return source;
		String remain = source;
		String result = "";
		while (remain.indexOf(from) != -1) {

			result += remain.substring(0, remain.indexOf(from)) + to;
			remain = remain.substring(remain.indexOf(from) + from.length(),
					remain.length());
		}
		if (remain != null && !remain.equals(""))
			result += remain;
		return result;
	}

	public static int firstIndexOf(String src, char ch) {

		int result = -1;
		if (src == null) {
			return result;
		}

		return src.indexOf(ch);
	}

	public static int lastIndexOf(String src, char ch) {

		int result = -1;
		if (src == null) {
			return result;
		}

		for (int i = src.length() - 1; i >= 0; i--) {
			if (src.charAt(i) == ch) {
				return i;
			}
		}
		return result;
	}

	public static String arrayToString(String[] arr) {

		String result = "";
		if (arr == null) {
			return result;
		}

		for (int i = 0; i < arr.length; i++) {
			if (i == 0) {
				result = arr[i];
			} else {
				result += "," + arr[i];
			}
		}

		return result;
	}

	public static String[] getDistinctArray(String[] oldArray) {

		int cnt = 0;
		for (int i = 0; i < oldArray.length; i++) {
			if (oldArray[i] == null) {
				continue;
			}
			if (oldArray[i].equals("")) {
				oldArray[i] = null;
				continue;
			}
			cnt++;
			for (int j = i + 1; j < oldArray.length; j++) {
				if (oldArray[j] == null) {
					continue;
				}
				if (oldArray[j].equals("")) {
					oldArray[j] = null;
					continue;
				}
				if (oldArray[i].equals(oldArray[j])) {
					oldArray[j] = null;
				}
			}
		}

		String[] newArray = new String[cnt];
		if (cnt > 0) {
			int index = 0;
			for (int i = 0; i < oldArray.length; i++) {
				if (oldArray[i] != null) {
					newArray[index++] = oldArray[i];
					// System.out.println("i=" +
					// oldArray[i]);
				}
			}
		}
		return newArray;
	}

	public static String[] replaceArray(String[] oldArray, Map map) {

		String[] result = new String[oldArray.length];
		for (int i = 0; i < result.length; i++) {
			String key = oldArray[i];
			String value = (String) map.get(key);
			result[i] = value == null ? key : value;
		}

		return result;
	}

	public static boolean isBlank(String str) {

		if (str == null || str.trim().equals("")) {
			return true;
		}
		return false;
	}
	
	public static boolean isNotBlank(String str) {

		if (null != str  && !str.trim().equals("")) {
			return true;
		}
		return false;
	}

	public static String replace(String sourceStr, int start, int end,
			String str) {

		if (sourceStr == null || sourceStr.trim().equals("")) {
			return sourceStr;
		}

		if (sourceStr.length() < end)
			return sourceStr;

		String s = sourceStr.substring(0, start) + str
				+ sourceStr.substring(end);
		return s;
	}

	public static int getSubstringCount(String src, String substr) {

		if (src == null)
			return 0;

		int num = 0;
		int index = 0;
		while ((index = src.indexOf(substr, index)) != -1) {
			num++;
			index += substr.length();
		}
		return num;
	}

	/**
	 * remove rest of string content if the string includes 2 bytes(0x81 0x40)
	 * or 00
	 * 
	 * @param src
	 * @return pure string
	 * @throws UnsupportedEncodingException
	 */
	public static String trimRightZero(String src, String encoding)
			throws UnsupportedEncodingException {

		byte pattern[] = { (byte) 0x81, 0x40 };
		String match = new String(pattern, encoding);
		int i = src.indexOf((char) 0);
		int j = src.indexOf(match);
		// int k = src.indexOf("@");
		if (i > 0) {
			return src.substring(0, i);
		} else if (j > 0) {
			return src.substring(0, j);
		} else {
			return src;
		}
	}

	public static String getLastlenStr(String source, int len) {

		String str = "";
		if (source != null && source.length() > 0) {
			int strlen = source.length();
			if (strlen > len) {
				str = source.substring(strlen - len);
			} else
				str = source;
		}
		return str;
	}

	public static String trim(String src) {

		if (src == null)
			return null;

		char halfSpace = ' ';
		int headIndex = 0;
		int tailIndex = 0;
		int len = src.length();
		for (int i = 0; i < len; i++) {
			char tmp = src.charAt(i);
			if (tmp == halfSpace) {
				headIndex++;
			} else {
				break;
			}
		}

		for (int i = (len - 1); i >= 0; i--) {
			char tmp = src.charAt(i);
			if (tmp == halfSpace) {
				tailIndex++;
			} else {
				break;
			}
		}

		if (headIndex == len)
			return "";

		String result = src.substring(headIndex, len - tailIndex);

		return result;
	}

	public static String convertStringEnc(String strSource, String strEncoding)
			throws UnsupportedEncodingException {

		String strResult = new String(strSource.getBytes("ISO-8859-1"),
				strEncoding);
		return strResult;
	}

	public static String map2String(Map map) {

		if (map == null) {
			return "";
		}

		if (map.isEmpty()) {
			return "";
		}
		String dataStr = "";
		Object[] expKeys = map.keySet().toArray();
		for (int i = 0; i < expKeys.length; i++) {
			String code = expKeys[i].toString();
			String value = (String) map.get(code);
			dataStr += "".equals(dataStr) ? code + ":" + value : ", " + code
					+ ":" + value;
		}
		return dataStr;
	}



	private static String getMD5Digest(String src)
			throws NoSuchAlgorithmException {

		char[] ha = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a',
				'b', 'c', 'd', 'e', 'f' };
		try {

			MessageDigest md = MessageDigest.getInstance("MD5");

			md.update(src.getBytes("UTF-8"));

			byte[] ba = md.digest();

			int j = ba.length;
			char[] ca = new char[j * 2];
			int k = 0;

			for (int i = 0; i < j; i++) {
				byte b = ba[i];
				ca[k++] = ha[b >>> 4 & 0xf];
				ca[k++] = ha[b & 0xf];
			}

			return new String(ca);
		} catch (Exception e) {
			LogHelper.error(e.toString());
			return null;
		}

	}

	
	public static String getNotNullStr(String str){
		return str!= null ? str.trim():"";
	}
	
	//去掉多余的0, 000908.8900  变为908.89
	public static String getPrettyNumber(String number) {
		if(number.contains("F")){
			return null;
		}
	    return BigDecimal.valueOf(Double.parseDouble(number))  
	            .stripTrailingZeros().toPlainString();  
	}
	
	/**
	 * 判断当前日期是星期几<br>
	 * <br>
	 * 
	 * @param pTime
	 *            修要判断的时间<br>
	 * @return dayForWeek 判断结果<br>
	 * @Exception 发生异常<br>
	 */
	public static int dayForWeek(String pTime) throws Exception {
		SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
		Calendar c = Calendar.getInstance();
		c.setTime(format.parse(pTime));
		int dayForWeek = 0;
		if (c.get(Calendar.DAY_OF_WEEK) == 1) {
			dayForWeek = 7;
		} else {
			dayForWeek = c.get(Calendar.DAY_OF_WEEK) - 1;
		}
		return dayForWeek;
	}
	
	
	 /**
     * 
     * 提供精确的小数位四舍五入处理。
     * @param v 需要四舍五入的数字
     * @param scale  小数点后保留几位
     * @return 四舍五入后的结果
    * 
     */
	 public static String roundForNumber(String v,int scale){
         if(scale<0){
             throw new IllegalArgumentException("The scale must be a positive integer or zero");
         }
         BigDecimal b = new BigDecimal(v);
         BigDecimal one = new BigDecimal("1");
         double retV =  b.divide(one,scale,BigDecimal.ROUND_HALF_UP).doubleValue();
         return retV+"";
     }
	 
	 public static String convertSecondToHourQ(String qStr){
			if(null==qStr || "".equals(qStr)){
				return null;
			}
			Double qSecond = Double.parseDouble(qStr);
			Double qHour = qSecond*3600;
			return qHour.toString();
		}
	
}
