package com.fos.core.util;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

public class Util {

    private static final SimpleDateFormat DATE_TIME_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd");
    private static final SimpleDateFormat ORDER_TIME_FORMAT = new SimpleDateFormat("yyyyMMddHHmmss");
    
    /**
     * 获取文件的扩展名称
     * @param filename
     * @return
     */
    public static String getExtensionName(String filename) {
        if(filename == null || filename.length() == 0)
            return null;
        if(filename.contains(".")){
            String[] species = filename.split("\\.");
            return "."+species[species.length-1].toLowerCase();
        }
        return null;
    }
    
    public static Date getTodayDate() {

        try {
            String source = Util.getCurrentDate();
            return DATE_FORMAT.parse(source);
        } catch (Exception e) {
            // TODO: handle exception
        }
        return null;
    }
    
    public static String getOrderDate() {

        return ORDER_TIME_FORMAT.format(System.currentTimeMillis());
    }

    public static String getDate(String source) {
        if (source != null && source.length() != 0) {
            source = source.split(" ")[0];
            String string[] = source.split("-");
            String date = string[1] + "月" + string[2] + "日";
            return date;
        }
        return null;
    }

    public static Date parseDate(String source) {

        if (source == null) {
            return null;
        }
        try {
            if (source.length() == "yyyy-MM-dd".length()) {

                return DATE_FORMAT.parse(source);
            } else if (source.length() == "yyyy-MM-dd HH:mm:ss".length()) {

                return DATE_TIME_FORMAT.parse(source);
            }
        } catch (Exception e) {
            // TODO: handle exception
        }
        return null;
    }

    public static String getCurrentDate() {

        return DATE_FORMAT.format(System.currentTimeMillis());
    }
    
    /**
     * 比较与当前时间的前后
     */
    public static boolean isBeforeNow(Date expireDate){
        Date now = new Date();
        boolean flag = expireDate.before(now);
        return flag;
    }

    /**
     * 
     * 获取当前日志yyyy-MM-dd HH:mm:ss
     * 
     * @return
     */
    public static String getCurrentDatetime() {

        return DATE_TIME_FORMAT.format(System.currentTimeMillis());
    }

    /**
     * 生成唯一CODE
     * 
     * @return
     */
    public static String getGenericCode() {

        return DigestUtils.md5Hex(Util.getGenericUUID() + System.currentTimeMillis() + Util.getRandom(1000, 9999));
    }

    public static String getGenericUUID() {
        UUID uuid = UUID.randomUUID();
        // 得到对象产生的ID
        String a = uuid.toString();
        // 转换为大写
        a = a.toLowerCase();
        a = a.replaceAll("-", "");
        return a;
    }

    public static boolean isrContainValues(JSONArray data, String... values) {
        if (data == null || values == null)
            return false;
        int count = 0;
        int len = data.size();
        for (String val : values) {
            for (int j = 0; j < len; j++) {
                if (val != null && val.equals(data.getString(j))) {
                    count++;
                    if (count == values.length) {
                        return true;
                    }
                }
            }
        }
        return false;
    }

    public static boolean isPraramerValue(JSONObject data, String... colums) {
        if (data == null || colums == null)
            return false;
        for (String colum : colums) {
            if (data.containsKey(colum) == false) {
                return false;
            }
        }
        return true;
    }

    /**
     * 生成稳健的随机数
     * 
     * @param min
     * @param max
     * @return
     */
    public static int getRandom(int min, int max) {

        int randomNumber = (int) (Math.random() * (max - min + 3) + min);
        while (randomNumber == min || randomNumber == max + 2) {
            randomNumber = (int) (Math.random() * (max - min + 3) + min);
        }
        return randomNumber - 1;
    }

    public static double getRandom(double max) {

        double randomNumber = Math.random() * (max + 2);
        while (randomNumber >= max + 1) {
            randomNumber = Math.random() * (max + 2);
        }
        return randomNumber;
    }

    /**
     * 获取客户端真实IP地址
     * 
     * @param request
     * @return
     */
    public static String getOnlineIP(HttpServletRequest request) {
        // 获取X-Forwarded-For
        if (request == null)
            return "Unknown";
        String ip = request.getHeader("X-Real-IP");
        if (StringUtils.isBlank(ip) || "Unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("x-forwarded-for");
            if (StringUtils.isBlank(ip) || "Unknown".equalsIgnoreCase(ip)) {
                // 获取HTTP_CLIENT_IP
                ip = request.getHeader("Proxy-Client-IP");
                if (StringUtils.isBlank(ip) || "Unknown".equalsIgnoreCase(ip)) {
                    // HTTP_X_FORWARDED_FOR
                    ip = request.getHeader("WL-Proxy-Client-IP");
                    if (StringUtils.isBlank(ip) || "Unknown".equalsIgnoreCase(ip)) {
                        ip = request.getRemoteAddr();
                    }
                }
            }
        }
        if (StringUtils.isBlank(ip))
            return "Unknown";
        return ip.split(",")[0];
    }

    /**
     * 得到请求的根目录
     * 
     * @param request
     * @return
     */
    public static String getBasePath(HttpServletRequest request) {
        try {
            String path = request.getContextPath();
            String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
                    + path;
            basePath = basePath.trim().replaceAll("/+$", "");// 将结尾的反斜杠去掉
            return basePath;
        } catch (Exception e) {
            // TODO: handle exception
        }
        return null;
    }

    /**
     * 得到结构目录
     * 
     * @param request
     * @return
     */
    public static String getContextPath(HttpServletRequest request) {
        String path = request.getContextPath();
        return path;
    }

}
