package com.nbclass.util;

import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.security.SecureRandom;
import java.sql.PreparedStatement;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.nbclass.szxgl.model.ProjectTaskTerm;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.codec.digest.UnixCrypt;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.formula.functions.T;

/**
 * 工具类
 * @author leiyun
 * @datetime 2016年3月18日 上午10:30:43
 */
public class Utility implements java.io.Serializable {

	private static final long serialVersionUID = 1L;

	protected static Utility instance = null;

	public static synchronized void setInstance(boolean clear) {
		if (clear)
			instance = null;
		else if (instance == null)
			instance = new Utility();
	}

	public static Utility getUtilityInstance() {
		if (instance == null)
			setInstance(false);
		return instance;
	}

	protected Utility() {
		instance = null;
	}


	/**
	 * Convert integer string array into integer array
	 * @param array
	 * @return
	 * @throws Exception
	 */
	public static int[] toIntArray(String[] array) {
		int[] result = new int[array.length];
		int count = 0;
		for (int i = 0; i < array.length; i++) {
			if (array[i] != null && !array[i].trim().equals("") && !array[i].trim().equals("undefined"))
				result[count++] = Integer.parseInt(array[i]);
		}
		return result;
	}

	/**
	 * Convert integer arraylist into integer array
	 * @param array
	 * @return
	 * @throws Exception
	 */
	public static int[] toIntArray(ArrayList<String> array) throws Exception {
		int[] result = new int[array.size()];
		int count = 0;
		for (int i = 0; i < array.size(); i++) {
			String item = array.get(i);
			if (item != null && !item.trim().equals(""))
				result[count++] = Integer.parseInt(item);
		}
		return result;
	}

	public static int[] toIntArray(String str){
		if(str == null || str.equals("")) return null;
		int[] result;
		if(str.indexOf(",")!=-1){
			String[] strArr = str.split(",");
			result =toIntArray(strArr);
		}else{
			result = new int[]{Integer.parseInt(str)};
		}

		return result;
	}

	public static String strArrayToString(String[] ids){
		if(ids == null || ids.length < 1) return null;
		String result = "";
		for(int i=0; i< ids.length; i++){
			result += (isEmpty(result) ? "" : ",") + ids[i];
		}
		return result;
	}

	public static String encodeHTML(String value) {
		if (value == null)
			return "";
		value = value.replaceAll("\"", "&#34;").replaceAll("'", "&#39;");
		value = value.replaceAll("<", "&lt;").replaceAll(">", "&gt;");
		return value;
	}

	public static String decodeHTML(String value) {
		if (value == null)
			return "";
		value = value.replaceAll("&#34;", "\"").replaceAll("&#39;", "'");
		value = value.replaceAll("&lt;", "<").replaceAll("&gt;", ">");
		return value;
	}

	/**
	 * This function will convert the string to a unicode string. (e.g. "\u7f51")
	 *
	 * @param value
	 * @return
	 */
	public static String toUnicodeString(String value) throws Exception {
		// Set the contant type as "UTF8".
		// <META http-equiv=content-tyhpe content="text/html; charset=UTF-8">
		if (value == null || value.equals(""))
			return value;

		String buffer = value;
		buffer = new String(buffer.getBytes("ISO8859_1"), "UTF8");
		buffer = URLEncoder.encode(buffer, "Unicode");

		StringBuffer sb = new StringBuffer();
		String[] sc = buffer.split("%FF%FE");
		// for each of unicode set
		for (int i = 0; i < sc.length; i++) {
			String si = sc[i];
			// for each of char in unicode line
			for (int j = 0; j < si.length(); j++) {
				char ch = si.charAt(j);
				if (ch == '%') {
					sb.append('\\').append('u');
					sb.append(si.substring(j + 4, j + 6).toLowerCase());
					sb.append(si.substring(j + 1, j + 3).toLowerCase());
					j += 5;
				} else {
					String ss = si.substring(j, j + 1);
					if (ss.equals("+"))
						ss = " ";
					sb.append(ss);
				}
			}
		}
		return sb.toString();
	}

	/**
	 * Create a instance from a class
	 *
	 * @param service
	 * @return @throws
	 *         ClassNotFoundException
	 * @throws InstantiationException
	 * @throws IllegalAccessException
	 */
	public static Object instantiate(String service) throws ClassNotFoundException, InstantiationException,
			IllegalAccessException {
		ClassLoader classloader = Thread.currentThread().getContextClassLoader();
		Class<?> instance = classloader.loadClass(service);
		return instance.newInstance();
	}

