package com.steering.pss.sale.order.qualityDesign;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.sql.ResultSet;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 质量设计 工具类
 * 
 * @author Administrator
 * 
 */
public class QualityDesignTool {

	/**
	 * 将对象属性NULL转化为空字符串
	 * 
	 * @param obj
	 */
	public static void nullConverNullString(Object obj) {
		if (obj != null) {

			Class<? extends Object> classz = obj.getClass();
			// 获取所有该对象的属性值
			Field fields[] = classz.getDeclaredFields();
			// 遍历属性值，取得所有属性为 null 值的
			for (Field field : fields) {
				try {
					Type t = field.getGenericType();
					if (!t.toString().equals("boolean")) {
						Method m = classz.getMethod("get"
								+ change(field.getName()));
						Object name = m.invoke(obj);// 调用该字段的get方法
						if (name == null) {

							Method mtd = classz.getMethod(
									"set" + change(field.getName()),
									new Class[] { String.class });// 取得所需类的方法对象
							mtd.invoke(obj, new Object[] { "" });// 执行相应赋值方法
						}
					}

				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
	}

	/**
	 * @param src
	 *            源字符串
	 * @return 字符串，将src的第一个字母转换为大写，src为空时返回null
	 */
	public static String change(String src) {
		if (src != null) {
			StringBuffer sb = new StringBuffer(src);
			sb.setCharAt(0, Character.toUpperCase(sb.charAt(0)));
			return sb.toString();
		} else {
			return null;
		}
	}

	/**
	 * 验证字符串 如：1<2
	 * 
	 * @param strA
	 *            数字字符串
	 * @param sign
	 *            符号
	 * @param strB
	 *            数字字符串
	 * @return true Or false
	 */
	public static boolean checkStr(String strA, String sign, String strB) {
		if (strA.length() == 0 || strB.length() == 0) {
			return true;
		}
		double a = Double.parseDouble(strA);
		double b = Double.parseDouble(strB);
		if (sign.equals("=")) {
			if (a == b) {
				return true;
			} else {
				return false;
			}
		}
		if (sign.equals(">")) {
			if (a > b) {
				return true;
			} else {
				return false;
			}
		}
		if (sign.equals(">=")) {
			if (a >= b) {
				return true;
			} else {
				return false;
			}
		}
		if (sign.equals("<")) {
			if (a < b) {
				return true;
			} else {
				return false;
			}
		}
		if (sign.equals("<=")) {
			if (a <= b) {
				return true;
			} else {
				return false;
			}
		}
		return false;
	}

	/**
	 * 时间 加天数
	 * 
	 * @param d
	 * @param day
	 * @return
	 * @throws ParseException
	 */
	public static Date addDate(Date d, double day) throws ParseException {

		long time = d.getTime();
		long dayTime = Math.round(day * 24 * 60 * 60 * 1000);
		time += dayTime;
		return new Date(time);

	}

	/**
	 * 时间转化为字符串
	 * 
	 * @param time
	 * @return
	 */
	public static String DateToString(Date time) {
		SimpleDateFormat sdf = new SimpleDateFormat(" yyyy-MM-dd HH:mm:ss ");
		String str = sdf.format(time);
		return str;

	}

	/**
	 * 字符串时间 转化为时间类型
	 * 
	 * @param str
	 * @return
	 * @throws ParseException
	 */
	public static Date StringToDate(String str) throws ParseException {
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date time = formatter.parse(str);
		return time;
	}

	/**
	 * 比较两个数组元素相同
	 * 
	 * @param arrayA
	 *            数组A
	 * @param arrrayB
	 *            数组B
	 * @return boolean
	 */
	public static boolean checkStringArraysCommon(String[] arrayA,
			String[] arrayB) {
		if (arrayA.length == 0 && arrayB.length != 0) {
			return false;
		}
		if (arrayA.length != 0 && arrayB.length == 0) {
			return false;
		}
		if (arrayA.length == 0 && arrayB.length == 0) {
			return true;
		}
		Arrays.sort(arrayA);
		Arrays.sort(arrayB);
		if (Arrays.equals(arrayA, arrayB)) {
			return true;
		} else {
			return false;
		}

	}

	/**
	 * 计算字符串公式
	 * 
	 * @param formula
	 *            字符串
	 * @return Object
	 * @throws ScriptException
	 */
	public static double countFormula(String formula) throws ScriptException {
		ScriptEngine jse = new ScriptEngineManager()
				.getEngineByName("JavaScript");
		return Double.valueOf(jse.eval(formula).toString());
	}

	/**
	 * 获取实体类集合
	 * 
	 * @param rs
	 *            结果集
	 * @param cls
	 *            实体类的类型
	 * @return 实体类集合
	 */
	public static <T> ArrayList<T> getEntitysByRs(ResultSet rs, Class<T> cls) {
		ArrayList<T> list = new ArrayList<T>();
		Method[] methods = cls.getMethods();
		try {
			while (rs.next()) {
				T obj = cls.newInstance();
				for (int i = 0; i < methods.length; i++) {
					try {
						Method method = methods[i];
						String methodName = method.getName();
						if (methodName.startsWith("set")) {
							String entityName = methodName.substring(3,
									methodName.length());
							String fieldName = getSqlFieldName(entityName);
							String val = rs.getString(fieldName);
							method.invoke(obj, val);
						}
					} catch (Exception e) {
					}
				}
				list.add(obj);
			}
		} catch (Exception e) {
			return list;
		}
		return list;
	}

	// 比如： StdCode转换为 STD_CODE
	private static String getSqlFieldName(String fieldName) {
		StringBuilder sb = new StringBuilder(fieldName);
		for (int i = 1; i < sb.length(); i++) {
			char ch = sb.charAt(i);
			if (Character.isUpperCase(ch)) {
				sb.insert(i, '_');
				i++;
			}
		}

		return sb.toString().toUpperCase();
	}

	/**
	 * 过滤集合属性值完全相同的元素
	 * 
	 * @param objs
	 *            集合
	 * @return List<Object>
	 * @throws SecurityException
	 * @throws NoSuchMethodException
	 * @throws IllegalArgumentException
	 * @throws IllegalAccessException
	 * @throws InvocationTargetException
	 */
	public static List<Object> fiterCommonObj(List<Object> objs)
			throws SecurityException, NoSuchMethodException,
			IllegalArgumentException, IllegalAccessException,
			InvocationTargetException {
		if (objs == null || objs.size() == 0) {
			return null;
		}
		Map<String, Object> map = new HashMap<String, Object>();
		for (Object obj : objs) {
			Class<? extends Object> classz = obj.getClass();
			// 获取所有该对象的属性值
			Field fields[] = classz.getDeclaredFields();
			String names = "";
			for (Field field : fields) {
				Method m = classz.getMethod("get" + change(field.getName()));
				Object name = m.invoke(obj);// 调用该字段的get方法
				names += name;
			}
			if (!map.containsKey(names)) {
				map.put(names, obj);
			}
		}
		if (map.size() == 0) {
			return null;
		}
		// 取出MAP里的元素
		List<Object> objNs = new ArrayList<Object>();
		Iterator<?> it = map.entrySet().iterator();
		while (it.hasNext()) {
			@SuppressWarnings("rawtypes")
			java.util.Map.Entry entry = (java.util.Map.Entry) it.next();
			objNs.add(entry.getValue());
		}
		return objNs;
	}

	/**
	 * 对象所有属性的值
	 * 
	 * @param obj
	 *            对象
	 * @return String
	 * @throws SecurityException
	 * @throws NoSuchMethodException
	 * @throws IllegalArgumentException
	 * @throws IllegalAccessException
	 * @throws InvocationTargetException
	 */
	public static String getObjNames(Object obj) throws SecurityException,
			NoSuchMethodException, IllegalArgumentException,
			IllegalAccessException, InvocationTargetException {
		if (obj == null) {
			return "";
		}
		Class<? extends Object> classz = obj.getClass();
		// 获取所有该对象的属性值
		Field fields[] = classz.getDeclaredFields();
		String names = "";
		for (Field field : fields) {
			Method m = classz.getMethod("get" + change(field.getName()));
			Object name = m.invoke(obj);// 调用该字段的get方法
			names += name;
		}
		return names;
	}

	/**
	 * 验证是否为DOUBLE
	 * 
	 * @param str
	 * @return
	 */
	public static boolean isNumeric(String str) {
		try {
			Double.parseDouble(str);
		} catch (Exception e) {
			return false;
		}
		return true;
	}

}
