package com.palmnest.application.core.util;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.InetAddress;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.net.UnknownHostException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.DecimalFormat;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.Formatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

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

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;
import org.jsoup.Jsoup;
import org.jsoup.select.Elements;

import cn.superdesk.libs.common.json.JsonUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.esotericsoftware.minlog.Log;
import com.palmnest.application.Constants;
import com.palmnest.service.wechat.impl.WeChatAccessManagerImpl;

public class StringUtil {

	private static Logger LOG = Logger.getLogger(StringUtil.class);

	/**
	 * 判断两个不为空字符串是否相等
	 *
	 * @param target
	 * @param source
	 * @return
	 */
	public static boolean isEqual(String target, String source) {

		if (null == target || null == source) {
			return false;
		}

		return target.trim().equalsIgnoreCase(source.trim());
	}

	public static boolean isValidString(String strValue) {
		if (strValue == null || strValue.equals("")
				|| strValue.equalsIgnoreCase("NULL")) {
			return false;
		}
		return true;
	}

//	/**
//	 * @param developId 当前开发者ID
//	 * @param timestamp 时间戳
//	 * @param noncestr  随机字符串
//	 * @param url       当前网页的URL
//	 * @return
//	 */
//	public static String wxSignature_JS(String developId, String noncestr,
//										String timestamp, String url) {
//		String jsapi_ticket = Constants.CacheMap.get("jsapi_" + developId);
//		if (StringUtils.isBlank(jsapi_ticket)) {
//			jsapi_ticket = new WeChatAccessManagerImpl().getJsApiTicket(developId);
//		}
//		Map<String, String> ret = sign(jsapi_ticket, url, noncestr, timestamp);
//		return ret.get("signature");
//	}

	public static Map<String, String> sign(String jsapi_ticket, String url,
										   String nonce_str, String timestamp) {
		Map<String, String> ret = new HashMap<String, String>();
		String string1;
		String signature = "";
		// 注意这里参数名必须全部小写，且必须有序
		/* string1 = "jsapi_ticket=" + jsapi_ticket + "&noncestr=" + nonce_str +
		 * "&timestamp=" + timestamp + "&url=" + url;
		 * System.out.println(string1);
		 */
		String[] paramArr = new String[]{"jsapi_ticket=" + jsapi_ticket,
				"timestamp=" + timestamp, "noncestr=" + nonce_str, "url=" + url};
		Arrays.sort(paramArr);
		// 将排序后的结果拼接成一个字符串
		string1 = paramArr[0].concat("&" + paramArr[1])
				.concat("&" + paramArr[2]).concat("&" + paramArr[3]);
		LOG.info("string1:" + string1);
		try {
			MessageDigest crypt = MessageDigest.getInstance("SHA-1");
			crypt.reset();
			crypt.update(string1.getBytes("UTF-8"));
			signature = byteToHex(crypt.digest());

			LOG.info("signature:" + signature);
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}

		ret.put("url", url);
		ret.put("jsapi_ticket", jsapi_ticket);
		ret.put("nonceStr", nonce_str);
		ret.put("timestamp", timestamp);
		ret.put("signature", signature);
		return ret;
	}

	public static String byteToHex(final byte[] hash) {
		Formatter formatter = new Formatter();
		for (byte b : hash) {
			formatter.format("%02x", b);
		}
		String result = formatter.toString();
		formatter.close();
		return result;
	}

	public static String create_nonce_str() {
		return UUID.randomUUID().toString();
	}

	public static String create_timestamp() {
		return Long.toString(System.currentTimeMillis() / 1000);
	}

	public static String toShortStr(int maxlen, String targetStr) {
		String shortStr = targetStr;
		if (StringUtils.isNotEmpty(targetStr)) {
			if (targetStr.length() > maxlen) {
				shortStr = targetStr.substring(0, maxlen) + "...";
			}
		}
		return shortStr;
	}

