package com.steering.pss.plnsaleord.processOrder.base;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.math.RoundingMode;
import java.net.HttpURLConnection;
import java.net.URL;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map.Entry;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.xml.namespace.QName;
import javax.xml.rpc.ParameterMode;

import org.apache.axis.client.Call;
import org.apache.axis.client.Service;
import org.apache.axis.encoding.XMLType;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

public class Tools {
	private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	private static Logger logger = Logger.getLogger("Tools"); 
	
	/**
	 * 将字符串的编码格式转换为utf-8
	 * 
	 * @param str
	 * @return Name = new
	 * String(Name.getBytes("ISO-8859-1"), "utf-8");
	 */
	public static String toUTF8(String str) throws Exception{
		if (isEmpty(str)) {
			return "";
		}
		if (str.equals(new String(str.getBytes("GB2312"), "GB2312"))) {
			str = new String(str.getBytes("GB2312"), "utf-8");
			return str;
		}
		if (str.equals(new String(str.getBytes("ISO-8859-1"), "ISO-8859-1"))) {
			str = new String(str.getBytes("ISO-8859-1"), "utf-8");
			return str;
		}
		if (str.equals(new String(str.getBytes("GBK"), "GBK"))) {
			str = new String(str.getBytes("GBK"), "utf-8");
			return str;
		}
		return str;
	}
	

	/**
	 * 判断字符串是否为空
	 * 
	 * @param str
	 * @return
	 */
	public static boolean isEmpty(String str) {
		// 如果字符串不为null，去除空格后值不与空字符串相等的话，证明字符串有实质性的内容
		if (str != null && !str.trim().isEmpty()) {
			return false;// 不为空
		}
		return true;// 为空
	}

	/**
	 *ResultSet转换为JSON数组
	 * 
	 * @param ResultSet
	 * @return JSONArray
	 */
    public static JSONArray resultSetToJsonArry(ResultSet rs) throws Exception {
        JSONArray array = new JSONArray();
        JSONObject jsonObj = new JSONObject();
        ResultSetMetaData metaData = rs.getMetaData();
        int columnCount = metaData.getColumnCount();
        while (rs.next()) {
            jsonObj = new JSONObject();
            for (int i = 1; i <= columnCount; i++) {
                String columnName = metaData.getColumnLabel(i);
                if("NUMBER".equals(metaData.getColumnTypeName(i))){//getColumnType 2
                	double value = rs.getDouble(columnName);
                	jsonObj.put(columnName, value);
                }  
                else if("DATE".equals(metaData.getColumnTypeName(i))){//getColumnType 93
            		String value = rs.getTimestamp(columnName)==null?"":sdf.format(rs.getTimestamp(columnName));
            		jsonObj.put(columnName, value);
                }else{
                	String value = rs.getString(columnName);
                	jsonObj.put(columnName, StringUtils.isBlank(value)?"":value);
                }
            }
            array.add(jsonObj);
        }
        return array;
    }
    
    /**
     * 返回当前调用方法的类名、方法名以及行数*/
    public static String getDebugInfo(){
		StackTraceElement[] lvStacks = Thread.currentThread().getStackTrace();
		return  sdf.format(System.currentTimeMillis()) + " ClassName:"+lvStacks[2].getClassName() + ",FunctionName:" + lvStacks[2].getMethodName()
			    +",Line:"+ lvStacks[2].getLineNumber() + "\n";
	}

