package com.yunniu.farming.util;

import org.apache.commons.lang3.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * String 工具类
 * 简化其他方法中对string的一些操作
 */
public class StringHelper {
	/**
	 * 功能：判断参数是否合法
	 */
	public static boolean isValid(Object param){
		if(null == param) return false;
		if("".equals(param.toString())) return false;
		if("0".equals(param.toString())) return false;
		if("null".equals(param.toString())) return false;
		if("undefined".equals(param.toString())) return false;
		return true;
	}

	/**
	 * 功能：判断字符串是否为空
	 */
	public static boolean isEmpty(String str){
		if(null == str) return true;
		if("".equals(str)) return true;
		return false;
	}
	
	/**
	 * 功能：判断字符串是否为空
	 */
	public static boolean isNotEmpty(String str){
		if(null == str) return false;
		if("".equals(str)) return false;
		return true;
	}
	
	/**
	 * 功能：判断一个字符串是不是电话号码
	 */
	public static boolean isMobile(String str){
		Pattern p = Pattern.compile("^[1][3,4,5,6,7,8,9][0-9]{9}$"); // 验证手机号
		Matcher m = p.matcher(str);
		return m.matches();
	}
	
	/**
	 * @return
	 * 功能：在服务器端存储文件的时候，获取要保存的文件的地址
	 */
	public static String getSaveFilePath(String rootpath, MultipartFile file){
		return StringHelper.getSaveFilePath(rootpath, file.getOriginalFilename());
	}
	
	/**
	 * @return
	 * 功能：在服务器端存储文件的时候，获取要保存的文件的地址
	 */
	public static String getSaveFilePath(String rootpath, String filename){
		//rootpath = D:/web/source/articalimg/
		Date date = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM");
		//dir = D:/web/source/articalimg/image/月份文件夹/
		String dir = rootpath + "image/" + sdf.format(date) + "/";
		
		File f = new File(dir);
		if(!f.exists()) f.mkdirs();
		
		sdf = new SimpleDateFormat("yyyyMMdd-HHmmss-SSS");
		//以当前时间替换需上传文件的文件名
		filename = sdf.format(date)+filename.substring(filename.lastIndexOf("."));
		//返回保存地址
		//D:/web/source/articalimg/image/月份文件夹/以时间命名的文件
		return dir + filename;
	}
	
	
	/**
	 * @return 获取有效的用户名
	 * 根据文件路径或者文件名称获取文件后缀
	 */
	public static String getFileSuffix(String filename){
		return filename.substring( filename.lastIndexOf(".") );
	}
	
	public static String getUUID(){
		return UUID.randomUUID().toString().replace("-", "");
	}
	
	public static String getUUIDoutpath(String source){
		String suffix = "";
		if(StringHelper.isNotEmpty(source)) suffix = StringHelper.getFileSuffix(source);
		
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
		String str = sdf.format(new Date());
		return str.substring(0,4) + "/" + str.substring(4, 6) + "/" + str.substring(6, 8) + "/" + str + suffix;
	}

	public static String getUUIDoutpath(){
		return StringHelper.getUUIDoutpath("");
	}
	
	public static final String[] chars = new String[] { "a", "b", "c", "d", "e", "f",
        "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s",  
        "t", "u", "v", "w", "x", "y", "z", "0", "1", "2", "3", "4", "5",  
        "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H", "I",  
        "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V",  
        "W", "X", "Y", "Z" };
	public static String generateShortUuid() {
	    StringBuffer shortBuffer = new StringBuffer();
	    String uuid = UUID.randomUUID().toString().replace("-", "");
	    for (int i = 0; i < 8; i++) {
	        String str = uuid.substring(i * 4, i * 4 + 4);
	        int x = Integer.parseInt(str, 16);
	        shortBuffer.append(chars[x % 0x3E]);
	    }
	    return shortBuffer.toString();  
	}  	
	
