package org.fouram.core.util;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

public class Tools {
	public static final DecimalFormat df2 = new DecimalFormat("#0.00");// 2位小数

	public static int getRandomNum() {
		Random r = new Random();
		return r.nextInt(900000) + 100000;
	}

	/*
	 * 判断是否为整数
	 * 
	 * @param str 传入的字符串
	 * 
	 * @return 是整数返回true,否则返回false
	 */
	public static boolean isInteger(String str) {
		Pattern pattern = Pattern.compile("^[-\\+]?[\\d]*$");
		return pattern.matcher(str).matches();
	}

	public static String getPorjectPath() {
		String nowpath = "";
		nowpath = System.getProperty("user.dir") + "/";

		return nowpath;
	}

	public static boolean notEmpty(String s) {
		return (s != null) && (!"".equals(s)) && (!"null".equals(s));
	}

	public static boolean isEmpty(String s) {
		return (s == null) || ("".equals(s)) || ("null".equals(s));
	}

	public static String[] str2StrArray(String str, String splitRegex) {
		if (isEmpty(str)) {
			return null;
		}
		return str.split(splitRegex);
	}

	public static String[] str2StrArray(String str) {
		return str2StrArray(str, ",\\s*");
	}

	public static String date2Str(Date date) {
		return date2Str(date, "yyyy-MM-dd HH:mm:ss");
	}

	public static Date str2Date(String date) {
		if (notEmpty(date)) {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			try {
				return sdf.parse(date);
			} catch (ParseException e) {
				LoggerUtil.error(e);

				return new Date();
			}
		}
		return null;
	}

	public static String date2Str(Date date, String format) {
		if (date != null) {
			SimpleDateFormat sdf = new SimpleDateFormat(format);
			return sdf.format(date);
		}
		return "";
	}

	public static String getTimes(String StrDate) {
		String resultTimes = "";

		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		try {
			Date now = new Date();
			Date date = df.parse(StrDate);
			long times = now.getTime() - date.getTime();
			long day = times / 86400000L;
			long hour = times / 3600000L - day * 24L;
			long min = times / 60000L - day * 24L * 60L - hour * 60L;
			long sec = times / 1000L - day * 24L * 60L * 60L - hour * 60L * 60L - min * 60L;

			StringBuffer sb = new StringBuffer();

			if (hour > 0L)
				sb.append(hour + "小时前");
			else if (min > 0L)
				sb.append(min + "分钟前");
			else {
				sb.append(sec + "秒前");
			}

			resultTimes = sb.toString();
		} catch (ParseException e) {
			LoggerUtil.error(e);
		}

		return resultTimes;
	}

	public static void writeFile(String fileP, String content) {
		String filePath = String.valueOf(Thread.currentThread().getContextClassLoader().getResource("")) + "../../";
		filePath = (filePath.trim() + fileP.trim()).substring(6).trim();
		if (filePath.indexOf(":") != 1)
			filePath = File.separator + filePath;
		try {
			OutputStreamWriter write = new OutputStreamWriter(new FileOutputStream(filePath), "utf-8");
			BufferedWriter writer = new BufferedWriter(write);
			writer.write(content);
			writer.close();
		} catch (IOException e) {
			LoggerUtil.error(e);
		}
	}

	public static boolean checkEmail(String email) {
		boolean flag = false;
		try {
			String check = "^([a-z0-9A-Z]+[-|_|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
			Pattern regex = Pattern.compile(check);
			Matcher matcher = regex.matcher(email);
			flag = matcher.matches();
		} catch (Exception e) {
			flag = false;
		}
		return flag;
	}