    /**
     * 发送https请求 
     * @param requestUrl  请求地址
     * @param requestMethod  请求方式（GET、POST）
     * @param outputStr  提交的数据
     * @return JSONObject(通过JSONObject.get(key)的方式获取json对象的属性值)
     * @throws NoSuchProviderException 
     * @throws NoSuchAlgorithmException 
     */
    public static JSONObject httpsRequest(String requestUrl, String requestMethod, String outputStr) throws Exception {
        JSONObject json = new JSONObject();
        // 创建SSLContext对象，并使用我们指定的信任管理器初始化
        TrustManager[] tm = null;
        SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
        sslContext.init(null, tm, new java.security.SecureRandom());
        // 从上述SSLContext对象中得到SSLSocketFactory对象
        SSLSocketFactory ssf = sslContext.getSocketFactory();

        URL url = new URL(requestUrl);
        HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
        conn.setSSLSocketFactory(ssf);

        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setUseCaches(false);
        // 设置请求方式（GET/POST）
        conn.setRequestMethod(requestMethod);

        // 当outputStr不为null时向输出流写数据
        if (null != outputStr) {
            OutputStream outputStream = conn.getOutputStream();
            // 注意编码格式
            outputStream.write(outputStr.getBytes("UTF-8"));
            outputStream.close();
        }

        // 从输入流读取返回内容
        InputStream inputStream = conn.getInputStream();
        InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
        BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
        String str = null;
        StringBuffer buffer = new StringBuffer();
        while ((str = bufferedReader.readLine()) != null) {
            buffer.append(str);
        }
        // 释放资源
        bufferedReader.close();
        inputStreamReader.close();
        inputStream.close();
        inputStream = null;
        conn.disconnect();
        json = JSONObject.fromObject(buffer.toString());
        String errcode = json.getString("errcode");
        if (!StringUtils.isBlank(errcode) && !errcode.equals("0")) {
            logger.error(json.toString());
            throw new Exception("ERRCODE:"+ errcode);
        }
        return json;
    }
    
