package foundation.util;

import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.math.BigDecimal;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.Charset;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import oracle.net.aso.l;

import foundation.config.Configer;
import foundation.data.Entity;
import foundation.data.EntitySet;
import foundation.persist.DataBaseType;
import foundation.persist.DataHandler;
import foundation.persist.sql.NamedSQL;
import foundation.user.OnlineUser;

public class Util {

	public static final String TRUE = "T";
	public static final String FALSE = "F";
	public static final String String_Return = "\r\n";
	public static final String String_Empty = "";

	public static String newShortGUID() {
		UUID uuid = UUID.randomUUID();
		String strGUID;
		String shortGUID;

		strGUID = uuid.toString();
		shortGUID = strGUID.substring(0, 8) + strGUID.substring(9, 13) + strGUID.substring(14, 18) + strGUID.substring(19, 23)
				+ strGUID.substring(24, 36);

		return shortGUID;
	}

	public static String quotedStr(String str) {
		if (str != null)
			return "'" + str + "'";
		else
			return "''";
	}

	public static String doubleQuotedStr(String str) {
		if (str != null)
			return "\"" + str + "\"";
		else
			return "\"\"";
	}

	public static String quotedLikeStr(String str) {
		if (str != null)
			return "'%" + str + "%'";
		else
			return "''";
	}
	
	public static String[] split(String str) {
		if (str == null) {
			return new String[0];
		}
		
		return str.replace(",", ";").replace("，", ";").replace("；", ";").split(";");
	}

	public static String newDBDateString() throws Exception {
		Date date = new Date();
		return newDBDateString(date);
	}

	public static String newDBDateString(Date date) throws Exception {
		DataBaseType dbType = Configer.getDataBaseType();

		if (DataBaseType.Oracle == dbType) {
			return newOracleDateString(date);
		}
		else if (DataBaseType.SQLServer == dbType) {
			return newSqlServerDateString(date);
		}
		else if (DataBaseType.MySQL == dbType) {
			return newMySqlDateString(date);
		}
		else {
			return DataTimeToString(date);
		}
	}

	public static String toOracleDataStr(String dataStr) {
		return "to_date('" + dataStr + "','YYYY-MM-DD HH24:MI:SS')";
	}

	public static String toMySQLDateStr(Date value) {
		return DataTimeToString(value, "yyyy-MM-dd HH:mm:ss");
	}

	public static String DataTimeToString(Date value) {
		return DataTimeToString(value, "yyyy-MM-dd HH:mm:ss");
	}
	
	public static String MySqlDateToString(Date value) {
		return DataTimeToString(value, "yyyy-MM-dd");
	}
	
	public static String DataTimeToString(Date value, String format) {
		if (value == null) {
			return null;
		}

		String result = "";
		DateFormat dateFormat = new SimpleDateFormat(format);
		result = dateFormat.format(value);

		return result;
	}

	public static String newDateStr() {
		return newDateTimeStr("yyyy-MM-dd");
	}

	public static String newDateTimeStr() {
		return newDateTimeStr("yyyy-MM-dd kk:mm:ss");
	}

	public static String newDateTimeStr(String fomater) {
		return getDateTimeStr(new Date(), fomater);
	}

	public static String getDateTimeStr(Date date, String fomater) {
		String result = "";
		DateFormat dateFormat = new SimpleDateFormat(fomater);
		result = dateFormat.format(date);

		return result;
	}

	public static String booleanToStr(boolean value) {
		if (value)
			return "T";
		else
			return "F";
	}

	public static boolean isEmptyStr(Object str) {
		boolean result = false;

		if ((str == null) || ("".equals(str)))
			result = true;

		return result;
	}
	
	public static String IfEmpetyStr(String str, String value) {
		if (isEmptyStr(str)) {
			return value;
		}
		
		return str;
	}

	public static boolean isNull(String value) {
		if ((value == null))
			return true;

		if ("".equals(value)) {
			return true;
		}

		if (value.length() == 4) {
			value = value.toLowerCase();
			return "null".equals(value);
		}

		return false;
	}

	public static String UTF8decode(String str) {
		if (!isUTF8Encoding(str))
			return str;
		byte[] bytes = str.getBytes();
		ByteBuffer bb = ByteBuffer.wrap(bytes);
		Charset csets = Charset.forName("UTF-8");
		CharBuffer c = csets.decode(bb);
		return c.toString();
	}

	private static boolean isUTF8Encoding(String str) {
		byte[] bytes = str.getBytes();
		for (int i = 0; i < bytes.length; i++) {
			int byteLen = Byte.toString(bytes[i]).length();
			if (byteLen == 4)
				return true;
			else
				continue;
		}
		return false;
	}

	public static boolean stringToBoolean(String value) {
		if (value != null) {
			value = value.toLowerCase();

			if (value.equals("t")) {
				return true;
			}
			else if (value.equals("y")) {
				return true;
			}
			else if (value.equals("true")) {
				return true;
			}
			else if (value.equals("yes")) {
				return true;
			}
			else {
				return false;
			}
		}
		else
			return false;
	}

