package com.ejweb.core.utils;

import java.io.File;
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.ejweb.conf.GConstants;

public class Util {

    /**
     * 获取上传文件的绝对地址
     * 
     * @author renmb
     * @time  2017年4月14日
     * @param moduleName
     * @param extesionName
     * @param uploadFileName
     * @return
     */
    public static File buildPhysicalPath(String moduleName, String uploadFileName) {
        
        String extesionName  = Util.getExtensionName(uploadFileName);
        File   baseUploadDir = Util.buildBaseUploadDir(moduleName, extesionName);
        File   physicalPath  = new File(baseUploadDir, uploadFileName);
        return physicalPath;
    }
    /**
     * 获取基本理解名称
     * 
     * @author renmb
     * @time  2017年4月14日
     * @param moduleName
     * @param extesionName
     * @return
     */
    public static File buildBaseUploadDir(String moduleName, String extesionName) {
        String baseDatePath = PathFormatUtils.parse(GConstants.PATH_FORMAt);//FORMAT.format(System.currentTimeMillis());
        String basePath     = moduleName+GConstants.FS+extesionName.replace(".", "")+GConstants.FS;
        // 上传文件基本地址
        File baseUploadDir = new File(GConstants.FILE_UPLOAD_DIR, baseDatePath+GConstants.FS+GConstants.FILE_IMAGE_ACTUALS+GConstants.FS+basePath);
        if(!baseUploadDir.exists()){// 如果文件夹不存在则创建
            baseUploadDir.mkdirs();
        }
        return baseUploadDir;
    }
//    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");
    public static String getAbsoluteUrl(String url, String want) {
        if(StringUtils.isBlank(url))
            return getAbsoluteUrl(want);
        if(url.startsWith("http://") || url.startsWith("https://"))// 绝对路径
            return url;
        if(GConstants.FILE_PREFIX_URL.endsWith("/") && url.startsWith("/"))// 相对路径
            return GConstants.FILE_PREFIX_URL+url.replaceAll("^/+", "");
        return GConstants.FILE_PREFIX_URL+url;
    }
    public static String getAbsoluteUrl(String url) {
        if(StringUtils.isBlank(url))
            return "";
        if(url.startsWith("http://") || url.startsWith("https://"))// 绝对路径
            return url;
        if(GConstants.FILE_PREFIX_URL.endsWith("/") && url.startsWith("/"))// 相对路径
            return GConstants.FILE_PREFIX_URL+url.replaceAll("^/+", "");
        return GConstants.FILE_PREFIX_URL+url;
    }
    public static Date getTodayDate(){
        
        try {
            SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd");
            String source = Util.getCurrentDate();
            return DATE_FORMAT.parse(source);
        } catch (Exception e) {
            // TODO: handle exception
        }
        return null;
    }
    public static Date parseDate(String source){
        
        if(source == null){
            return null;
        }
        try {
            if(source.length() == "yyyy-MM-dd".length()){
                SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd");
                return DATE_FORMAT.parse(source);
            } else if(source.length() == "yyyy-MM-dd HH:mm:ss".length()){
                SimpleDateFormat DATE_TIME_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                return DATE_TIME_FORMAT.parse(source);
            }
        } catch (Exception e) {
            // TODO: handle exception
        }
        return null;
    }
    
    /**
     * 获取文件的扩展名称
     * @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 String getCurrentDate(){
        SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd");
        return DATE_FORMAT.format(System.currentTimeMillis());
    }
    /**
     * 
     * 获取当前日志yyyy-MM-dd HH:mm:ss
     * @return
     */
    public static String getCurrentDatetime(){
        SimpleDateFormat DATE_TIME_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        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;
    }
    
    /**
     * 生成稳健的随机数
     * @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;
    }
    /**
     * 格式化座机号
     * 
     * @author renmb
     * @time  2016年12月12日
     * @param workPhone
     * @return
     */
    public static String formatedWorkPhone(String workPhone){
        if(workPhone == null || workPhone.length() == 0)
            return workPhone;
        try {
            workPhone = workPhone.replaceAll("[^\\d|+]+", "");
            if(workPhone.matches("0+")){ // 非座机号设置为空
                workPhone = "";
            } else if(workPhone.startsWith("0") == false){ // 非0开头的号码需要处理
                if(workPhone.startsWith("1") && workPhone.length() == 11){// 非座机号，是手机号，将号码处理为空
                    
                    workPhone = "";
                }
            }
            if(workPhone.startsWith("+") == false){// 去掉电话号码中间的加号
                
                workPhone = workPhone.replace("+", "");
            }
            if(workPhone.startsWith("0106961")){// 1、010 6961 xxxx    -> xxxx              内部号码，直接拨短号
                
                workPhone = workPhone.replace("0106961", "");
            } else if(workPhone.startsWith("06961")){// 2、06961 xxxx    -> xxxx              内部号码，直接拨短号
                
                workPhone = workPhone.replace("06961", "");
            } else if(workPhone.startsWith("6961")){// 2、6961 xxxx    -> xxxx              内部号码，直接拨短号
                
                workPhone = workPhone.replace("6961", "");
            } else if(workPhone.startsWith("010")){// 3、010 xxxx xxxx    -> 0 xxxx xxxx       北京号码，去掉区号，加拨0
                
                workPhone = workPhone.replace("010", "0");
            } else if(workPhone.startsWith("+")){// 4、+ xxxx xxxx    -> 000 xxxx xxxx       北京号码，去掉+号，加拨000
                
                workPhone = workPhone.replace("+", "000");
            } else {// 5、xxx xxxx xxxx    -> 0 xxx xxxx xxxx   国内非北京号码，加拨0
                
                workPhone = "0"+workPhone;
            }
            return workPhone;
        } catch (Exception e) {
            // TODO: handle exception
        }
        return workPhone;
    }
//    public static void main(String[] args){
//        System.out.println(Util.buildPhysicalPath("image", "af.png"));
//    }
}