    /**
     * 发送Http Get请求*/
    public static String httpURLGETCase(String methodUrl) {
        HttpURLConnection connection = null;
        BufferedReader reader = null;
        String line = null;
        StringBuilder result = new StringBuilder();
        try {
            URL url = new URL(methodUrl);
            connection = (HttpURLConnection) url.openConnection();// 根据URL生成HttpURLConnection
            connection.setRequestMethod("GET");// 默认GET请求
            connection.connect();// 建立TCP连接
            if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));// 发送http请求
                // 循环读取流
                while ((line = reader.readLine()) != null) {
                    result.append(line).append(System.getProperty("line.separator"));// "\n"
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                reader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            connection.disconnect();
        }
        return result==null?"":result.toString();
    }
    
    /**
     * 发送Http Post请求*/
    public static String httpURLPOSTCase(String methodUrl,String data) {
        HttpURLConnection connection = null;
        PrintWriter pw = null;
        BufferedReader reader = null;
        String line = "";
        StringBuilder result = new StringBuilder();
        try {
            URL url = new URL(methodUrl);
            connection = (HttpURLConnection)url.openConnection();// 根据URL生成HttpURLConnection
            connection.setDoOutput(true);// 设置是否向connection输出，因为这个是post请求，参数要放在http正文内，因此需要设为true,默认情况下是false
            connection.setDoInput(true); // 设置是否从connection读入，默认情况下是true;
            connection.setRequestMethod("POST");// 设置请求方式为post,默认GET请求
            connection.setUseCaches(false);// post请求不能使用缓存设为false
            connection.setConnectTimeout(1200000);// 连接主机的超时时间
            connection.setReadTimeout(1200000);// 从主机读取数据的超时时间
            connection.setInstanceFollowRedirects(true);// 设置该HttpURLConnection实例是否自动执行重定向
            
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");// 连接复用
            //connection.setRequestProperty("charset", "UTF-8");
            connection.setRequestProperty("Content-Type", "application/json");
            connection.setRequestProperty("user-agent","Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            connection.connect();// 建立TCP连接,getOutputStream会隐含的进行connect,所以此处可以不要

            pw = new PrintWriter(new OutputStreamWriter(connection.getOutputStream(), "UTF-8"));// 创建输入输出流,用于往连接里面输出携带的参数
            pw.write(data);//json数据
            pw.flush();
            pw.close();

            if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));// 发送http请求
                // 循环读取流
                while (null != (line = reader.readLine())) {
                    result.append(line);
                }
                reader.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            connection.disconnect();
        }
        return result.toString();
    }
    
    /** 
     * 使用NumberFormat,保留小数点后两位 
     * value 被修约参数
     * count 保留几位小数
     */  
    public static double numberFormat(double value,int count) {  
  
        NumberFormat nf = NumberFormat.getNumberInstance();  
        nf.setMaximumFractionDigits(2);  
        /* 
         * setMinimumFractionDigits设置成2 
         *  
         * 如果不这么做，那么当value的值是100.00的时候返回100 
         *  
         * 而不是100.00 
         */  
        nf.setMinimumFractionDigits(count);  
        nf.setRoundingMode(RoundingMode.HALF_UP);  
        /* 
         * 如果想输出的格式用逗号隔开，可以设置成true 
         */  
        nf.setGroupingUsed(false);  
        return Double.parseDouble(nf.format(value));  
    }
    
    /**数字类型字符串转换成数字再相加
     * value：数字类型字符串
     * incremental：加数
     * */
    public static String calculateIntegerForStringValue(String value, int incremental){
		if (value == null || value.length() == 0)
			throw new IllegalArgumentException("String Value is invalid :" + value);
		
		int length = value.length();
		String digit = "";
		for (int i=0; i<length; i++)
			digit += "0";
		
		DecimalFormat decimalFormat = new DecimalFormat(digit);
		Long number = null;
		try{
			number = (Long)decimalFormat.parse(value);			
		}catch (ParseException pe){
			return value;
		} 
		// long value
		int result = number.intValue() + incremental;
		return decimalFormat.format((long)result);
	}
    
    /**调用webservice接口
     * url:调用路径
     * TargetSpaceName:命名空间名，可在浏览器输入接口地址查看
     * serviceName:调用方法名
     * keys Object[] 对象数组类型:方法参数名
     * values Object[] 对象数组类型:参数值
     * */
    public static String webServiceAxisCase(String url,String TargetSpaceName,String serviceName,
    		 	Object[] values) throws Exception{
    	String result = "";
    	try {
            String endpoint = url;  
            //直接引用远程的wsdl文件
            Service service = new Service();  
            Call call = (Call) service.createCall();
            call.setTargetEndpointAddress(new URL(endpoint));  
            //call.setOperationName(serviceName);//调用的方法名 当这种调用不到的时候,可以使用下面的,加入命名空间名
            call.setOperationName(new QName(TargetSpaceName, serviceName));// 调用的方法名 加入命名空间名
            //java的webservice可以不传参数名，但是asmx的接口调用必须指定确定的参数名称与下列方法
            //call.setUseSOAPAction(true);
            //call.setSOAPActionURI(TargetSpaceName + serviceName);
            
            for(int i = 0; i < values.length; i++){
    			//String key = (String) keys[i]; //方法参数
    			Object value = values[i]; //参数值
    			if(value == null){
    				call.addParameter("arg"+i, XMLType.XSD_STRING, ParameterMode.IN);
    			} else if(value instanceof String){
    				call.addParameter("arg"+i, XMLType.XSD_STRING, ParameterMode.IN);
    			} else if(value instanceof Integer){
    				call.addParameter("arg"+i, XMLType.XSD_INTEGER, ParameterMode.IN);
    			} else if(value instanceof Boolean){
    				call.addParameter("arg"+i, XMLType.XSD_BOOLEAN, ParameterMode.IN);
    			}
    		}
            call.setReturnType(XMLType.XSD_STRING);// 设置返回类型  
            if(values.length == 0)
            	result = (String) call.invoke(new Object[]{});  
            else
            	result = (String) call.invoke(values);
            // 给方法传递参数，并且调用方法  
        } catch (Exception e) {  
            System.err.println("Error:"+e.toString());
        }  
    	return result;
    }
      
    /** 
     * ? 和参数的实际个数是否匹配 
     * 
     * @param sql 
     *   SQL 语句，可以带有 ? 的占位符 
     * @param params 
     *   插入到 SQL 中的参数，可单个可多个可不填 
     * @return true 表示为 ? 和参数的实际个数匹配 
     */
    public static boolean IsMatchParamter(String sql, Object[] params) { 
    	if(params == null || params.length == 0) return true; // 没有参数，完整输出 
    	Matcher m = Pattern.compile("(\\?)").matcher(sql); 
    	int count = 0; 
    	while (m.find()) { 
    		count++; 
    	} 
       
    	return count == params.length; 
    }
    /**
     * 获取实体类集合
     * @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();
        HashMap<String, Method> map = new HashMap<String, Method>();

        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);
                    if (rs.findColumn(fieldName) > 0) {
                        map.put(fieldName, method);
                    }
                }
            }
            catch (Exception e) {
            }
        }

        try {
            while (rs.next()) {
                T obj = cls.newInstance();
                Iterator<Entry<String, Method>> iter = map.entrySet()
                        .iterator();
                while (iter.hasNext()) {
                    Entry<String, Method> entry = iter.next();
                    String key = entry.getKey();
                    Method val = entry.getValue();
                    String strValue = rs.getString(key);
                    strValue = strValue == null ? "" : strValue;
                    val.invoke(obj, strValue);
                }
                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();
    }
    /**
	 * 将对象属性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;
		}
	}
	/**
	 * 判断字符串是否是数字
	 * 
	 * @param str
	 *            String
	 * @return boolean
	 */
	public static boolean isNumeric(String str) {
		return isInteger(str) || isDouble(str);
	}
	/**
	 * 判断字符串是否是整数
	 * 
	 * @param str
	 *            String
	 * @return boolean
	 */
	public static boolean isInteger(String str) {
		Pattern pattern = Pattern.compile("^[-\\+]?[\\d]+$");
		return pattern.matcher(str).matches();
	}

	/**
	 * 判断字符串是否是小数
	 * 
	 * @param str
	 *            String
	 * @return boolean
	 */
	public static boolean isDouble(String str) {
		Pattern pattern = Pattern.compile("^[-\\+]?\\d+\\.\\d+$");
		return pattern.matcher(str).matches();
	}
	
	public static JSONArray jsonArraySort(JSONArray array, final String sortColName,
            final boolean isAsc) {
JSONArray sortedJsonArray = new JSONArray();
List<JSONObject> jsonList = new ArrayList<JSONObject>();
for (int i = 0; i < array.size(); i++) {
jsonList.add(array.getJSONObject(i));
}

//将 JSONArray 转换成 List,本质上还是对 List 进行排序
Collections.sort(jsonList, new Comparator<JSONObject>() {
@Override
public int compare(JSONObject o1, JSONObject o2) {
String valA = o1.getString(sortColName);
String valB = o2.getString(sortColName);
if (isAsc) {
// 升序
return compare1(valA,valB);
} else {
return compare1(valB,valA);
}
}
});
// 此时jsonList已经是排完序的集合了
for(JSONObject obj : jsonList) {
sortedJsonArray.add(obj);
}
return sortedJsonArray;
	}
	public static int compare1(String o1, String o2) {		
		if (o1.equals(o2)) {			
			return 0;		
			}		
		int i = 0, j = 0;		
		String temp1, temp2;		
		int sum1, sum2;		
		int len1 = o1.length();		
		int len2 = o2.length();		
		int length = Math.min(len1, len2);		
		while (i < length && j < length) 
		{			
			temp1 = "";			
			temp2 = "";			
			// 1、当前位置不是数字，要么区分大小，要么相等循环继续			
			if (o1.charAt(i) > '9' || o1.charAt(i) < '0' || o2.charAt(j) > '9'					|| o2.charAt(j) < '0') 
			{				
				if (o1.charAt(i) == o2.charAt(j)) {					
					i++;					
					j++;					
					continue;				
					} else if (o1.charAt(i) > o2.charAt(j)) {					
						return 1;				
						} else {					
							return -1;				
							}			
				}			
			// 2、当前位置是数字，继续取后几位的数字，拼成字符串			
			while (i < len1 && o1.charAt(i) <= '9' && o1.charAt(i) >= '0') {				
				temp1 += o1.charAt(i);				
				i++;			
				}			
			while (j < len2 && o2.charAt(j) <= '9' && o2.charAt(j) >= '0') {				
				temp2 += o2.charAt(j);				
				j++;			
				}			
			// 计算字符串中数字的数值			
			sum1 = calculate(temp1);			
			sum2 = calculate(temp2);			
			// 如果数值相等，要么长度一致，那么i==j，循环继续;			
			// 要么长度不一致，长度较长的字符串前面是0，以0开头的放前面			
			if (sum1 == sum2) {				
				if (temp1.length() < temp2.length()) {					
					return 1;				
					} else if (temp1.length() > temp2.length()) {					
						return -1;				
						} else {					
							continue;				
							}			
				} else if (sum1 > sum2) {				
					return 1;			
					} else {				
						return -1;			
						}		
			}		
		// 超过较小长度，未判断出谁大谁小，即较长者放后面		
		return len1 > len2 ? 1 : -1;	
		}
