package com.nantian.cloud.jljc.tools;

import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
public class CharLengthUtil {
    /**
     * 获取字符串的长度，如果有中文，则每个中文字符计为2位
     * @param str
     * @param total 每行所占的字符数
     * @return
     */
    public static List<String> getCharLength(String str, int total){
        int strLength = 0;
        String chinese = "[\u0391-\uFFE5]";
        List<String> resultList = new ArrayList<>();
        Integer count = 0;
        int size = str.length();
        for (int i = 0; i < str.length(); i++) {
            //截取一个字符
            String temp = str.substring(i, i + 1);
            //判断是否是中文标点符号
            if (isChinesePunctuation(temp.charAt(0))){
                //word中标点符号不会出现在首位
                strLength += 2;
                //判断是否是中文标点符号
            }else if (temp.matches(chinese)){
                strLength += 2;
                //非中文字符
            }else{
                String tmpAgo = "";
                String tmpLatter = "";
                //判断当前字符前面是否是中文，如果是，则占一个中文字符位
                if (i > 0){
                    tmpAgo = str.substring(i - 1, i);
                }
                //判断当前字符后面时候是中文，如果是，则占一个中文字符位
                if (i + 1 < str.length()){
                    tmpLatter = str.substring(i,i+1);
                }
                if (tmpAgo.matches(chinese) && tmpLatter.matches(chinese)){
                    strLength += 3;
                }else if ((tmpAgo.matches(chinese) && !(tmpLatter.matches(chinese))) || (!(tmpAgo.matches(chinese)) && tmpLatter.matches(chinese))){
                    strLength += 2;
                }else {
                    strLength += 1;
                }
            }

            if (i == str.length() - 1){
                resultList.add(str.substring(count, size));
            }else{
                if (strLength >= total){
                    strLength = 0;
                    if (isChinesePunctuation(str.substring(i + 1, i + 2).charAt(0))){
                        resultList.add(str.substring(count,i + 2));
                        count = i + 2;
                    }else {
                        resultList.add(str.substring(count,i + 1));
                        count = i + 1;
                    }
                }
            }
        }
        return resultList;
    }

    /**
     * 判断是否是中文标点符号
     * @param c
     * @return
     */
    private static boolean isChinesePunctuation(char c){
        Character.UnicodeBlock ub = Character.UnicodeBlock.of(c);
        if (ub == Character.UnicodeBlock.GENERAL_PUNCTUATION
                || ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION
                || ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS
                || ub == Character.UnicodeBlock.CJK_COMPATIBILITY_FORMS
                || ub == Character.UnicodeBlock.VERTICAL_FORMS){
            return true;
        }else {
            return false;
        }
    }
}
