package com.dashitech.utils;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.*;

/**
 * 混杂工具类
 * Created by CX on 2017/3/31 0031.
 */
public class CommonUtil {
    private static final Logger LOG = LoggerFactory.getLogger(CommonUtil.class);

    private CommonUtil(){}

    public static <T> List<?> transList(List<?> list) {
        return list;
    }

    /**
     * 把新地址加入到classpath中
     * @param path 新地址,绝对路劲
     * @return  是否成功
     */
    public static boolean addJavaClassPath(String path) {
        try {
            File programRootDir = new File(path);
            URLClassLoader classLoader = (URLClassLoader) ClassLoader.getSystemClassLoader();
            Method add = URLClassLoader.class.getDeclaredMethod("addURL", new Class[]{URL.class});
            add.setAccessible(true);
            add.invoke(classLoader, programRootDir.toURI().toURL());
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 在source的下标 start和end中间插入newStr
     */
    public static String cutInsertString(String source, int start, int end, String newStr) {
        String startStr = source.substring(0, start);
        String endStr = source.substring(end, source.length());
        String result = startStr + newStr + endStr;
        return result;
    }

    /**
     * 获取中文类型长度，中文长度2，其他1
     */
    public static int getChineseLength(String source) {
        int valueLength = 0;
        String chinese = "[\u0391-\uFFE5]";
		/* 获取字段值的长度，如果含中文字符，则每个中文字符长度为2，否则为1 */
        for (int i = 0; i < source.length(); i++) {
			/* 获取一个字符 */
            String temp = source.substring(i, i + 1);
			/* 判断是否为中文字符 */
            if (temp.matches(chinese)) {
				/* 中文字符长度为2 */
                valueLength += 2;
            } else {
				/* 其他字符长度为1 */
                valueLength += 1;
            }
        }
        return valueLength;
    }

    /**
     * 获取翻页数
     *
     * @param itemTotal
     *            总条数
     * @param PageCount
     *            一页数
     * @return 翻页数
     */
    public static int getPageTotal(Integer itemTotal, int PageCount) {
        // 设置总页数
        int total = 0;
        if (itemTotal % PageCount == 0) {
            total = itemTotal / PageCount;
        } else {
            total = (itemTotal / PageCount) + 1;
        }
        return total;
    }

    /**
     * 自己写sql分页必须处理pageIndex
     */
    public static int getPageIndex(int pageIndex,int showCount) {
        int result = 0;
        if(pageIndex <= 1) {
            result = 0;
        }else if(pageIndex > 1) {
            result = ((pageIndex * showCount) - showCount);
        }
        return result;
    }

    /**
     * url中文编码
     */
    public static String urlEncode(String url) {
        String s = url;
        try {
            s = URLEncoder.encode(url, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return s;
    }

    /**
     * url中文解码
     */
    public static String urlDecode(String url) {
        String s = url;
        try {
            s = URLDecoder.decode(url, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return s;
    }

    /**
     * 排序
     * @param list
     * @param field 字段名称，必须有get方法
     * @param fieldType 字段类型
     */
    public static void sort(List<?> list,final String field,final String fieldType) {
        Collections.sort(list, new Comparator<Object>() {
            public int compare(Object o1, Object o2) {
                Method m = null;
                try {
                    String getKey = "get" + field.toUpperCase().charAt(0) + field.substring(1, field.length());
                    m = o1.getClass().getMethod(getKey);
                    Object o1Value = m.invoke(o1);

                    m = o2.getClass().getMethod(getKey);
                    Object o2Value = m.invoke(o2);

                    if(o1Value == null && o2Value == null) {
                        return 0;
                    }else if(o1Value == null && o2Value != null) {
                        return -1;
                    }else if(o1Value != null && o2Value == null) {
                        return 1;
                    }

                    if("Integer".equals(fieldType.toString())) {
                        Integer _o1 = (Integer)o1Value;
                        Integer _o2 = (Integer)o2Value;
                        return _o1.compareTo(_o2);
                    }else if("String".equals(fieldType.toString())) {
                        String _o1 = (String)o1Value;
                        String _o2 = (String)o2Value;
                        return _o1.compareTo(_o2);
                    }else if("StringNumber".equals(fieldType.toString())) {
                        try{
                            Double _o1 = Double.valueOf(o1Value.toString());
                            Double _o2 = Double.valueOf(o2Value.toString());
                            return _o1.compareTo(_o2);
                        }catch (NumberFormatException ex) {
                            ex.printStackTrace();
                        }
                    }
                }catch (Exception e) {
                    e.printStackTrace();
                }
                return 0;
            }
        });
    }

    /**
     * 逻辑分页
     *
     * @param src
     *            源数据
     * @param start
     *            分页页数，1起始
     * @param size
     *            分页limit
     * @return 新的分页后的List
     * @throws Exception
     */
    public static <T> List<T> paginateList(List<T> src, int start, int size) {
        if(src == null) {
            return Collections.emptyList();
        }

        List<T> list = null;
        if(start <= 1) {
            start = 0;
        }else {
            start = (start-1) * size;
        }

        size = size + start;
        if (size > src.size()) {
            size = src.size();
        }

        try {
            list = src.subList(start, size);
        } catch (Exception e) {
            System.out.println("list.size:"+src.size()+"start:" + start + " , size" + size);
            e.printStackTrace();
        }
        return list;
    }


    /**
     * map.toString之后，转回map
     */
    public static Map<String,String> string2Map(String mapString) {
        Map<String,String> map = new LinkedHashMap<String,String>();
        try {
            if(StringUtils.isNotEmpty(mapString)) {
                String args = mapString.substring(1,mapString.length()-1);
                String[] argArr = args.split(", ");
                for (String entry : argArr) {
                    int index = entry.indexOf("=");
                    String key = entry.substring(0,index);
                    String value = entry.substring(index+1);
                    map.put(key, value);
                }
            }
        }catch (Exception ex) {
            ex.printStackTrace();
        }
        return map;
    }
}
