package com.ifish.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
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.Map;
import java.util.Random;

import org.springframework.web.multipart.MultipartFile;

import com.ifish.entity.LookReport;
import com.ifish.entity.ShopsInfo;
import com.ifish.entity.User;
import com.ifish.enums.Index1Enum;
import com.ifish.enums.Index2Enum;
import com.ifish.enums.Index3Enum;
import com.ifish.hibernate.Pagination;
import java.io.UnsupportedEncodingException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.type.JavaType;

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（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);
    }

    //返回时分秒的时间字符串
    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 {
            map.put("data", value);
        }
        return map;
    }

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

    /**
     * 生成看护报告页面
     *
     * @param title
     * @param base64
     * @return
     */
    public static LookReport getLookFile(ShopsInfo shopsInfo, User user, String index1, String index2, String index3, String suggestion, String pngName, String modelFile, String filePath) {
        LookReport lookReport = new LookReport();
        try {
            //根据时间得文件名
            Calendar calendar = Calendar.getInstance();
            String fileName = String.valueOf(calendar.getTimeInMillis());
            Date date = new Date();
            String time = format2(date);
            //读取模板文件
            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);

            String value1 = Index1Enum.getValue(index1);
            String value2 = Index2Enum.getValue(index2);
            String value3 = Index3Enum.getValue(index3);
            Integer totalIndex = Integer.valueOf(index1) + Integer.valueOf(index2) + Integer.valueOf(index3);
            Integer baifenbi = 99;
            if (totalIndex >= 0 && totalIndex <= 50) {
                //50%～70%
                baifenbi = getRandom(50, 70);
            } else if (totalIndex > 50 && totalIndex <= 80) {
                //71%～84%
                baifenbi = getRandom(71, 84);
            } else {
                //85％～99％
                baifenbi = getRandom(85, 99);
            }
            //替换掉模板中相应的地方
            templateContent = templateContent.replaceAll("###time###", time);
            templateContent = templateContent.replaceAll("###index1###", index1);
            templateContent = templateContent.replaceAll("###index2###", index2);
            templateContent = templateContent.replaceAll("###index3###", index3);
            templateContent = templateContent.replaceAll("###totalIndex###", totalIndex.toString());
            templateContent = templateContent.replaceAll("###baifenbi###", baifenbi.toString());
            templateContent = templateContent.replaceAll("###value1###", value1);
            templateContent = templateContent.replaceAll("###value2###", value2);
            templateContent = templateContent.replaceAll("###value3###", value3);
            templateContent = templateContent.replaceAll("###suggestion###", suggestion);
            templateContent = templateContent.replaceAll("###fileName###", pngName);
            templateContent = templateContent.replaceAll("###shopsName###", shopsInfo.getShopsName());
            templateContent = templateContent.replaceAll("###userImg###", user.getUserImg());
            templateContent = templateContent.replaceAll("###signature###", user.getSignature());
            //看护报告
            lookReport.setTimestamp(date);
            lookReport.setShareImg(pngName);
            lookReport.setIndex1(index1);
            lookReport.setIndex2(index2);
            lookReport.setIndex3(index3);
            lookReport.setSuggestion(suggestion);
            lookReport.setTotalIndex(totalIndex.toString());
            lookReport.setBaifenbi(baifenbi.toString());
            lookReport.setUserImg(user.getUserImg());
            lookReport.setShopsName(shopsInfo.getShopsName());
            lookReport.setSignature(user.getSignature());
            lookReport.setCreateTime(new Date());
            //html文件名
            fileName = fileName + ".html";
            lookReport.setHtmlName(fileName);
            //建立文件输出流
            FileOutputStream fileoutputstream = new FileOutputStream(filePath + fileName);
            byte tag_bytes[] = templateContent.getBytes();
            fileoutputstream.write(tag_bytes);
            fileoutputstream.close();
            return lookReport;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 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);
    }
}
