package com.yh.saas.plugin.news.util.thread;

import org.apache.commons.lang3.StringUtils;

import java.util.regex.Pattern;

public class ExcelCellAutoHeight {

	// 字母或字符
	private static final Pattern LETTER_PATTERN = Pattern.compile("^[A-Za-z0-9]+$");
	// 全角
	private static final Pattern SBC_CASE_PATTERN = Pattern.compile("[\u4e00-\u9fa5]+$");
	// 全角符号及中文
	private static final Pattern CHINESE_PATTERN = Pattern.compile("[^x00-xff]");

	/**
	 * POI获取高度
	 *
	 * @param str
	 * @param fontCountInline
	 * @return
	 */
	public static float getExcelCellAutoHeight(String str, float fontCountInline) {
		// 每一行的高度指定
		float defaultRowHeight = 15.00f;
		float defaultCount = 0.00f;
		if (StringUtils.isEmpty(str)) {
		} else {
			for (int i = 0; i < str.length(); i++) {
				float ff = getregex(str.substring(i, i + 1), fontCountInline);
				defaultCount = defaultCount + ff;
			}
		}
		if (defaultCount % fontCountInline > 0) {
			return ((int) (defaultCount / fontCountInline) + 1) * defaultRowHeight;// 计算
		} else {
			return (int) ((defaultCount / fontCountInline)) * defaultRowHeight;// 计算
		}
	}

	/**
	 * POI获取高度
	 *
	 * @param str
	 * @param fontCountInline
	 * @return
	 */
	public static float getExcelCellAutoHeight(String str, float fontCountInline, float defaultRowHeight) {

		float defaultCount = 0.00f;
		if (StringUtils.isEmpty(str)) {
		} else {
			for (int i = 0; i < str.length(); i++) {
				float ff = getregex(str.substring(i, i + 1), fontCountInline);
				defaultCount = defaultCount + ff;
			}
		}
		if (defaultCount % fontCountInline > 0) {
			return ((int) (defaultCount / fontCountInline) + 1) * defaultRowHeight;// 计算
		} else {
			return (int) ((defaultCount / fontCountInline)) * defaultRowHeight;// 计算
		}
	}

	/**
	 * poi获取单元格内容所需高度
	 *
	 * @param charStr
	 */
	public static float getregex(String charStr, float fontCountInline) {

		if ("\n".equals(charStr)) {
			return fontCountInline;
		}
		if (" ".equals(charStr)) {
			return 0.5f;
		}
		// 判断是否为字母或字符
		if (LETTER_PATTERN.matcher(charStr).matches()) {
			return 0.5f;
		}
		// 判断是否为全角
		if (SBC_CASE_PATTERN.matcher(charStr).matches()) {
			return 1.00f;
		}
		// 全角符号及中文
		if (CHINESE_PATTERN.matcher(charStr).matches()) {
			return 1.00f;
		}

		return 0.5f;

	}

	private ExcelCellAutoHeight() {
	}
}