	public static String getPercent(int x, int total) {
		String result = "";// 接受百分比的值
		double x_double = x * 1.0;
		double tempresult = x_double / total;
		// NumberFormat nf = NumberFormat.getPercentInstance(); 注释掉的也是一种方法
		// nf.setMinimumFractionDigits( 2 ); 保留到小数点后几位
		DecimalFormat df1 = new DecimalFormat("0.00%"); // ##.00%
		// 百分比格式，后面不足2位的用0补齐
		// result=nf.format(tempresult);
		result = df1.format(tempresult);
		return result;
	}

	/**
	 * 客户端请求MD5加密
	 *
	 * @param imei      设备串
	 * @param appkey    秘钥
	 * @param timestamp 时间戳
	 * @return
	 */
	public static String getSgin(String imei, String appkey, String timestamp) {
		String strCore = imei + "&" + appkey + "&" + timestamp;
		return DigestUtils.md5Hex(strCore);
	}

	/**
	 * 过滤些特殊字符
	 *
	 * @param str
	 * @return
	 */
	public static String StringFilter(String str) {
		// 只允许字母和数字
		// String regEx = "[^a-zA-Z0-9]";
		// 清除掉所有特殊字符
		String regEx = "[`~!@#$%^&*()+=|{}':;',//[//].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]";
		Pattern p = Pattern.compile(regEx);
		Matcher m = p.matcher(str);
		String result = m.replaceAll("").trim();
		//System.out.println("result:"+result);
		return result;
	}

	/**
	 * 日期格式化
	 *
	 * @param time 分钟
	 * @return
	 */
	public static String formatTime(int time) {
		String timeStr = "";
		if (time > 0) {
			if (time / (60 * 24) >= 1) {
				timeStr += ((int) (time / (60 * 24)) + "天");
			}
			if ((int) ((time % (60 * 24)) / 60) > 0) {
				timeStr += ((int) ((time % (60 * 24)) / 60)) + "小时";
			}
			if ((time % 60) > 0) {
				timeStr += ((int) (time % 60)) + "分钟";
			}
		} else {
			timeStr = "";
		}
		return timeStr;
	}

