/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.ifish.util;

import com.ifish.bean.PageResult;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.lang3.StringUtils;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.type.JavaType;
import org.springframework.web.multipart.MultipartFile;

/**
 *
 * @author Administrator
 */
public class IfishUtil {

    private static final String formatDate = "yyyy-MM-dd HH:mm:ss";

    private static final String formatDate3 = "MM-dd HH:mm";

    private static final String formatDate2 = "yyyy-MM-dd HH:mm";

    private static final String formatDate1 = "yyyy-MM-dd";

    /**
     * 测试缓存时间：一分钟；单位：秒
     */
    public static final int CacheTime_Test_SECONDS = 60;
    /**
     * 缓存时间：一秒；单位：秒
     */
    public static final int CacheTime_SECONDS = 1;
    /**
     * 缓存时间：一分钟；单位：分
     */
    public static final int CacheTime_MINUTES = 1;
    /**
     * 缓存时间：一小时；单位：小时
     */
    public static final int CacheTime_HOURS = 1;
    /**
     * 缓存时间：一天；单位：天
     */
    public static final int CacheTime_DAYS = 1;

    /**
     * Object转Json
     */
    public static String ObjectToJson(Object value) {
        try {
            if (value == null) {
                return null;
            }
            ObjectMapper mapper = new ObjectMapper();
            String js = mapper.writeValueAsString(value);
            return js;
        } catch (Exception ex) {
            System.out.println("【异常信息】 >>> " + ex.toString());
            return "Error";
        }
    }

    /**
     * Json转Object（List）
     *
     * @param json 需要转换的JSON字符串
     * @param bean JavaBean,
     * @return 拿到结果需要强转一次，因为你拿到的是Object, 例如这样调用和强转： List&lt;School&gt; lst
     * =(List&lt;School&gt;)StringUtil.JsonToObjectList(value, School.class);
     */
    public static Object JsonToList(String json, Class<?> bean) throws Exception {
        ObjectMapper mapper = new ObjectMapper();
        JavaType javaType = mapper.getTypeFactory().constructParametricType(List.class, bean);
        return mapper.readValue(json, javaType);
    }

    /**
     * Json转Object（JavaBean）
     *
     * @param json 需要转换的JSON字符串
     * @param bean JavaBean,
     * @return 拿到结果需要强转一次，因为你拿到的是Object, 例如这样调用和强转： School lst
     * =(School)StringUtil.JsonToObjectList(value, School.class);
     */
    public static Object JsonToBean(String json, Class<?> bean) throws Exception {
        ObjectMapper mapper = new ObjectMapper();
        JavaType javaType = mapper.getTypeFactory().uncheckedSimpleType(bean);
        return mapper.readValue(json, javaType);
    }

    /**
     * 将json格式的字符串解析成Map对象
     */
    public static Map<String, Map<String, String>> JsonToMap(String json) {
        try {
            ObjectMapper mapper = new ObjectMapper();
            Map<String, Map<String, String>> maps = mapper.readValue(json, Map.class);
            return maps;
        } catch (Exception e) {
            System.out.println("【异常信息】 >>> " + e.toString());
            return null;
        }
    }

    public static Map<String, Map> JsonToMapContainMap(String json) {
        try {
            ObjectMapper mapper = new ObjectMapper();
            Map<String, Map> maps = mapper.readValue(json, Map.class);
            return maps;
        } catch (Exception e) {
            System.out.println("【异常信息】 >>> " + e.toString());
            return null;
        }
    }

    public static Map JsonToRealMap(String json) {
        try {
            ObjectMapper mapper = new ObjectMapper();
            Map maps = mapper.readValue(json, Map.class);
            return maps;
        } catch (Exception e) {
            System.out.println("【异常信息】 >>> " + e.toString());
            return null;
        }
    }