private static int calculate(String str) {		
	// 这里要小心，需要判断有效性		
	if (str == null || str.length() == 0) {			
		return 0;		
		}		
	int len = str.length();		
	double sum = 0;		
	int sign = 1;		
	int j = 0;		
	// 剔除字符串前方的空格		
	while (str.charAt(j) == ' ') 
	{			
		j++;		
		}		
	// 判断正数和负数		
	if (str.charAt(j) == '+') {			
		sign = 1;			
		j++;		
		} else if (str.charAt(j) == '-') {			
			sign = -1;			
			j++;		
			}		
	// 计算剩余字符串		
	for (int i = j; i < len; i++) {			
		char current = str.charAt(i);			
		if (current >= '0' && current <= '9') {				
			sum = sum * 10 + (int) (current - '0');			
			} else {				
				// 碰到非数字，退出转换				
				break;			
				}		
		}		
	sum = sum * sign;		
	// 这里要小心，需要判断范围		
	if (sum > Integer.MAX_VALUE) {			
		sum = Integer.MAX_VALUE;		
		} else if (sum < Integer.MIN_VALUE) {			
			sum = Integer.MIN_VALUE;		}		
	return (int) sum;	}

/**
 * 去除平均值误差,返回LIST<double[]> list里五个double数组,数组里两个数据,第一个支数,第二个单支重量
 * @param wgt 重量
 * @param num 支数
 * @return LIST<double[]>
 */