	public static int stringToInt(String value, int defaultValue) {
		if (value != null) {
			try {
				Double doubleValue = Double.valueOf(value);
				return doubleValue.intValue();
			}
			catch (Exception e) {
				return defaultValue;
			}
		}
		else
			return defaultValue;
	}

	public static BigDecimal stringToBigDecimal(String value, BigDecimal defaultValue) {
		if (value == null) {
			return defaultValue;
		}

		try {
			BigDecimal decimalValue = BigDecimal.valueOf(Double.valueOf(value));
			return decimalValue;
		}
		catch (Exception e) {
			return defaultValue;
		}
	}

	public static Date StringToDate(String str) throws ParseException {
		if (Util.isEmptyStr(str)) {
			return null;
		}

		Date result = null;
		String fomater = null;
		str = str.replace('T', ' ');

		if (str.indexOf("/") == 4) {
			fomater = "yyyy/MM/dd";
		}
		else if (str.indexOf("/") == 2 || str.indexOf("/") == 1) {
			fomater = "MM/dd/yyyy";
		}
		else if (str.indexOf("-") == 2 || str.indexOf("-") == 1) {
			fomater = "MM-dd-yyyy";
		}
		else if (str.indexOf("-") == 4 && str.indexOf(":") < 0) {
			fomater = "yyyy-MM-dd";
		}
		else if (str.indexOf("-") == 4 && str.indexOf(":") > 0) {
			if (str.split(":").length == 3) {
				fomater = "yyyy-MM-dd HH:mm:ss";
			}
			else {
				str = str + ":00";
				fomater = "yyyy-MM-dd HH:mm:00";
			}

		}
		else if (str.indexOf(".") == 2 || str.indexOf(".") == 1) {
			fomater = "MM.dd.yyyy";
		}
		else if (str.indexOf(".") == 4) {
			fomater = "yyyy.MM.dd";
		}
		else if (str.indexOf("-") < 0 && str.indexOf("/") < 0) {
			fomater = "yyyyMMdd";
		}

		DateFormat dateFormat = new SimpleDateFormat(fomater);
		result = dateFormat.parse(str);

		return result;
	}

	public static Date doubleToDate(Double value) throws ParseException {
		Date result = null;

		if (value != null) {
			if (value > 195000 && value <= 210001) {
				value = value * 100 + 01;
			}

			if (value >= 19500101 && value <= 21000101) {
				String value_Str = String.valueOf(value.intValue());
				result = Util.StringToDate(value_Str);
			}
			else if (value > (1950 - 1900) * 365 && value < (2100 - 1900) * 365) {
				int dateValue = value.intValue();
				double secValue = value - dateValue;
				Date dayDate = intToDate(dateValue);
				long sec = Math.round(secValue * 24 * 3600 * 1000);

				result = new Date();
				result.setTime(dayDate.getTime() + sec);
				return result;
			}
		}

		return result;
	}

	public static Date intToDate(int value) {
		Calendar result = Calendar.getInstance();
		result.set(Calendar.YEAR, 1900);
		result.set(Calendar.MONTH, 0);
		result.set(Calendar.DAY_OF_MONTH, 1);
		result.set(Calendar.HOUR_OF_DAY, 0);
		result.set(Calendar.MINUTE, 0);
		result.set(Calendar.SECOND, 0);

		result.add(Calendar.DATE, value - 2);
		return result.getTime();
	}

	public static int getArrayContentSize(Object[] datas) {
		int result = 0;

		for (int i = 0; i < datas.length; i++) {
			if (datas[i] != null) {
				result++;
			}
		}

		return result;
	}

	public static String deleteSuffix(String name) {
		String result = null;

		if (!isEmptyStr(name)) {
			int pos = name.lastIndexOf(".");
			result = name.substring(0, pos);
		}

		return result;
	}

	public static String[] mergeArray(String[] array1, String[] array2) {
		if (array1 == null) {
			return array2;
		}

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

		List<String> set = new ArrayList<String>(array1.length + array2.length);

		for (int i = 0; i < array1.length; i++) {
			set.add(array1[i]);
		}

		for (int i = 0; i < array2.length; i++) {
			if (!set.contains(array2[i])) {
				set.add(array2[i]);
			}
		}

		String[] result = new String[0];
		return set.toArray(result);
	}

	public static String newOracleDateString(Date date) {
		String nowStr = "";
		DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		nowStr = dateFormat.format(date);

		return "to_date('" + nowStr + "','YYYY-MM-DD HH24:MI:SS')";
	}

	public static String newMySqlDateString(Date date) {
		String nowStr = "";
		DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		nowStr = dateFormat.format(date);

		return "('" + nowStr + "')";
	}

	public static String newSqlServerDateString(Date date) {
		String nowStr = "";
		DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		nowStr = dateFormat.format(date);

		return "('" + nowStr + "')";
	}

	public static boolean isSameString(String value1, String value2) {
		if (value1 == null) {
			if (value2 == null) {
				return true;
			}
			else {
				return false;
			}
		}
		else {
			if (value2 == null) {
				return false;
			}
			else {
				return value1.equals(value2);
			}
		}
	}