	public static String generateShortUuid(int len) {
	    StringBuffer shortBuffer = new StringBuffer();
	    String uuid = UUID.randomUUID().toString().replace("-", "");
	    int tm = uuid.length()/len;
	    for (int i = 0; i < len; i++) {
	        String str = uuid.substring(i * tm, i * tm + tm);
	        int x = Integer.parseInt(str, 16);
	        shortBuffer.append(chars[x % 0x3E]);
	    }
	    return shortBuffer.toString();  
	}
	
	
	public static String[] useragents = null;
	static{
		useragents = new String[]{
				"Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_8; en-us) AppleWebKit/534.50 (KHTML, like Gecko) Version/5.1 Safari/534.50",
				"Mozilla/5.0 (Windows; U; Windows NT 6.1; en-us) AppleWebKit/534.50 (KHTML, like Gecko) Version/5.1 Safari/534.50",
				"Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0",
				"Mozilla/5.0 (Macintosh; Intel Mac OS X 10.6; rv:2.0.1) Gecko/20100101 Firefox/4.0.1",
				"Mozilla/5.0 (Windows NT 6.1; rv:2.0.1) Gecko/20100101 Firefox/4.0.1",		//Firefox 4.0.1 – Windows
				"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_0) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.56 Safari/535.11",	//Chrome 17.0 – MAC
				"Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Trident/4.0; SE 2.X MetaSr 1.0; SE 2.X MetaSr 1.0; .NET CLR 2.0.50727; SE 2.X MetaSr 1.0)",
				"Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; 360SE)",
				"Mozilla/5.0 (iPhone; U; CPU iPhone OS 4_3_3 like Mac OS X; en-us) AppleWebKit/533.17.9 (KHTML, like Gecko) Version/5.0.2 Mobile/8J2 Safari/6533.18.5",
				"Mozilla/5.0 (Linux; U; Android 2.3.7; en-us; Nexus One Build/FRF91) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1",
				"Opera/9.80 (Android 2.3.4; Linux; Opera Mobi/build-1107180945; U; en-GB) Presto/2.8.149 Version/11.10",
				"UCWEB7.0.2.37/28/999"
		};
	}
	public static String getRandUserAgent(){
		int index = (new Random()).nextInt(useragents.length);
		return useragents[index];
	}
	
	
	/**
	 * @param str
	 * @param charset	编码：utf-8， gbk
	 * @return
	 * @throws Exception
	 * URL编码
	 */
	public static String urlencode(String str, String charset) throws Exception {
		 String nameStr = new String(java.net.URLEncoder.encode(str, charset).getBytes());
		 return nameStr;
	}
	
	/**
	 * @param str
	 * @param charset
	 * @throws Exception
	 * URL解码
	 */
	public static String urldecode(String str, String charset) throws Exception {
		String nameStr = java.net.URLDecoder.decode(new String(str.getBytes("ISO-8859-1"), "UTF-8"), "UTF-8");
		return nameStr;
	}
	
	/**
	 * @param num	 分子
	 * @param total	 分母
	 * @param len	小数点后保留位数
	 * @return	百分比格式字符串
	 */
	public static String getPrecentage(String num, String total, int len){
		return StringHelper.getPrecentage(Float.parseFloat(num), Float.parseFloat(total), len);
	}
	
	public static String getPrecentage(int num, int total, int len){
		return StringHelper.getPrecentage(num*0.1, total*0.1, len);
	}
	
	public static String getPrecentage(double num, double total, int len){
		String format = "0%";
		if(len > 0){
			format = "0.";
			for(int i=0; i<len; i++) format += "0";
			format += "%";
		}
		if(total==0) return format;
		DecimalFormat df = new DecimalFormat(format);
		return df.format(num/total);
	}

	/**
	 * @param coll
	 * @功能：打印列表集合
	 */
	public static void printList(Collection<String> coll){
		if(coll==null || coll.size()==0) {
			//System.out.println("集合为空");
			return ;
		}
		for(String obj : coll){
			//System.out.println(obj.toString());
		}
	}
	
	/**
	 * 从带《》的字符串中提取gamename
	 */
	public static String getGamenameFromTitle(String title){
		if(!title.contains("《")) return "";
		if(!title.contains("》")) return "";
		title = title.substring(title.indexOf("《") + 1);
		title = title.substring(0, title.indexOf("》"));
		return title;
	}
	
	public static String getLengthStr(String str, int length) {
		if(isEmpty(str)) return null;
		if(str.length() <= length) return str;
		return str.substring(0, length - 1);
	}
	
	public static String removeStr(String target, String... strs){
		if(isEmpty(target)) return target;
		for(String str : strs) {
			target = target.replace(str, "");
		}
		return target;
	}
	
	/**
	 *  获取指定2个字符串之间的内容
	 */
	public static String getBetweenStr(String target, String begin, String end){
		if(!target.contains(begin)) return "";
		if(!target.contains(end)) return "";
		int indexBegin = target.indexOf(begin);
		target = target.substring(indexBegin + 1);
		int indexEnd = target.indexOf(end);
		target = target.substring(0, indexEnd);
		return target;
	}
	
	/**
	 * 获取 订单编号 201803011210150001
	 * @return
	 */
	public static String getOrderno() {
	    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSSS");
	    return sdf.format(new Date()) + getRandomNumberStr(4);
	}

	/**
	 * @功能 : 获取指定长度的随机数字组成字符串
	 */
	public static String getRandomNumberStr(int len){
	    Random rand = new Random();
	    String str = "";
	    for(int i=0; i<len; i++) {
	        str += rand.nextInt(10);
	    }
	    return str;
	}
	
	public static String toUTF8(String str) {
		try {
			return new String(str.getBytes("UTF-8"));
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * 将list转换成String，并且有分隔符
	 * @param list
	 * @param separator
	 * @return
	 */
	public static String listToString(List<String> list, char separator) {
		return StringUtils.join(list.toArray(),separator);    
	}
	
	public static String toGBK(String str) {
		try {
			return new String(str.getBytes("GBK"));
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			return str;
		}
	}

	
	public static void main(String[] args) throws Exception {
	}

}





