/**
 * 
 */
package com.platomix.userprofile.utils;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import cn.hutool.core.date.DateUtil;

/**
 * @author wookvn
 *
 *	辅助工具类
 */
public class TagKit {

	final static Pattern FORMAT_PATTERN = Pattern.compile("\\$\\w*");
	final static Pattern SQL_FORMAT_PATTERN = Pattern.compile("\\$\\{\\w*\\}");
	
	/**
	 * 文本替换
	 * @param tplContent
	 * @param params
	 * @return
	 */
	public static String textMatchReplace(String tplContent, Map<String, ?> params) {
		if(params == null || params.isEmpty()) {
			return tplContent;
		}
		Matcher matcher = FORMAT_PATTERN.matcher(tplContent);
		while (matcher.find()) {
			String group = matcher.group();
			String key = group.substring(1, group.length());
			if (params.containsKey(key)) {
				tplContent = tplContent.replace(group, params.get(key).toString());
			}
		}
		return tplContent;
	}
	
	/**
	 * 
	 * @param tplContent
	 * @param params
	 * @return
	 */
	public static String sqlMatchReplace(String tplContent, Map<String, String> params) {
		Matcher matcher = SQL_FORMAT_PATTERN.matcher(tplContent);
		while (matcher.find()) {
			String group = matcher.group();
			String key = group.substring(2, group.length() - 1);
			if (params.containsKey(key)) {
				tplContent = tplContent.replace(group, params.get(key));
			}
		}
		return tplContent;
	}

	/**
	 * 获取临时表名
	 * @param tableName
	 * @param month
	 * @return
	 */
	public static String getTagTempTable(String tableName,String month){
		return tableName+"_"+month;
	}
	
	/**
	 * 判断给定的月份，是否属于当前月的2个月内
	 * @param month
	 * @return
	 */
	public static boolean isIntervalTwoMonthWithNow(String month) {
		long betweenMonth = DateUtil.betweenMonth(DateUtil.parse(month, "yyyyMM"), new Date(), true);
		return betweenMonth < 2;
	}
	
	public static void main(String[] args) {
		LocalDate monthDate = LocalDate.parse("202203"+"01", DateTimeFormatter.BASIC_ISO_DATE);
		LocalDate months = monthDate.plusMonths(1);
		System.out.println(DateUtil.format(months.atStartOfDay(), "yyyyMM"));
	}


}