	/**
	 * 格式化输出json,防止中文乱码
	 *
	 * @param json
	 * @param request
	 * @param response
	 */
	public static void charSet(JSONObject json, HttpServletRequest request, HttpServletResponse response) {
		try {
			request.setCharacterEncoding("utf-8");//这里不设置编码会有乱码
			response.setContentType("text/html;charset=utf-8");
			response.setHeader("Cache-Control", "no-cache");
			PrintWriter out = response.getWriter();  //输出中文，这一句一定要放到response.setContentType("text/html;charset=utf-8"),  response.setHeader("Cache-Control", "no-cache")后面，否则中文返回到页面是乱码
			out.print(json.toString());
			out.flush();
			out.close();
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	/**
	 * 格式化输出参数
	 *
	 * @param map
	 * @return
	 */
	public static String paramStr(Map<String, String> map) {
		StringBuffer sbf = new StringBuffer();
		StringBuffer paramStr = new StringBuffer();
		if (null != map && map.size() > 0) {
			for (String dataKey : map.keySet()) {
				if (!dataKey.equals("sign")) {
					sbf.append(dataKey + map.get(dataKey) + ",");
				}
			}
			String sbStr = sbf.toString().substring(0, sbf.length() - 1);
			String[] sort = sbStr.split(",");
			Arrays.sort(sort);

			for (String str : sort) {
				paramStr.append(str);
			}
		}
		return paramStr.toString();
	}

	/**
	 * 输出静态字符串
	 *
	 * @param str
	 * @param request
	 * @param response
	 */
	public static void outJsonp(HttpServletRequest request, HttpServletResponse response, String str) {
		response.setCharacterEncoding("UTF-8");
		response.setContentType("application/json");
		try {
			String callback = request.getParameter("callback");
			if (StringUtils.isEmpty(callback)) {
				PrintWriter out = response.getWriter();
				out.write(str);
				out.close();
			} else {
				String json = callback + "('" + str + "')";
				PrintWriter out = response.getWriter();
				out.write(json);
				out.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
//	public static void main(String[] args) {
//		//System.out.println(getPercent(2010, 7600));
//		/*String redirectUrl = "http%3a%2f%2fwx.palmnest.com%2fsuper_reception%2fwechat%2ffrontSecurity%2fauth%3fredirectUrl%3d%2fwechat%2fappUser%2fredirectSingleServerKey%26serviceCode%3d1";
//		try {
//			System.out.println(java.net.URLEncoder.(redirectUrl,"utf-8"));
//		} catch (UnsupportedEncodingException e) {
//			e.printStackTrace();
//		}*/
//		
////		Pattern pattern = Pattern.compile("^-?(?:\\d+|\\d{1,3}(?:,\\d{3})+)(?:\\.\\d+)?$");
////		Matcher m = pattern.matcher("-1.1");
////		System.out.println(m.matches());
//		StringBuilder sql=new StringBuilder("");
//		sql.append("  INSERT INTO `tr_app_role_function` (`ROLEID`, `FUNCTION_ID`, `OPERATE_STR`) VALUES ('-1', '360', NULL);   ");
//		String s=sql.toString();
//		//项目
//		int [] str={9110,9114,9118,9119,9120,9121,9132,9133,9134,9135,9136,9137,9138,9143,9150,9162,9163,9164,9165,9166,9167,9168,9169,9170,9171,9172,9173,9174,9175,9176,9177,9178,9179,9180,9184,9191,9192,9193,9195,9196,9202,9203,9211,9212,9213,9214,9215,9216,9217,9218,9219,9221,9224,9225,9227,9228,9229,9230,9231,9234,9235,9236,9237,9238,9239,9240,9241,9242,9243,9244,9245,9246,9247,9248,9249,9250,9251,9252,9253,9254,9255,9256,9257,9258,9259,9260,9261,9262,9263,9264,9265,9266,9267,9268,9269,9270,9271,9272,9273,9274,9275,9276,9277,9278,9279,9280,9281,9282,9283,9284,9285,9286,9287,9288,9289,9290,9291,9292,9293,9294,9295,9296,9297,9298,9299,9300,9301,9302,9303,9304,9305,9306,9307,9308,9309,9310,9311,9312,9313,9314,9315,9316,9317,9318,9319,9320,9321,9322,9323,9324,9325,9326,9327,9328,9329,9330,9331,9332,9333,9334,9335,9336,9337,9338,9339,9340,9341,9342,9343,9344,9345,9346,9347,9348,9349,9350,9351,9352,9353,9354,9355,9356,9357,9358,9359,9360,9361,9362,9363,9364,9365,9366,9367,9368,9369,9370,9371,9372,9373,9374,9375,9376,9377,9378,9379,9380,9381,9382,9383,9384,9385,9386,9387,9388,9389,9390,9391,9392,9393,9394,9395,9396,9397,9398,9399,9400,9401,9402,9403,9404,9405,9406,9407,9408,9409,9410,9411,9412,9413,9414,9415,9416,9417,9418,9419,9420,9421,9422,9423,9424,9425,9426,9427,9428,9429,9430,9431,9432,9433,9434,9435,9436,9437,9438,9439,9440,9441,9442,9443,9444,9445,9446,9447,9448,9449,9450,9451,9452,9453,9454,9455,9456,9457,9458,9459,9460,9461,9462,9463,9464,9465,9466,9467,9468,9469,9470,9471,9472,9473,9474,9475,9476,9477,9478,9479,9480,9481,9482,9483,9484,9485,9486,9487,9488,9489,9490,9491,9492,9493,9494,9495,9496,9497,9498,9499,9500,9501,9502,9503,9504,9505,9506,9507,9508,9509,9510,9511,9512,9513,9514,9515,9516,9517,9518,9519,9520,9521,9522,9523,9524,9525,9526,9527,9528,9529,9530,9531,9532,9533,9534,9535,9536,9537,9538,9539,9540,9541,9542,9543,9544,9545,9546,9547,9548,9549,9550,9551,9552,9553,9554,9555,9556,9557,9558,9559,9560,9561,9562,9563,9564,9565,9566,9567,9568,9569,9570,9571,9572,9573,9574,9575,9576,9577,9578,9579,9580,9581,9582,9583,9584,9585,9586,9587,9588,9589,9590,9591,9592,9593,9594,9595,9596,9597,9598,9599,9600,9601,9602,9603,9604,9605,9606,9607,9608,9609,9610,9611,9612,9613,9614,9615,9616,9617,9618,9619,9620,9621,9622,9623,9624,9625,9626,9627,9628,9629,9630,9631,9632,9633,9634,9635,9636,9637,9638,9639,9640,9641,9642,9643,9644,9645,9646,9647,9648,9649,9650,9651,9652,9653,9654,9655,9656,9657,9658,9659,9660,9661,9662,9663,9664,9665,9666,9667,9668,9669,9670,9671,9672,9673,9674,9675,9676,9677,9678,9679,9680,9681,9682,9683,9684,9685,9686,9687,9688,9689,9690,9691,9692,9693,9694,9695,9698,9699,9700,9702,9703,9706,9710};
////		int [] arr={133,145,148,147,146,152,140,142,125,126,123};
//		try {
//			System.setOut(new PrintStream(new File("E:/project/log.txt")));
//			for(int k=0;k<str.length;k++){
////				s=s.replaceAll("53", str[k]+"");
//				LOG.info(s.replaceAll("-1", str[k]+""));
//				System.out.println(s.replaceAll("-1", str[k]+""));
//			}
//		} catch (FileNotFoundException e) {
//			e.printStackTrace();
//		}
//		
//	}

	/**
	 * @param str
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	public static String getUTF_8(String str) {
		try {
			if (StringUtils.isEmpty(str)) {
				return str;
			}
			String decodeStr = URLDecoder.decode(str, "utf-8");
			return decodeStr;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return str;
	}


	/**
	 * 签名
	 *
	 * @return
	 */
	public static String commonParameters() {
		String timestamp = DateUtils.getTime(new Date(), "");// new
		// 构建待签名字符串：接口密码+时间戳+用户编号+时间戳+接口密码；
		String signaturePending = Constants.SIGN + timestamp + Constants.NAME + timestamp
				+ Constants.SIGN;
		// 32位 Md5加密
		String sign = md5(signaturePending).toUpperCase();
		return sign;
	}

	/**
	 * timestamp 时间戳 (yyyyMMddHHmmss)
	 * 签名
	 *
	 * @return
	 */
	public static String commonParameters(String timestamp) {
		// 构建待签名字符串：接口密码+时间戳+用户编号+时间戳+接口密码；
		String signaturePending = Constants.SIGN + timestamp + Constants.NAME + timestamp
				+ Constants.SIGN;
		// 32位 Md5加密
		String sign = md5(signaturePending).toUpperCase();
		return sign;
	}

	/**
	 * md5 32位
	 *
	 * @return
	 */
	public static String md5(String str) {
		StringBuffer buf = new StringBuffer("");
		try {
			MessageDigest md5 = MessageDigest.getInstance("MD5");
			md5.update((str).getBytes("UTF-8"));
			byte b[] = md5.digest();

			int i;

			for (int offset = 0; offset < b.length; offset++) {
				i = b[offset];
				if (i < 0) {
					i += 256;
				}
				if (i < 16) {
					buf.append("0");
				}
				buf.append(Integer.toHexString(i)).toString();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return buf.toString();
	}

	/**
	 * 得到手机号码的归属地与运营商
	 *
	 * @return
	 */
	public static Map<String, String> getMobileAddress(String mobile) {
		Map<String, String> map = new HashMap<String, String>();
		String url = "http://www.ip138.com:8080/search.asp?action=mobile&mobile=%s";
		url = String.format(url, mobile);
		org.jsoup.nodes.Document doc = null;
		try {
			doc = Jsoup.connect(url).get();
		} catch (IOException e) {
			e.printStackTrace();
		}

		Elements els = doc.getElementsByClass("tdc2");
		System.out.println("归属地：" + els.get(1).text());
		System.out.println("类型：" + els.get(2).text());
		map.put("address", els.get(1).text());
		map.put("carrieroperator", els.get(2).text());
		return map;
	}

	/**
	 * 得到手机号码的归属地与运营商--淘宝
	 *
	 * @return
	 */
	public static JSONObject getMobileAddressTaoBao(String mobile) {
		String url = "https://tcc.taobao.com/cc/json/mobile_tel_segment.htm";
		try {
			JSONObject json = HttpKit.getMobileAddress(url, mobile);
			return json;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	//多判断了"null"
	public static boolean isNotEmpty(String str) {

		if (StringUtils.isNotEmpty(str) && !"null".equalsIgnoreCase(str)) {
			return true;
		} else {
			return false;
		}
	}


	/**
	 * 参数名ASCII码从小到大排序
	 *
	 * @param paramMap
	 * @param apikey
	 * @return
	 */
	public static String sign(Map<String, String> paramMap, String apikey) {
		String sign = "";
		StringBuffer sbfStr = new StringBuffer("");
		List<String> list = new ArrayList<String>(paramMap.keySet());
		Collections.sort(list); //参数名ASCII码从小到大排序（字典序）
		for (String key : list) {
			sbfStr.append(key + "=" + paramMap.get(key) + "&");
		}
		String str = "";
		if (StringUtils.isNotEmpty(apikey)) {
			str = sbfStr.append("app_key=").append(apikey).toString();
		} else {
			str = sbfStr.toString().substring(0, sbfStr.length() - 1);
		}
		sign = DigestUtils.md5Hex(str.toString()).toUpperCase();
		LOG.info("sbfStr:" + sbfStr);
		LOG.info("sign:" + sign);
		return sign;
	}

	public static String getLocalIp(HttpServletRequest request) {
		String remoteAddr = request.getRemoteAddr();
		String forwarded = request.getHeader("X-Forwarded-For");
		String realIp = request.getHeader("X-Real-IP");

		String ip = null;
		if (realIp == null) {
			if (forwarded == null) {
				ip = remoteAddr;
			} else {
				ip = remoteAddr + "/" + forwarded.split(",")[0];
			}
		} else {
			if (realIp.equals(forwarded)) {
				ip = realIp;
			} else {
				if (forwarded != null) {
					forwarded = forwarded.split(",")[0];
				}
				ip = realIp + "/" + forwarded;
			}
		}
		return ip;
	}

	//获取用户真实ip
	public static String getIpAddr(HttpServletRequest request) {
		String ipAddress = null;
		ipAddress = request.getHeader("x-forwarded-for");
		if (ipAddress == null || ipAddress.length() == 0
				|| "unknown".equalsIgnoreCase(ipAddress)) {
			ipAddress = request.getHeader("Proxy-Client-IP");
		}
		if (ipAddress == null || ipAddress.length() == 0
				|| "unknown".equalsIgnoreCase(ipAddress)) {
			ipAddress = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ipAddress == null || ipAddress.length() == 0
				|| "unknown".equalsIgnoreCase(ipAddress)) {
			ipAddress = request.getRemoteAddr();
			if (ipAddress.equals("127.0.0.1") || ipAddress.equals("0:0:0:0:0:0:0:1")) {
				// 根据网卡取本机配置的IP
				InetAddress inet = null;
				try {
					inet = InetAddress.getLocalHost();
				} catch (UnknownHostException e) {
					e.printStackTrace();
				}
				ipAddress = inet.getHostAddress();
			}

		}

		// 对于通过多个代理的情况，第一个IP为客户端真实IP,多个IP按照','分割
		if (ipAddress != null && ipAddress.length() > 15) { // "***.***.***.***".length()
			if (ipAddress.indexOf(",") > 0) {
				ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));
			}
		}
		return ipAddress;
	}

	public static String xmlToJSON(String xml) {
		JSONObject obj = new JSONObject();
		try {
			InputStream is = new ByteArrayInputStream(xml.getBytes("utf-8"));
			SAXBuilder sb = new SAXBuilder();
			Document doc = sb.build(is);
			Element root = doc.getRootElement();
			Map map = iterateElement(root);
			obj.put(root.getName(), map);
			return obj.toString();
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}


	@SuppressWarnings({"unchecked", "rawtypes"})
	private static Map iterateElement(Element root) {
		List childrenList = root.getChildren();
		Element element = null;
		Map map = new HashMap();
		List list = null;
		for (int i = 0; i < childrenList.size(); i++) {
			list = new ArrayList();
			element = (Element) childrenList.get(i);
			if (element.getChildren().size() > 0) {
				if (root.getChildren(element.getName()).size() > 1) {
					if (map.containsKey(element.getName())) {
						list = (List) map.get(element.getName());
					}
					list.add(iterateElement(element));
					map.put(element.getName(), list);
				} else {
					map.put(element.getName(), iterateElement(element));
				}
			} else {
				if (root.getChildren(element.getName()).size() > 1) {
					if (map.containsKey(element.getName())) {
						list = (List) map.get(element.getName());
					}
					list.add(element.getTextTrim());
					map.put(element.getName(), list);
				} else {
					map.put(element.getName(), element.getTextTrim());
				}
			}
		}
		return map;
	}

	/**
	 * 根据时间生成订单号
	 *
	 * @param cday        时间
	 * @param orderPrefix 订单号前缀
	 * @return
	 */
	public static String getOrderId(String orderPrefix) {
		return UUID.randomUUID().toString().replace("-", "");
	}

	/**
	 * 根据订单号查询手机充值信息
	 *
	 * @param orderId   订单号
	 * @param ordertype 订单号类型 0-流量充值平台订单号；1-接入系统订单号。默认值为0
	 * @return
	 */
	public static String getRecharge(String orderId, String ordertype) {
		Map<String, String> mapQuery = new HashMap<String, String>();
		String timestamp = DateUtils.getTime(new Date(), "");
		mapQuery.put("name", Constants.NAME);
		mapQuery.put("timestamp", timestamp);
		mapQuery.put("sign", StringUtil.commonParameters(timestamp));
		mapQuery.put("version", Constants.VERSION);
		mapQuery.put("ordertype", ordertype);
		mapQuery.put("msgid", orderId);

		return HttpKit.httpRecharge(Constants.ASK_URL + "Query", mapQuery, Constants.POST);
	}

	/**
	 * 调用微信支付接口
	 *
	 * @param map
	 * @return
	 */
	public static String rechargePay(Map<String, String> map) {
		if (StringUtils.isEmpty(map.get("tradeType"))) {
			map.put("tradeType", "JSAPI");//JSAPI--公众号支付、NATIVE--原生扫码支付、APP--app支付，统一下单接口trade_type的传参可参考这里
		}
		map.put("IMEI", "0");
		map.put("SIGN", StringUtil.getSgin("0", map.get("appkey"), map.get("timeStamp")));
		String jsonStr = "";
		try {
			jsonStr = HttpKit.httpRecharge(map.get("palmpay"), map, "POST");
		} catch (Exception e) {
			LOG.error("rechargeSign occur error." + LogExceptionStackUtil.LogExceptionStack(e));
		}
		return jsonStr;
	}

	public static boolean isPhone(String phone) {
		Pattern p = Pattern.compile("^((13[0-9])|(15[^4,\\D])|(18[0,5-9]))\\d{8}$");
		Matcher m = p.matcher(phone);
		return m.matches();
	}

	/**
	 * 往数组里面插入数据
	 *
	 * @param arr
	 * @param str
	 * @return
	 */
	public static String[] insert(String[] arr, String str) {
		int size = arr.length;
		String[] tmp = new String[size + 1];
		System.arraycopy(arr, 0, tmp, 0, size);
		tmp[size] = str;
		return tmp;
	}

	public static String getDateString(int dateType, String date, String endDate, int type) {
		String dateString = "";
		if (1 == dateType) {//年
			dateString = date + "年";
		} else if (2 == dateType) {//季度
			dateString = date + "年" + endDate + "季度";
		} else if (3 == dateType && type == 1) {//月
			dateString = date + "月";
		} else if (3 == dateType && type == 2) {//月
			dateString = date + "年-" + endDate + "月";
		} else if (4 == dateType) {//周/日
			dateString = date + "至" + endDate;
		}
		return dateString;
	}


	public static List<String> getImgSrc(String htmlStr) {

		String img = "";

		Pattern p_image;

		Matcher m_image;

		List<String> pics = new ArrayList<String>();

		// String regEx_img = "<img.*src=(.*?)[^>]*?>"; //图片链接地址

		String regEx_img = "<img.*src\\s*=\\s*(.*?)[^>]*?>";

		p_image = Pattern.compile(regEx_img, Pattern.CASE_INSENSITIVE);

		m_image = p_image.matcher(htmlStr);

		while (m_image.find()) {

			img = img + "," + m_image.group();

			// Matcher m =

			// Pattern.compile("src=\"?(.*?)(\"|>|\\s+)").matcher(img); //匹配src

			Matcher m = Pattern.compile("src\\s*=\\s*\"?(.*?)(\"|>|\\s+)").matcher(img);

			while (m.find()) {

				pics.add(m.group(1));

			}

		}
		return pics;
	}
	
	public static boolean isContainChinese(String str) {
		 
		Pattern p = Pattern.compile("^[A-Fa-f0-9]+$");//16进制
//        Pattern p = Pattern.compile("[\u4e00-\u9fa5]");//中文
        Matcher m = p.matcher(str);
        if (m.find()) {
            return true;
        }
        return false;
    }


//	public static void main(String[] args) {
////		dateIsCurrentMonth("2021-04-12 00:00:00");
//		int total=10000;
//		int pageSize=1000;
//		int pageNo=(total-1)/pageSize+1;
//
//	}
//	
	public static Date StrToDate(String time, String parrten) {

        if (parrten == null || parrten.equals("")) {
            parrten = "yyyy-MM-dd";
        }
        SimpleDateFormat formatter = new SimpleDateFormat(parrten);
        ParsePosition pos = new ParsePosition(0);
        Date dt1 = formatter.parse(time, pos);
        return dt1;
    }
	
	 public static boolean  dateIsCurrentMonth(String date){

	        boolean dateIsCurrentMonth = false;

	        int yy_current=new Date().getYear();
	        int yy=StrToDate(date,"yyyy-MM-dd HH:mm:ss").getYear();
	        if(yy_current==yy){
	            dateIsCurrentMonth = true;
	            System.out.println("在本年");
	        }else{
	            dateIsCurrentMonth = false;
	            System.out.println("不在本年");
	            return  dateIsCurrentMonth;
	        }
	        int MM_current=new Date().getMonth()+1;
	        int mm=StrToDate(date,"yyyy-MM-dd HH:mm:ss").getMonth()+1;

	        if(MM_current==mm){
	            dateIsCurrentMonth = true;
	            System.out.println("在本月份");
	        }else{
	            dateIsCurrentMonth = false;
	            System.out.println("不在本月份");
	        }

	        return  dateIsCurrentMonth;
	    }
	
	
	public static List<String> indexStr(String str){
		String [] list=str.split(",");
		if(null != list){
			System.out.println(list.length);
		}
		List<String> strList=new ArrayList<String>();
		StringBuilder sb=new StringBuilder("");
		int l=list.length;
		for(int i=0;i<l;i++){
			sb.append(list[i]).append(",");
			if(0 != i && i%100==0){
				if(StringUtils.isNotBlank(sb.toString())){
                    strList.add(sb.toString().substring(0,sb.length()-1));
                    sb=new StringBuilder("");
                }
			}
			if(i == l-1){
				if(StringUtils.isNotBlank(sb.toString())){
					strList.add(sb.toString().substring(0,sb.length()-1));
				}
			}
		}
		return strList;
	}
	
	public static void main(String[] args) {
		StringBuilder sb=new StringBuilder("");
		for(int i=0;i<1000;i++){
			sb.append("number"+(i+1));
			sb.append(",");
		}
		String cards=sb.toString();
		if(StringUtils.isNotEmpty(cards)){
			cards=cards.substring(0,cards.length()-1);
		}
		System.out.println("cards:"+cards);
		List<String> list=indexStr(cards);
		int i=1;
		for(String str:list){
			System.out.println("str"+i+":"+str);
			i++;
		}
		
	}

}