	public static boolean isSameStringIgnoreCase(String value1, String value2) {
		if (value1 == null) {
			if (value2 == null) {
				return true;
			}
			else {
				return false;
			}
		}
		else {
			if (value2 == null) {
				return false;
			}
			else {
				return value1.equalsIgnoreCase(value2);
			}
		}
	}

	public static String toLowerCase(String name, String defaultValue) {
		if (name == null) {
			return defaultValue;
		}
		else {
			return name.toLowerCase();
		}
	}

	public static String getExceptionStack(Exception e) {
		ByteArrayOutputStream outStream = new ByteArrayOutputStream();
		PrintStream printStream = new PrintStream(outStream);
		e.printStackTrace(printStream);

		return outStream.toString();
	}

	public static Date getSpecialDayOffToday(int dayCount) {
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(new Date());
		calendar.set(Calendar.DAY_OF_YEAR, calendar.get(Calendar.DAY_OF_YEAR) + dayCount);
		return calendar.getTime();
	}

	public static String getPassWord(int length) {
		int[] array = new int[length];
		char[] chars = new char[length];
		StringBuilder str = new StringBuilder();
		int temp = 0;
		for (int i = 0; i < length; i++) {
			while (true) {
				temp = (int) (Math.random() * 1000);
				if (temp >= 48 && temp <= 57)
					break;
				if (temp >= 65 && temp <= 90)
					break;
				if (temp >= 97 && temp <= 122)
					break;
			}

			array[i] = temp;
			chars[i] = (char) array[i];
			str.append(chars[i]);
		}

		return str.toString();
	}

	public static void main(String[] args) {
		System.out.println(getPassWord(10));
	}

	public static String escapeQuoted(String filter) {
		if (filter == null) {
			return filter;
		}

		int length = filter.length();

		if (length <= 1) {
			return filter;
		}

		char first = filter.charAt(0);
		char last = filter.charAt(length - 1);

		if (('\'' == first || '"' == first) && (first == last)) {
			filter = filter.substring(1, length - 1);
			filter = filter.trim();
			return filter;
		}

		return filter;
	}

	public static int[] getCurYearMonth() {
		Date date = new Date();
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);
		int year = calendar.get(Calendar.YEAR);
		int month = calendar.get(Calendar.MONTH) + 1;
		return new int[] { year, month };
	}

	public static String getTimeStamp(Date date) {
		DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		return dateFormat.format(date);
	}

	public static String getFileExt(String filename) {
		int pos = filename.lastIndexOf(".");
		String ext = filename.substring(pos);
		return ext;
	}

	public static int getMonth(String value) throws ParseException {
		Date date = StringToDate(value);
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);
		return calendar.get(Calendar.MONTH) + 1;
	}
	
    public static void getFile(byte[] bfile, String filePath, String fileName) {  
        BufferedOutputStream bos = null;  
        FileOutputStream fos = null;  
        File file = null;  
        try {  
            File dir = new File(filePath);  
            if(!dir.exists()){//判断文件目录是否存在  
                dir.mkdirs();  
            }  
            file = new File(filePath+"\\"+fileName);  
            fos = new FileOutputStream(file);  
            bos = new BufferedOutputStream(fos);  
            bos.write(bfile);  
        } catch (Exception e) {  
            e.printStackTrace();  
        } finally {  
            if (bos != null) {  
                try {  
                    bos.close();  
                } catch (IOException e1) {  
                    e1.printStackTrace();  
                }  
            }  
            if (fos != null) {  
                try {  
                    fos.close();  
                } catch (IOException e1) {  
                    e1.printStackTrace();  
                }  
            }  
        }  
    }  
    public static String getchildren(OnlineUser user)  {
    	List<Map<String, StringBuilder>> mappingList = new ArrayList<Map<String,StringBuilder>>();
    	String userId = user.getId();
    	String chlidren = "'"+ userId + "'";
    	
    	try {
			EntitySet entitySet = DataHandler.getDataSet("territory","1=1");
			
			for (Entity entity : entitySet) {
				int field = 2;
				
				while (field <= 7) {
					String id = entity.getString("parentid" + field);
					
					if (id == null || id.isEmpty()) {
						break;
					}
					
					if (id.equalsIgnoreCase(userId)) {
						String childId = entity.getString("parentid1");
						String childStr = ",'" + childId +"'";
						Entity line = DataHandler.getLine("usr", childId);
						String rolecode = line.getString("rolecode");
						
						for (Map<String, StringBuilder> mapping : mappingList) {
							
							if (mapping.containsKey(rolecode)) {
								StringBuilder stringBuilder = mapping.get(rolecode);
								stringBuilder.append(childStr);
							}
							
							LinkedHashMap<String,StringBuilder> map = new LinkedHashMap<String, StringBuilder>();
							StringBuilder stringBuilder = new StringBuilder(chlidren);
							stringBuilder.append(childStr);
							map.put(rolecode, stringBuilder);
							mappingList.add(map);
						}
						
						break;
					}
					field++;
				}
			}
			for (Map<String, StringBuilder> mapping : mappingList) {
				
			}
		chlidren = builder.toString();
    	} catch (Exception e) {
			e.printStackTrace();
		}
		return chlidren;
	}
}