public static List<double[]> MeanCalculation(double wgt, int num) {
    List<double[]> list = new ArrayList<double[]>();
    double[] num1 = new double[2];
    double[] num2 = new double[2];
    double[] num3 = new double[2];
    double[] num4 = new double[2];
    double[] numSurplus = new double[2];
    DecimalFormat df = new DecimalFormat("######0.000");
    String meanValue = df.format(wgt / num);
    String error = df.format(wgt - Double.parseDouble(meanValue) * num);
    int index = error.indexOf(".");
    if (num < 10) {
        num1[0] = 1;
        num1[1] = Double.parseDouble(df.format(Double.parseDouble(error)
                + Double.parseDouble(meanValue)));
        num2[0] = 0;
        num2[1] = 0;
        num3[0] = 0;
        num3[1] = 0;
        num4[0] = 0;
        num4[1] = 0;
        numSurplus[0] = num - num1[0];
        numSurplus[1] = Double.parseDouble(meanValue);
        if (numSurplus[0] <= 0) {
            numSurplus[0] = 0;
            numSurplus[1] = 0;
        }
    }
    if (num >= 10 && num < 100) {
        double a = Double
                .parseDouble(error.substring(index + 3, index + 4)) / 1000;
        if (error.startsWith("-")) {
            a = -a;
        }
        num1[0] = 1;
        num1[1] = Double.parseDouble(df.format(a
                + Double.parseDouble(meanValue)));
        num2[0] = 10;
        if (num == 10) {
            num2[0] = 9;
        }
        num2[1] = Double
                .parseDouble(df.format((Double.parseDouble(error) - a)
                        / num2[0] + Double.parseDouble(meanValue)));
        num3[0] = 0;
        num3[1] = 0;
        num4[0] = 0;
        num4[1] = 0;
        numSurplus[0] = num - num1[0] - num2[0];
        numSurplus[1] = Double.parseDouble(meanValue);
        if (numSurplus[0] <= 0) {
            numSurplus[0] = 0;
            numSurplus[1] = 0;
        }
    }
    if (num >= 100 && num < 1000) {
        double a = Double
                .parseDouble(error.substring(index + 3, index + 4)) / 1000;
        if (error.startsWith("-")) {
            a = -a;
        }
        num1[0] = 1;
        num1[1] = a + Double.parseDouble(meanValue);
        double b = Double.parseDouble(df.format(Double.parseDouble(error
                .substring(index + 2, index + 3)) / 100));
        if (error.startsWith("-")) {
            b = -b;
        }
        num2[0] = 10;
        num2[1] = Double.parseDouble(df.format(b / num2[0]
                + Double.parseDouble(meanValue)));
        num3[0] = 100;
        if (num >= 100 && num <= 110) {
            num3[0] = num - 11;
        }
        num3[1] = Double.parseDouble(df.format((Double.parseDouble(error)
                - a - b)
                / num3[0] + Double.parseDouble(meanValue)));
        num4[0] = 0;
        num4[1] = 0;
        numSurplus[0] = num - num1[0] - num2[0] - num3[0];
        numSurplus[1] = Double.parseDouble(meanValue);
        if (numSurplus[0] <= 0) {
            numSurplus[0] = 0;
            numSurplus[1] = 0;
        }
    }
    if (num >= 1000 && num < 10000) {
        double a = Double
                .parseDouble(error.substring(index + 3, index + 4)) / 1000;
        if (error.startsWith("-")) {
            a = -a;
        }
        num1[0] = 1;
        num1[1] = a + Double.parseDouble(meanValue);
        double b = Double.parseDouble(df.format(Double.parseDouble(error
                .substring(index + 2, index + 3)) / 100));
        if (error.startsWith("-")) {
            b = -b;
        }
        num2[0] = 10;
        num2[1] = b / num2[0] + Double.parseDouble(meanValue);
        double c = Double.parseDouble(df.format(Double.parseDouble(error
                .substring(index + 1, index + 2)) / 10));
        if (error.startsWith("-")) {
            c = -c;
        }
        num3[0] = 100;
        num3[1] = Double.parseDouble(df.format(c / 100
                + Double.parseDouble(meanValue)));
        num4[0] = 1000;
        if (num >= 1000 && num <= 1110) {
            num4[0] = 1110-num;
        }
        num4[1] = (Double.parseDouble(error) - a - b - c) / num4[0]
                + Double.parseDouble(meanValue);
        numSurplus[0] = num - num1[0] - num2[0] - num3[0] - num4[0];
        numSurplus[1] = Double.parseDouble(meanValue);
        if (numSurplus[0] <= 0) {
            numSurplus[0] = 0;
            numSurplus[1] = 0;
        }
    }
    if (num >= 10000) {
        num1[0] = 0;
        num1[1] = 0;
        num2[0] = 0;
        num2[1] = 0;
        num3[0] = 0;
        num3[1] = 0;
        num4[0] = 0;
        num4[1] = 0;
        numSurplus[0] = 0;
        numSurplus[1] = 0;
    }
    list.add(num1);
    list.add(num2);
    list.add(num3);
    list.add(num4);
    list.add(numSurplus);
    return list;
}



}