	public static boolean checkMobileNumber(String mobileNumber) {
		boolean flag = false;
		try {
			Pattern regex = Pattern.compile("^1[3|4|5|6|7|8][0-9]\\d{8}$");
			// .compile("^(((13[0-9])|(15([0-3]|[5-9]))|(18[0,5-9]))\\d{8})|(0\\d{2}-\\d{8})|(0\\d{3}-\\d{7})$");
			Matcher matcher = regex.matcher(mobileNumber);
			flag = matcher.matches();
		} catch (Exception e) {
			flag = false;
		}
		return flag;
	}

	public static boolean checkKey(String paraname, String FKEY) {
		paraname = paraname == null ? "" : paraname;
		return MD5.md5(paraname + DateUtil.getDays() + ",fh,").equals(FKEY);
	}

	@SuppressWarnings("resource")
	public static String readTxtFile(String fileP) {
		try {
			String filePath = String.valueOf(Thread.currentThread().getContextClassLoader().getResource("")) + "../../";
			filePath = filePath.replaceAll("file:/", "");
			filePath = filePath.replaceAll("%20", " ");
			filePath = filePath.trim() + fileP.trim();
			if (filePath.indexOf(":") != 1) {
				filePath = File.separator + filePath;
			}
			String encoding = "utf-8";
			File file = new File(filePath);
			if ((file.isFile()) && (file.exists())) {
				InputStreamReader read = new InputStreamReader(new FileInputStream(file), encoding);
				BufferedReader bufferedReader = new BufferedReader(read);
				String lineTxt = null;
				if ((lineTxt = bufferedReader.readLine()) != null) {
					return lineTxt;
				}
				read.close();
			} else {
				// System.out.println("找不到指定的文件,查看此路径是否正确:" + filePath);
			}
		} catch (Exception e) {
			// System.out.println("读取文件内容出错");
		}
		return "";
	}

	public static String formatString(Object code) {
		if (code != null) {
			return code.toString();
		} else {
			return "";
		}
	}

	/**
	 * 获取double类型两位小数
	 * 
	 * @param number
	 * @return
	 */
	public static double getTwoDecimalFormat(double number) {
		return Double.valueOf(df2.format(number));
	}

	// 获取请求IP
	public static String getIpAddress(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.getHeader("HTTP_CLIENT_IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("HTTP_X_FORWARDED_FOR");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		return ip;
	}

	/**
	 * 获取订单编号
	 * 
	 * @return
	 */
	public static String getOrderno() {
		return new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date()) + getFiveRandom();
	}

	/**
	 * 获取随机5位数字
	 * 
	 * @return
	 */
	public static String getFiveRandom() {
		Random random = new Random();
		String fourRandom = random.nextInt(100000) + "";
		int randLength = fourRandom.length();
		if (randLength < 5) {
			for (int i = 1; i <= 5 - randLength; i++)
				fourRandom = "0" + fourRandom;
		}
		return fourRandom;
	}

	public static Object str2Bean(String text, Class<?> clazz) {
		return JSONObject.parseObject(text, clazz);
	}

	/**
	 * 获取格式化后的银行卡号码
	 * 
	 * @param cardNum
	 * @return
	 */
	public static String getBankCardNumFormat(String cardNum) {
		if (StringUtils.isNotBlank(cardNum)) {
			if (cardNum.length() == 19) {
				return cardNum.substring(0, 4) + " **** **** **** "
						+ cardNum.substring(cardNum.length() - 3, cardNum.length());
			} else if (cardNum.length() == 16) {
				return cardNum.substring(0, 4) + " **** **** "
						+ cardNum.substring(cardNum.length() - 4, cardNum.length());
			} else if (cardNum.length() > 8) {
				return cardNum.substring(0, 4) + " **** **** "
						+ cardNum.substring(cardNum.length() - 4, cardNum.length());
			} else {
				return cardNum;
			}
		}
		return cardNum;
	}