	public static double getRoundUp(double d, int scale) {
		double result = d;
		BigDecimal bd = new BigDecimal(d);
		result = bd.setScale(scale, BigDecimal.ROUND_HALF_UP).doubleValue();
		return result;
	}

	public static float getRoundUp(float d, int scale) {
		float result = d;
		BigDecimal bd = new BigDecimal(d);
		result = bd.setScale(scale, BigDecimal.ROUND_HALF_UP).floatValue();
		return result;
	}

	public static Calendar getCalendar(Date date) throws Exception {
		Calendar result = Calendar.getInstance();
		result.setTime(date);
		return result;
	}

	public static Calendar getCalendar(long milliseconds) throws Exception {
		Calendar result = Calendar.getInstance();
		result.setTimeInMillis(milliseconds);
		return result;
	}

	public static String getTimeStampWithMillis() {
		return getTimeStampWithMillis(Calendar.getInstance());
	}

	public static String getTimeStampWithMillis(Calendar calendar) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
		String result = sdf.format(calendar.getTime());
		return result;
	}

	/**
	 * Convert a string with format "yyyyMMddHHmmss" into Calendar object
	 * @param date
	 * @return
	 * @throws Exception
	 */
	public static Calendar getCalendar(String date) throws Exception {
		if (date == null || date.trim().equals(""))
			return null;

		for (int i = date.length(); i < 14; i++)
			date += "0";
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
		Calendar result = Calendar.getInstance();

		try {
			result.setTime(sdf.parse(date));
		} catch (ParseException e) {
			result = null;
		}
		return result;
	}

	public static Calendar getCalendar(String date, String format) throws Exception {
		if (date == null || date.trim().equals(""))
			return null;

		SimpleDateFormat sdf = new SimpleDateFormat(format);
		Calendar result = Calendar.getInstance();

		try {
			result.setTime(sdf.parse(date));
		} catch (ParseException e) {
			result = null;
		}
		return result;
	}

	public static String getDateString(Calendar date){
		return getDateString(date, "yyyyMMddHHmmss");
	}

	public static String getDateString(Calendar date, String format){
		if (date == null)	return "";
		SimpleDateFormat sdf = new SimpleDateFormat(format);
		return sdf.format(date.getTime());
	}

	public static String getHttpContent(String urlStr, String encoding) throws Exception {
		URL url = new URL(urlStr);
		InputStream is = null;
		HttpURLConnection connection = (HttpURLConnection) url.openConnection();
		try {
			if (connection.getResponseCode() != 200) {
				//return "Error: " + connection.getResponseCode() + " " + connection.getResponseMessage();
				is = connection.getErrorStream();
			} else {
				is = connection.getInputStream();
			}

			ByteArrayOutputStream bos = new ByteArrayOutputStream();
			byte[] buffer = new byte[16384];
			int count;
			while ((count = is.read(buffer)) != -1) {
				bos.write(buffer, 0, count);
			}
			return bos.toString(encoding);
		} finally {
			connection.disconnect();
		}
	}

	public static byte[] objectToByteArray(Object obj) throws Exception {
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		ObjectOutputStream oos = new ObjectOutputStream(bos);
		oos.writeObject(obj);
		oos.flush();
		oos.close();
		return bos.toByteArray();
	}

	public static byte[] InputStreamToByteArray(InputStream is) throws Exception {
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		byte[] buffer = new byte[16384];
		int count;
		while ((count = is.read(buffer)) != -1) {
			bos.write(buffer, 0, count);
		}
		return bos.toByteArray();
	}


	public static Object byteArrayToObject(byte[] array) throws Exception {
		ByteArrayInputStream bis = new ByteArrayInputStream(array);
		ObjectInputStream ois = new ObjectInputStream(bis);
		return ois.readObject();
	}

	public static void byteArrayToFile(byte[] content, String filename) throws Exception {
		FileOutputStream out = new FileOutputStream(filename);
		out.write(content);
		out.flush();
		out.close();
	}

	public static byte[] fileToByteArray(String filename) throws Exception {
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		FileInputStream fos = new FileInputStream(filename);
		byte[] buffer = new byte[10240];
		int count;
		while ((count = fos.read(buffer)) != -1)
			bos.write(buffer, 0, count);
		fos.close();
		return bos.toByteArray();
	}

	public static int[] getIntegerArray(String values) throws Exception {
		String[] slice = values.split(",");
		int[] result = new int[slice.length];
		for (int i = 0; i < slice.length; i++)
			result[i] = Integer.parseInt(slice[i]);
		return result;
	}

	public static String getFormatedDate(Calendar date) {
		return getFormatedDate(date, "yyyy-MM-dd HH:mm:ss");
	}

	public static String getFormatedDate(Calendar date, String format) {
		if (date == null)
			return "";
		SimpleDateFormat sdf = new SimpleDateFormat(format);
		return sdf.format(date.getTime());
	}

	public static String getFormatedTimeStamp() {
		return getFormatedTimeStamp(Calendar.getInstance());
	}

	public static String getFormatedTimeStamp(Calendar calendar) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss SSS");
		return sdf.format(calendar.getTime());
	}

	public static String getTimeStamp() {
		Calendar calendar = Calendar.getInstance();
		return getTimeStamp(calendar);
	}

	public static String getTimeStamp(Calendar calendar) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
		String result = sdf.format(calendar.getTime());
		result = result + "000";
		return result;
	}


	public static String getFormatedFileSize(long value) {
		double kb = value / 1024.00;
		DecimalFormat df = new DecimalFormat("#0.00");
		return df.format(kb);
	}

	public static String getFormatedDecimal(double value) {
		return getFormatedDecimal(value, "#0.00");
	}

	public static String getFormatedDecimal(double value, int decimal) {
		String format = "#0.";
		if (decimal == 0) format = "#0";
		else {
			for (int i = 1; i <= decimal; i++) format += "0";
		}
		return getFormatedDecimal(value, format);
	}

	public static String getFormatedDecimal(double value, String format) {
		DecimalFormat df = new DecimalFormat(format);
		return df.format(value);
	}

	public static Date getMonthLastDay(int year, int month) {
		Calendar calendar = Calendar.getInstance();
		calendar.set(year, month, 1);
		calendar.add(Calendar.DATE, -1);
		return calendar.getTime();
	}

	public static String getDateFormat(Date date, String format) {
		if (date == null) return "";
		SimpleDateFormat dateFormat = new SimpleDateFormat(format, Locale.US);
		return dateFormat.format(date);
	}

	public static java.sql.Date UtilDateToSQLDate(Date utilDate) {
		if (utilDate == null) return null;
		return new java.sql.Date(utilDate.getTime());
	}

	public static java.sql.Timestamp UtilDateToSQLTimeStamp(Date utilDate) {
		if (utilDate == null) return null;
		return new java.sql.Timestamp(utilDate.getTime());
	}

	public static java.util.Date SQLDateToUtilDate(java.sql.Date SQLDate) {
		if (SQLDate == null) return null;
		return new Date(SQLDate.getTime());
	}

	public static java.util.Date SQLDateToUtilDate(java.sql.Timestamp SQLDate) {
		if (SQLDate == null) return null;
		return new Date(SQLDate.getTime());
	}

	public static Date parseDate(String strDate, String pattern) throws Exception {
		if (strDate == null || strDate.trim().equals("")) return null;
		SimpleDateFormat format = new SimpleDateFormat(pattern);
		Date date = format.parse(strDate);
		return date;
	}

	public static String getSearchFormat(String pattern) {
		if (pattern == null) return "%";
		pattern = pattern.trim();	// format maybe : A, A%, %A%, A%B%, %A"B
		if (pattern.equals("")) {
			pattern = "%";
		} else if (pattern.indexOf("%") == -1) {
			pattern = "%" + pattern + "%";
		}
		return pattern;
	}

	public static String getLeadingZero(int intValue, int maxLength) {
		String result = String.valueOf(intValue);
		if (result.length() < maxLength) {
			while (result.length() < maxLength) {
				result = "0" + result;
			}
		}
		return result;
	}

	public static String getQuantityAsString(float qty) {
		DecimalFormat df = new DecimalFormat("#0.00");
		return df.format(qty);
	}

	public static String getQuantityAsString(double qty) {
		DecimalFormat df = new DecimalFormat("#0.00");
		return df.format(qty);
	}

	public static String getQuantityAsString(float amt, String pattern) {
		DecimalFormat df = new DecimalFormat(pattern);
		return df.format(amt);
	}

	public static String getQuantityAsString(double amt, String pattern) {
		DecimalFormat df = new DecimalFormat(pattern);
		return df.format(amt);
	}

	public static String getInvoiceAsString(float amt) {
		DecimalFormat df = new DecimalFormat("#,##0.00");
		return df.format(amt);
	}

	public static String getAmountAsString(float amt, String pattern) {
		DecimalFormat df = new DecimalFormat(pattern);
		return df.format(amt);
	}

	public static String getAmountAsString(double amt, String pattern) {
		DecimalFormat df = new DecimalFormat(pattern);
		return df.format(amt);
	}

	public static String getFloatFormat(float f, String pattern) {
		DecimalFormat df = new DecimalFormat(pattern);
		return df.format(f);
	}

	public static String getDoubleFormat(double d, String pattern) {
		DecimalFormat df = new DecimalFormat(pattern);
		return df.format(d);
	}

	public static Date parseExcelDate(String Date) {
		Calendar calendar = Calendar.getInstance();
		long millis = (long) (Integer.parseInt(Date) - 25569)*24*60*60*1000;
		calendar.setTimeInMillis(millis);
		return calendar.getTime();
	}

    public static double mul(double d1, double d2) {
    	BigDecimal b1 = new BigDecimal(String.valueOf(d1));
    	BigDecimal b2 = new BigDecimal(String.valueOf(d2));

    	return b1.multiply(b2).doubleValue();
    }

    public static double mul(BigDecimal b1, double d2) {
    	BigDecimal b2 = new BigDecimal(String.valueOf(d2));

    	return b1.multiply(b2).doubleValue();
    }

    public static double add(double d1, double d2) {
    	BigDecimal b1 = new BigDecimal(String.valueOf(d1));
    	BigDecimal b2 = new BigDecimal(String.valueOf(d2));

    	return b1.add(b2).doubleValue();
    }

	public static boolean isPositiveInteger(String inValue) {
		return isNumericValue(inValue, false, false);
	}

	public static boolean isNumericValue(String inValue) {
		return isNumericValue(inValue, true, true);
	}

	public static boolean isNumericValue(String inValue, boolean includeSymbol, boolean includeDecimal) {
		boolean result = false;
		if (inValue != null) {
			inValue = inValue.trim();
			if (!inValue.equals("")) {
				if (inValue.indexOf("=") != -1) {
					inValue = inValue.substring(inValue.indexOf("=") + 1);
				}
				inValue = inValue.trim();
				String nString = "1234567890";
				if (includeSymbol) nString += "-";
				if (includeDecimal) nString += ".";
				result = true;
				for (int i=0; i < inValue.length(); i++) {
					if (nString.indexOf(inValue.substring(i, i+1)) == -1) {
						result = false;
						break;
					}
				}
			}
		}
		return result;
	}

	public static String getIDAsString(ArrayList<?> idList, int idFrom, int idTo) {
		String IDs = null;
		if (idList != null && idList.size() > 0) {
			if (idFrom < 0) idFrom = 0;
			if (idTo > idList.size()) idTo = idList.size();
			int lp;
			IDs = idList.get(idFrom).toString();
			if (idList.size() > 1 && idTo > idFrom) {
				for (lp = idFrom+1; lp < idTo; lp ++) IDs += "," + idList.get(lp).toString();
			}
		}
		return IDs;
	}

	public static String getPreparedParameterList(int fromID, int toID) {
		String result = "";
		for (int i = fromID; i <= toID; i++) {
			if (i == fromID) result += "?";
			else result += ",?";
		}
		return result;
	}

	public static void setPreparedParameterList(PreparedStatement stmt, int startParamIndex, ArrayList<Integer> idList, int fromID, int toID) throws Exception {
		int idx = startParamIndex;
		for (int i = fromID; i <= toID; i++) {
			stmt.setInt(idx, idList.get(i).intValue());
			idx ++;
		}
	}

	public static String replaceMailAddress(String mailAddress, String oldPattern, String newPattern) {
		if (mailAddress == null || mailAddress.trim().equals("") || oldPattern == null || newPattern == null)
			return mailAddress;
		else {
			return mailAddress.trim().replaceAll(oldPattern, newPattern);
		}
	}

	public static String getValidMailAddress(String mailAddress, String defaultAddress) {
		if (mailAddress != null && !mailAddress.trim().equals(""))
			return mailAddress;
		else
			return defaultAddress;
	}

	public static String getValidString(String str) {
		if (str == null) return "";
		else return str;
	}

	public static String[] getMailTo(String to) {
		String[] toAC = null;
		if (to != null && to.indexOf("@") != -1) {
			if (to.indexOf(",") != -1) toAC = to.split(",");
			else if (to.indexOf(";") != -1) toAC = to.split(";");
			else if (to.indexOf(" ") != -1) toAC = to.split(" ");
			else {
				toAC = new String[1];
				toAC[0] = to;
			}
		}
		return toAC;
	}

	public static int getASCII(String str) {
		int result = 48;
		if (str != null && !str.trim().equals("")) {
			result = 48 + Integer.parseInt(str);
		}
		return result;
	}

	public static void getKeyAsVector(String s_key, Vector<String> v_key) {
		int idx;
		if (s_key != null && !s_key.trim().equals("")) {
			if (s_key.startsWith(".")) s_key = s_key.substring(1);
			while (s_key.length() > 0) {
				idx = s_key.indexOf(".");
				if (idx != -1) {
					v_key.addElement(s_key.substring(0, idx));
					s_key = s_key.substring(idx+1);
				} else {
					v_key.addElement(s_key);
					s_key = "";
				}
			}
		}
	}

	public static String getNameFromAscII(String s_key, int startIndex, int length) {
		Vector<String> v_key = new Vector<String>();
		Utility.getKeyAsVector(s_key, v_key);
		String result = getNameFromAscII(v_key, startIndex, length);
		v_key = null;
		return result;
	}

	public static String getNameFromAscII(Vector<String> v_key, int startIndex, int length) {
		String result = "";
		if (length > v_key.size() - startIndex) length = v_key.size() - startIndex;
		for (int i = startIndex; i < startIndex + length; i++) {
			result += (char)Integer.parseInt(v_key.elementAt(i));
		}
		return result;
	}

	public static String NameToASCII(String str) {
		String result = null;
		char[] ch = str.toCharArray();
		for (int i = 0; i < ch.length; i++) {
			if (result == null) result = String.valueOf((int)ch[i]);
			else result = result + "." + String.valueOf((int)ch[i]);
		}
		return result;
	}

    public static void writeLog(String log) {
		try {
			System.out.println(getFormatedTimeStamp() + " : " + log);
		} catch (Exception e) {
		}
	}

	public static String intToHex(int i) {
		String result = Integer.toHexString(i).trim();
		if (result.length() == 0) result = "00";
		if (result.length() == 1) result = "0" + result;
		return result;
	}

	public static int HexToInt(String s) {
		return Integer.parseInt(Integer.valueOf(s, 16).toString());
	}

	public static ArrayList<String> str2List(String str){
		ArrayList<String> list = new ArrayList<>();
		if(str!=null && str.trim().length()>0){
			if(str.indexOf(",")!=-1){
				String[] arr = str.split(",");
				for (String string : arr) {
					list.add(string);
				}
			}else{
				list.add(str);
			}
		}
		return list;
	}


    public static String getDateFormat(Calendar calendar){
    	String returnValue="";
    	Date now = new Date();
		long leftTime=now.getTime()-calendar.getTimeInMillis();
		long day=leftTime/(24*60*60*1000);
		long hour=(leftTime/(60*60*1000)-day*24);
		long min=((leftTime/(60*1000))-day*24*60-hour*60);
		long s=(leftTime/1000-day*24*60*60-hour*60*60-min*60);

		if(returnValue.equals("") && day>=365){
			int year = (int) (day/365);
			returnValue=year+"年前";
		}
		if(returnValue.equals("") && day>=30){
			int month = (int) (day/30);
			returnValue=month+"个月前";
		}
		if(returnValue.equals("") && day > 0)
			returnValue=day+"天前";
		if(returnValue.equals("") && hour > 0 )
			returnValue=hour+"小时前";
		if(returnValue.equals("") && min > 0 )
			returnValue=min+"分前";
		if(returnValue.equals("") && s > 0)
			returnValue=s+"秒前";
		if(returnValue.equals(""))
			returnValue="0秒前";

		return returnValue;
    }

    public static String getUUID(){
    	return java.util.UUID.randomUUID().toString();
    }

    /**
     * 格式化日期  eg. 2014年07月10日  12:29 星期四
     * @param date
     * @return
     */
    public static String getDateCN(Date date){
    	SimpleDateFormat dateFm = new SimpleDateFormat("yyyy年MM月dd日  HH:mm  EEEE");
    	return dateFm.format(date);

    }

    /**
     * 获取文件的后缀名
     * @param filename
     * @return
     */
    public static String getFileSuffix(String filename){
    	String suffix="";
    	if(filename!=null && filename.indexOf(".")!=-1)suffix=filename.substring(filename.lastIndexOf("."));
    	return suffix;
	}

    public static String getFileSuffix(File file){
    	String fileName=file.getName();
    	return getFileSuffix(fileName);
    }

    /**
     * 获取访问者IP
     * 在一般情况下使用Request.getRemoteAddr()即可，但是经过nginx等反向代理软件后，这个方法会失效。
     * 本方法先从Header中获取X-Real-IP，如果不存在再从X-Forwarded-For获得第一个IP(用,分割)，
     * 如果还不存在则调用Request.getRemoteAddr()。
     * @param request
     * @return
     */
    public static String getClientIPAddr(HttpServletRequest request) {
    	String ip = request.getHeader("x-forwarded-for");
    	if (!StringUtils.isBlank(ip) && !"unknown".equalsIgnoreCase(ip)) {
            // 多次反向代理后会有多个IP值，第一个为真实IP。
            int index = ip.indexOf(',');
            if (index != -1) {
            	ip = ip.substring(0, index);
            }
        }
        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.getHeader("X-Real-IP");
        }
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }

	public static String listToString(List<?> stringList){
		if (stringList==null) {
            return null;
        }
        StringBuilder result=new StringBuilder();
        boolean flag=false;
        for (Object string : stringList) {
            if (flag) {
                result.append(",");
            }else {
                flag=true;
            }
            result.append(String.valueOf(string));
        }
        return result.toString();
	}


	public static boolean strIsEqual(String str1, String str2){
		if(StringUtils.isBlank(str1) || StringUtils.isBlank(str2))return false;
		if(str1.equals(str2) || str1.trim().equals(str2.trim()))return true;
		else return false;
	}

	/**
	 * 判断是否是整数
	 * @param str
	 * @return
	 */
	public static boolean isNumber(String str){
		if(StringUtils.isEmpty(str))return false;
		try {
			Long.parseLong(str);
			return true;
		} catch (Exception e) {
			return false;
		}
	}

	/**
	 * 判断是否是浮点数
	 * @param str
	 * @return
	 */
	public static boolean isDouble(String str){
		if(StringUtils.isEmpty(str))return false;
		try {
			Double.parseDouble(str);
			return true;
		} catch (Exception e) {
			return false;
		}
	}

	/**
	 * 密码加密方法
	 * @param pwd
	 * @return
	 */
	public static String encryptPwd(String pwd){
		if(StringUtils.isEmpty(pwd))return null;
		else return UnixCrypt.crypt(pwd, DigestUtils.sha256Hex(pwd));
	}

	/**
	 * 优惠码的生成, 默认6为长度
	 * @return
	 */
	public static String getCode() {
		return getCode(6);
	}

	/**
	 * 优惠码的生成
	 * @return
	 */
	public static String getCode(int length) {
		char[] chs = { 'a', 'b', 'c', '1', '2', '3', '4', '5', 'd', 'e', 'f',
				'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r',
				's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '6', '7', '8', '9' };
		SecureRandom random = new SecureRandom();
		final char[] value = new char[length];
		for (int i = 0; i < length; i++) {
			value[i] = chs[random.nextInt(chs.length)];
		}
		final String code = new String(value);
		return code;
	}

	/**
	 * 通过正则验证手机号码是否正确
	 * @param str
	 * @return
	 */
	public static boolean isMobile(String str) {
        boolean b = false;
        Pattern p=Pattern.compile("^1(3|4|5|7|8)\\d{9}$");
        Matcher m = p.matcher(str);
        b = m.matches();
        return b;
	}

	/**
	 * 使用urlencode对链接进行编码
	 * @param url
	 * @return
	 */
	public static String UrlEncode(String url){
		if(url == null || url.trim().equals(""))return null;
		try {
			return URLEncoder.encode(url, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * 使用URLDecoder对链接进行解码
	 * @param url
	 * @return
	 */
	public static String UrlDecode(String url){
		if(url == null || url.trim().equals(""))return null;
		try {
			return URLDecoder.decode(url, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			return null;
		}
	}

	public static boolean isEmpty(String str){
		return (str == null || "".equals(str.trim()));
	}

	public static boolean isNotEmpty(String str){
		return (str != null && str.trim().length() > 0);
	}

	/**
	 * 判断文件是否是图片
	 * @param file
	 * @return
	 */
	public static boolean isImage(File file){
		if(file == null)return false;
		boolean flag = false;
		try {
			InputStream inputStream = new FileInputStream(file);
			flag = isImage(inputStream);
			inputStream.close();
		} catch (Exception e) {
		}
		return flag;
	}

	/**
	 * 判断输入流是否是图片
	 * @param inputStream
	 * @return
	 */
	public static boolean isImage(InputStream inputStream){
		boolean flag = false;
		try {
			BufferedImage Image=ImageIO.read(inputStream);
			if(null == Image) {
				return flag;
			}
			Image.flush();
			flag = true;
		} catch (Exception e){
		}
		return flag;
	}

	/**
	 * 通过文件路径获取文件的ContentType
	 *  JDK1.7以上支持
	 * @param filePath
	 * @return ContentType
	 */
	public static String getFileContentType(String filePath){
		String contentType = null;
		try {
			contentType = Files.probeContentType(Paths.get(filePath));
		} catch (IOException e) {
			e.printStackTrace();
		}
		return contentType;
	}

	public static String getReqIpAddr(HttpServletRequest request) {
		String ip = null;
		try {
			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();
			}
			if(ip == null){
				ip = "未知IP";
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

        return ip;
    }

	/**
	 * 获取http访问路径，包括ContextPath
	 * @param request
	 * @return
	 */
	public static String getDomainPath(HttpServletRequest request){
		String strport = "";
		int port = request.getServerPort();
		if(port != 80){
			strport = ":"+port;
		}
		String domainPath = request.getScheme()+"://"+request.getServerName()+strport+request.getContextPath();
		return domainPath;
	}

    /**
     * 生成微信支付需要的nonce_str参数
     * @return
     */
    public static String getNonceStr(){
    	return UUID.randomUUID().toString().replace("-", "");
    }

    /**
	 * 生成[min,max]区间的随机小数 (保留2位小数)
	 * @param min
	 * @param max
	 * @return
	 */
	public static double getRandom(double min, double max){
		return getRandom(min, max, 2);
	}

	/**
	 * 生成[min,max]区间的随机小数
	 * @param min
	 * @param max
	 * @param scale 精度位数(保留的小数位数)
	 * @return
	 */
	public static double getRandom(double min, double max, int scale){
		Random r = new Random();
		double result = r.nextDouble() * (max-min) + min;
		result = round(result, scale); // 精度位数(保留的小数位数)
		return result;
	}

	private static double round(double value, int scale) {
		return round(value, scale, BigDecimal.ROUND_HALF_UP);
	}

	/**
    * 对double数据进行取精度.
    * @param value  double数据.
    * @param scale  精度位数(保留的小数位数).
    * @param roundingMode  精度取值方式.
    * @return 精度计算后的数据.
	*/
	private static double round(double value, int scale, int roundingMode) {
       BigDecimal bd = new BigDecimal(value);
       bd = bd.setScale(scale, roundingMode);
       double d = bd.doubleValue();
       bd = null;
       return d;
	}

	/**
	 * double保留2位小数
	 * @param value
	 * @return
	 */
	public static double getDouble2(double value) {
	   BigDecimal bd = new BigDecimal(value);
	   bd = bd.setScale(2, BigDecimal.ROUND_HALF_UP);
	   double d = bd.doubleValue();
	   bd = null;
	   return d;
	}

	/**
     * 向URL中添加参数(有则修改，无则添加)
     * @param url
     * @param ParamName
     * @param ParamValue
     * @return
     */
	public static String addParamValue(String url, String ParamName, String ParamValue) {
        if(StringUtils.isNotBlank(url) && StringUtils.isNotBlank(ParamName) && StringUtils.isNotBlank(ParamValue)) {
            if(url.contains(ParamName+"=")){
            	url = replaceParamValue(url, ParamName, ParamValue);
            }else{
            	if(url.contains("?") || url.contains("\\?")){
                	url += "&"+ParamName+"=" + ParamValue;
                }else{
                	url += "?"+ParamName+"=" + ParamValue;
                }
            }
        }
        return url;
    }

    /**
     * 替换URL参数的值
     * @param url
     * @param ParamName
     * @param ParamValue
     * @return
     */
	public static String replaceParamValue(String url, String ParamName, String ParamValue) {
		if(StringUtils.isNotBlank(url) && StringUtils.isNotBlank(ParamName) && StringUtils.isNotBlank(ParamValue)) {
            url = url.replaceAll("(\\?" + ParamName +"=[^&]*)", "?"+ParamName + "=" + ParamValue);
            url = url.replaceAll("(\\&" + ParamName +"=[^&]*)", "&"+ParamName + "=" + ParamValue);
        }
        return url;
    }

	/**
	 * 删除URL中的参数
	 * @param url
	 * @param ParamName
	 * @return
	 */
	public static String removeParamValue(String url, String ParamName) {
        if(StringUtils.isNotBlank(url) && StringUtils.isNotBlank(ParamName)) {
        	while(url.contains("?"+ParamName+"=") || url.contains("%3f"+ParamName+"%3d") || url.contains("%3F"+ParamName+"%3D")
        		|| url.contains("&"+ParamName+"=") || url.contains("%26"+ParamName+"%3d") || url.contains("%26"+ParamName+"%3D")){
        		url = url.replaceAll("(\\?" + ParamName +"=[^&]*)", "");
            	url = url.replaceAll("(%3f" + ParamName +"%3d[^&]*)", "");
                url = url.replaceAll("(%3F" + ParamName +"%3D[^&]*)", "");

            	url = url.replaceAll("(\\&" + ParamName +"=[^&]*)", "");
            	url = url.replaceAll("(%26" + ParamName +"%3d[^&]*)", "");
                url = url.replaceAll("(%26" + ParamName +"%3D[^&]*)", "");
            }
        }
        return url;
    }


	/**
	 * 获取当天日期
	 * @return
	 */
	public static int getDateNum() {
		return getDateNum(new Date());
	}
	// 获取指定时间日期
	public static int getDateNum(Date date) {
		String dateStr = getDateFormat(date, "yyyyMMdd");
		int dateNum = Integer.parseInt(dateStr);
		return dateNum;
	}

	public static String getRandomCode() {
		return getRandomCode(5);
	}

	public static String getRandomCode(int length) {
		char[] chs = { 'a', 'b', 'c', '1', '2', '3', 'd', 'e', 'f',
				'A', 'B', 'C', 'D', 'E', 'F',
				'4', '5',
				'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r',
				'6', '8',
				'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R',
				's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '6', '7', '8', '9',
				'2', '5', '9',
				'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' };

		SecureRandom random = new SecureRandom();
		char[] value = new char[length];
		for (int i = 0; i < length; i++) {
			value[i] = chs[random.nextInt(chs.length)];
		}
		String code = new String(value);
		return code;
	}

    public static void main(String[] args) {
		Map<String, Object> map = new HashMap<>();
		Map<String, Object> map2 = new HashMap<>();
		map.put("402880817dfaaae1017dfaac17ee0010","主kv");
		map.put("402880817dfaaae1017dfaac17ee0011","海报");
		map.put("402880817dfaaae1017dfaac17ee0012","长图");
		String s2 = "[{\"listValuesId\": 244,\"term\": \"1\"},{\"listValuesId\": 245,\"term\": \"3\"}]";
		System.out.println(s2);
		System.out.println(map);
		String s = JSONObject.toJSONString(map);
		System.out.println(s);
		//List<String> list = Arrays.asList(s.split(","));
		JSONArray jsonArray = JSONObject.parseArray(s2);
		System.out.println(jsonArray);
		for (int i = 0; i < jsonArray.size(); i++) {
			ProjectTaskTerm projectTaskTerm = jsonArray.getObject(i, ProjectTaskTerm.class);
			projectTaskTerm.setProjectId(UUIDUtil.uuid());
			projectTaskTerm.setId(UUIDUtil.uuid());
			System.out.println(projectTaskTerm);
		}
		System.out.println(getDouble2(2.31468d));
	}
}