    /**
     * 返回分页数据
     *
     * @param str
     * @return
     */
    public static Object returnPageData(PageResult<?> page, String resultKey) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("result", resultKey);
        //实际的行数
        map.put("total", page.getTotalCount());
        //数据
        map.put("data", page.getList());
        return map;
    }

    //返回时分秒的时间字符串
    public static String TimestampToStringAndSecond(Object timestamp) {
        DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            return (format.format(timestamp));
        } catch (Exception e) {
            System.out.println("【isGaokaoYearExpire 异常】:" + e);
            return "";
        }
    }

    //返回时分秒的时间字符串
    public static String TimestampToStringAndSecond(Object timestamp, String geshi) {
        DateFormat format = new SimpleDateFormat(geshi);
        try {
            return (format.format(timestamp));
        } catch (Exception e) {
            System.out.println("【isGaokaoYearExpire 异常】:" + e);
            return "";
        }
    }

    /**
     * 返回当前日期yyyy-MM-dd
     *
     * @return
     * @throws ParseException
     */
    public static Date getCurDate() {
        DateFormat df = DateFormat.getDateInstance();
        try {
            return df.parse(df.format(new Date()));
        } catch (ParseException e) {
        }
        return null;
    }

    /**
     * 格式化日期yyyy-MM-dd HH:mm:ss
     *
     * @param date
     * @return
     */
    public static String format(Date date) {
        SimpleDateFormat format = new SimpleDateFormat(formatDate);
        return format.format(date);
    }

    /**
     * 格式化日期
     *
     * @param date
     * @return
     */
    public static String format1(Date date) {
        SimpleDateFormat format = new SimpleDateFormat(formatDate1);
        return format.format(date);
    }

    /**
     * 格式化日期
     *
     * @param date
     * @return
     */
    public static String format2(Date date) {
        SimpleDateFormat format = new SimpleDateFormat(formatDate2);
        return format.format(date);
    }

    /**
     * 格式化日期
     *
     * @param date
     * @return
     */
    public static String format3(Date date) {
        SimpleDateFormat format = new SimpleDateFormat(formatDate3);
        return format.format(date);
    }

    /**
     * 字符串转换成日期
     *
     * @param str
     * @return date
     */
    public static Date StrToDate(String str) {
        SimpleDateFormat format = new SimpleDateFormat(formatDate1);
        Date date = null;
        try {
            date = format.parse(str);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return date;
    }

    /**
     * 随机生成字母与数字组合
     *
     * @param length
     * @return
     */
    public static String getCharAndNumr(int length) {
        String val = "";
        Random random = new Random();
        for (int i = 0; i < length; i++) {
            // 输出字母还是数字
            String charOrNum = random.nextInt(2) % 2 == 0 ? "char" : "num";
            // 字符串
            if ("char".equalsIgnoreCase(charOrNum)) {
                // 取得大写字母还是小写字母
                int choice = random.nextInt(2) % 2 == 0 ? 65 : 97;
                val += (char) (choice + random.nextInt(26));
                // 数字
            } else if ("num".equalsIgnoreCase(charOrNum)) {
                val += String.valueOf(random.nextInt(10));
            }
        }
        return val;
    }

    /**
     * 返回json数据
     *
     * @param str
     * @return
     */
    public static Map<String, Object> returnJson(String key, Object value) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("result", key);
        if (value.equals("")) {
            map.put("data", null);
        } else {
            map.put("data", value);
        }
        return map;
    }

    /**
     * 返回json数据
     *
     * @param str
     * @return
     */
    public static Map<String, Object> toJson(String key, Object value) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("result", key);
        if (value.equals("")) {
            map.put("data", null);
        } else {
            if (value.getClass().equals(HashMap.class)) {
                Map map1 = (Map) value;
                if (map1.get("total") != null && StringUtils.isNotBlank(map1.get("total").toString())) {
                    map.put("total", map1.get("total"));
                    map1.remove("total");
                }
            }
            map.put("data", value);
        }
        return map;
    }

    /**
     * 上传图片文件
     *
     * @param fileUpload
     * @param path
     * @return
     */
    public static String uploadFile(MultipartFile fileUpload, String path) {
        //根据时间得文件名
        Calendar calendar = Calendar.getInstance();
        String fileName = String.valueOf(calendar.getTimeInMillis());
        //保存文件
        if (fileUpload == null) {
            return "base/default.png";
        }
        if (!fileUpload.isEmpty()) {
            try {
                if (!fileUpload.getOriginalFilename().equals("")) {
                    File picFile = new File(path, fileName + ".png");
                    //不存在则创建
                    if (!picFile.exists()) {
                        picFile.mkdirs();
                    }
                    //保存
                    fileUpload.transferTo(picFile);
                }
                return "share/" + fileName + ".png";
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
        return "";
    }

    /**
     * 生成微信分享页面
     *
     * @param title
     * @param base64
     * @return
     */
    public static String getHtmlFile(String title, String pngName, String modelFile, String filePath) {
        try {
            if (pngName != null && !pngName.equals("")) {
                //读取模板文件
                FileInputStream fileinputstream = new FileInputStream(filePath + modelFile);
                int lenght = fileinputstream.available();
                byte bytes[] = new byte[lenght];
                fileinputstream.read(bytes);
                fileinputstream.close();
                String templateContent = new String(bytes);
                //替换掉模板中相应的地方
                templateContent = templateContent.replaceAll("###title###", title);
                templateContent = templateContent.replaceAll("###fileName###", pngName);
                //根据时间得文件名
                Calendar calendar = Calendar.getInstance();
                String fileName = String.valueOf(calendar.getTimeInMillis());
                fileName = fileName + ".html";
                //建立文件输出流
                FileOutputStream fileoutputstream = new FileOutputStream(filePath + fileName);
                byte tag_bytes[] = templateContent.getBytes();
                fileoutputstream.write(tag_bytes);
                fileoutputstream.close();
                return fileName;
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return "";
    }

    /**
     * 随即区间整数
     *
     * @param min
     * @param max
     * @return
     */
    public static int getRandom(int min, int max) {
        int r = new Random().nextInt(max - min);
        return r + min;
    }

    /**
     * URL 解码
     *
     * @return String
     * @author lifq
     * @date 2015-3-17 下午04:09:51
     */
    public static String getURLDecoderString(String str) {
        String result = "";
        if (null == str) {
            return "";
        }
        try {
            result = java.net.URLDecoder.decode(str, "GBK");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * URL 转码
     *
     * @return String
     * @author lifq
     * @date 2015-3-17 下午04:10:28
     */
    public static String getURLEncoderString(String str) {
        String result = "";
        if (null == str) {
            return "";
        }
        try {
            result = java.net.URLEncoder.encode(str, "GBK");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 正则表达式截取字符串
     *
     * @param str
     * @param regex
     * @return
     */
    public static String regex(String str, String regex) {
        Matcher matcher = Pattern.compile(regex).matcher(str);
        if (matcher.find()) {
            return matcher.group(0);
        } else {
            return "";
        }
    }

    public static String regexToChinese(String str) {
        String regex = "([\\u4e00-\\u9fa5]+)";
        return regex(str, regex);
    }

    /**
     * 验证当前系统是windows(本地，返回true)，还是unix(服务器，返回false)
     *
     * @return
     */
    public static boolean IsWinOrUnix() {
        String os = System.getProperty("os.name");//获取当前操作系统
        return os.toLowerCase().startsWith("win");
    }

    public static String EncoderByMd5(String str) throws NoSuchAlgorithmException, UnsupportedEncodingException {

        byte[] bs = MessageDigest.getInstance("MD5").digest(str.getBytes());
        StringBuilder sb = new StringBuilder(40);
        for (byte x : bs) {
            if ((x & 0xff) >> 4 == 0) {
                sb.append("0").append(Integer.toHexString(x & 0xff));
            } else {
                sb.append(Integer.toHexString(x & 0xff));
            }
        }
        return sb.toString();
    }
}