	/**
	 * 获取格式化后的身份证号码
	 * 
	 * @param cardId
	 * @return
	 */
	public static String getCardIdFormat(String cardId) {
		if (StringUtils.isNotBlank(cardId)) {
			if (cardId.length() == 18) {
				return cardId.substring(0, 3) + "************" + cardId.substring(cardId.length() - 3, cardId.length());
			} else if (cardId.length() > 6) {
				return cardId.substring(0, 3) + "************" + cardId.substring(cardId.length() - 3, cardId.length());
			} else {
				return cardId;
			}
		}
		return cardId;
	}

	/**
	 * 获取格式化后的手机号码
	 * 
	 * @param phone
	 * @return
	 */
	public static String getPhoneFormat(String phone) {
		if (StringUtils.isNotBlank(phone)) {
			if (phone.length() == 11) {
				return phone.substring(0, 3) + "****" + phone.substring(phone.length() - 4, phone.length());
			} else if (phone.length() > 7) {
				return phone.substring(0, 3) + "****" + phone.substring(phone.length() - 4, phone.length());
			} else {
				return phone;
			}
		}
		return phone;
	}

	public static void writeJson(HttpServletResponse response, Object object) {
		try {
			String json = JSON.toJSONStringWithDateFormat(object, "yyyy-MM-dd HH:mm:ss");
			response.setContentType("text/json;charset=utf-8");
			response.getWriter().write(json);
			response.getWriter().flush();
			response.getWriter().close();
		} catch (IOException e) {
			LoggerUtil.error(e);
		}
	}

	public static String filterEmoji(String source) {
		if (StringUtils.isNotBlank(source)) {
			return source.replaceAll("[\\ud800\\udc00-\\udbff\\udfff\\ud800-\\udfff]", "");
		} else {
			return source;
		}
	}

	/**
	 * URL编码（utf-8）
	 * 
	 * @param source
	 * @return
	 */
	public static String urlEncodeUTF8(String source) {
		String result = source;
		try {
			result = URLEncoder.encode(source, "utf-8");
		} catch (UnsupportedEncodingException e) {
			LoggerUtil.error(e);
		}
		return result;
	}

	public static void main(String[] args) {
		System.out.println("‭13888811166".length());
		System.out.println(formatPhone("‭13888811166"));
		System.out.println(formatPhone("‭13888811166").length());
	}

	public static String formatPhone(String str) {
		String phone = "";
		for (int i = 0; i < str.length(); i++) {
			if (NumberUtils.isNumber(String.valueOf(str.charAt(i)))) {
				phone += String.valueOf(str.charAt(i));
			}
		}
		return phone;
	}

	// 定义移动端请求的所有可能类型
	private final static String[] agent = { "Android", "iPhone", "iPod", "iPad", "Windows Phone", "MQQBrowser" };

	/**
	 * 判断User-Agent 是不是来自于手机
	 * 
	 * @param ua
	 * @return
	 */
	public static boolean checkAgentIsMobile(String ua) {
		boolean flag = false;
		if (!ua.contains("Windows NT") || (ua.contains("Windows NT") && ua.contains("compatible; MSIE 9.0;"))) {
			// 排除 苹果桌面系统
			if (!ua.contains("Windows NT") && !ua.contains("Macintosh")) {
				for (String item : agent) {
					if (ua.contains(item)) {
						flag = true;
						break;
					}
				}
			}
		}
		return flag;
	}

	public static boolean isWechat(String ua) {
		if (ua.indexOf("micromessenger") > -1) {
			return true;// 微信
		}
		return false;// 非微信手机浏览器
	}

	public static String returnStr(String s) {
		if ((s == null) || ("".equals(s)) || ("null".equals(s))) {
			return "";
		} else {
			return s;
		}
	}

	public static String returnStrNew(String s) {
		if ((s == null) || ("".equals(s)) || ("null".equals(s))) {
			return "";
		} else {
			return s.trim();
		}
	}

	public static boolean isRightTelehone(String telephone) {
		if (StringUtils.isNotBlank(telephone) && telephone.startsWith("1") && telephone.length() == 11) {
			return true;
		}
		return false;
	}
}