package com.persagy.framework.util;

import java.io.IOException;
import java.io.InputStream;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.text.Collator;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Properties;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.persagy.core.constant.SystemConstant;
import com.persagy.core.mvc.pojo.BusinessObject;

/**
 * 通用工具类
 */
@SuppressWarnings({"unchecked","rawtypes"})
public class CommonToolUtils {
	private static final Logger log = Logger.getLogger(CommonToolUtils.class);
	
	private final static Collator CHINA_COLLATOR = Collator.getInstance(Locale.CHINA);

	/**
	 * 
	 *<p>Description:  获取初始配置文件信息.</p> 
	 *<p>@param objet
	 *<p>@return List<Map>
	 *@since 2018年4月16日: 下午2:39:05
	 *@author gezhanbin
	 *@version 1.0
	 */
	public static <T extends BusinessObject> List<Map> getInitFileInfo(T objet) {
		InputStream in = null;
		List<Map> list = null;
		try {
			in = CommonToolUtils.class.getResourceAsStream("/init/" + objet.getClass().getSimpleName() + ".json");
			list = SystemConstant.jsonMapper.readValue(in, List.class);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			log.error(e.getMessage());
			e.printStackTrace();
		} finally {
			if (in != null) {
				try {
					in.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		return list;
	}

	/**
	 * 
	 *<p>Description: 获取文件存储根节点路径 .</p> 
	 *<p>@return   返回文件存储根节点路径
	 *<p>@throws Exception String
	 *@since 2018年3月30日: 下午5:10:16
	 *@author gezhanbin
	 *@version 1.0
	 */
	public static String getFileStorageDictionary() throws Exception {
		String fileStorageDirectory = getProperty("file.storage.directory");
		return fileStorageDirectory;
	}
	
	/**
	 * Description: 获取配置文件/config/system.properties配置的信息
	 * @param key 配置属性key
	 * @return
	 * @throws Exception String
	 * @author cuixubin
	 * @since 2018年8月18日: 下午3:08:42
	 * Update By cuixubin 2018年8月18日: 下午3:08:42
	 */
	public static String getProperty(String key) throws Exception {
		Properties properties = new Properties();
		properties.load(CommonToolUtils.class.getResourceAsStream("/config/system.properties"));
		
		String value = properties.getProperty(key);
		return value;
	}
	
	/**
	 * 获取.properties配置文件配置的信息
	 * @param key 配置属性key 
	 * @param confFilePath 配置文件路径，如/config/system.properties
	 * @return
	 * @throws Exception String
	 */
	public static String getProperty(String key, String confFilePath) {
		Properties properties = new Properties();
		try {
			properties.load(CommonToolUtils.class.getResourceAsStream(confFilePath));
		} catch (Exception e) {
			log.error("读取配置文件：" + confFilePath + "出错！");
		}
		
		String value = properties.getProperty(key);
		return value;
	}
	
	/**
	 * 获取登录ip地址
	 * @return String
	 */
	public static String getIpAddr() {
		HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
		String 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.equals("127.0.0.1")) {
				// 根据网卡取本机配置的IP
				InetAddress inet = null;
				try {
					inet = InetAddress.getLocalHost();
				} catch (UnknownHostException e) {
					e.printStackTrace();
				}
				ip = inet.getHostAddress();
			}
		}
		// 对于通过多个代理的情况，第一个IP为客户端真实IP,多个IP按照','分割
		if (ip != null && ip.length() > 15) {
			if (ip.indexOf(",") > 0) {
				ip = ip.substring(0, ip.indexOf(","));
			}
		}
		return ip;
	}

	/**
	 * 获取登录ip地址
	 * @return String
	 */
	public static String getIpAddr(HttpServletRequest request) {
		String 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.equals("127.0.0.1")) {
				// 根据网卡取本机配置的IP
				InetAddress inet = null;
				try {
					inet = InetAddress.getLocalHost();
				} catch (UnknownHostException e) {
					e.printStackTrace();
				}
				ip = inet.getHostAddress();
			}
		}
		// 对于通过多个代理的情况，第一个IP为客户端真实IP,多个IP按照','分割
		if (ip != null && ip.length() > 15) {
			if (ip.indexOf(",") > 0) {
				ip = ip.substring(0, ip.indexOf(","));
			}
		}
		return ip;
	}


	/**
	 * 按名称进行中文升序排序
	 * @param srcList
	 * @param sortField
	 */
	public static void sortChineseList(List<Map<String, Object>> srcList, String sortField) {
		Collections.sort(srcList, new Comparator<Map>() {
			@Override
			public int compare(Map o1, Map o2) {
				String name1 = (String) o1.get(sortField);
				name1=name1==null?"":name1;
				String name2 = (String) o2.get(sortField);
				name2=name2==null?"":name2;
				return CHINA_COLLATOR.compare(name1, name2);
			}
		});
	}
	
	/**
	 * 按名称进行中文排序 
	 * @param srcList
	 * @param sortField
	 * @param isAsc true升序，false降序
	 */
	public static void sortChineseList(List srcList, String sortField, boolean isAsc) {
		Collections.sort(srcList, new Comparator<Map>() {
			@Override
			public int compare(Map o1, Map o2) {
				String name1 = (String) o1.get(sortField);
				name1=name1==null?"":name1;
				String name2 = (String) o2.get(sortField);
				name2=name2==null?"":name2;
				if(isAsc) {
					return CHINA_COLLATOR.compare(name1, name2);
				}else {
					return CHINA_COLLATOR.compare(name2, name1);
				}
			}
		});
	}
	
	/**
	 * 给list中的map对象进行升序排序
	 * @param srcList
	 * @param sortField
	 */
	public static void sortList(List srcList, String sortField) {
		Collections.sort(srcList, new Comparator<Map>() {
			@Override
			public int compare(Map o1, Map o2) {
				String name1 = (String) o1.get(sortField);
				name1=name1==null?"":name1;
				String name2 = (String) o2.get(sortField);
				name2=name2==null?"":name2;
				return name1.compareTo(name2);
			}
		});
	}
	
	/**
	 * 给list中的map对象进行升序排序
	 * @param srcList
	 * @param sortField
	 * @param isAsc true升序，false降序
	 */
	public static void sortList(List srcList, String sortField,boolean isAsc) {
		Collections.sort(srcList, new Comparator<Map>() {
			@Override
			public int compare(Map o1, Map o2) {
				String name1 = (String) o1.get(sortField);
				name1=name1==null?"":name1;
				String name2 = (String) o2.get(sortField);
				name2=name2==null?"":name2;
				if(isAsc) {
					return name1.compareTo(name2);
				}else {
					return name2.compareTo(name1);
				}
			}
		});
	}
	
	/**
	 * 获得32位的UUID
	 * @return
	 */
	public static String getUuid() {
    	String uuid = UUID.randomUUID().toString().replace("-","");
    	return uuid;
    }

	/**
	 * 根据传入的前缀生成主键
	 * @param prefix
	 * @return prefix+32位UUID
	 */
	public static String getRecordId(String prefix) {
		String recordId = "";
		if (StringUtils.isNotBlank(prefix)) {
			recordId = prefix;
		}
		recordId = recordId + getUuid();
		return recordId;
	}
	
}
