package com.friday.custody.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.util.CollectionUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Slf4j
public class StrUtil {
    //replace with secureRandom
    public static String getRandomStr(int targetStringLength) {
        int leftLimit = 48; // numeral '0'
        int rightLimit = 122; // letter 'z'
        return new Random().ints(leftLimit, rightLimit + 1)
                .filter(i -> (i <= 57 || i >= 65) && (i <= 90 || i >= 97))
                .limit(targetStringLength)
                .collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append)
                .toString();
    }

    //(存在且长度超过32位字符）截取前32位字符  若不存在，则在数据录入时生成32位随机（大/小写字母+数字）字符串
    public static String getSeqNo(String str) {
        return StringUtils.isNotBlank(str) ? str.length() > 32 ? str.substring(0, 32) : str : StrUtil.getRandomStr(32);
    }

    public static String getSeqNoWithoutNoRandom(Object obj) {
        if (obj == null) return null;
        String str = obj.toString();
        return StringUtils.isNotBlank(str) ? str.length() > 32 ? str.substring(0, 32) : str : null;
    }
    public static String subString(String str, int startIndex, int length) {
        return StringUtils.isNotBlank(str) ? str.length() > length ? str.substring(startIndex, length- startIndex - 1 ) : str : null;
    }

    public static String subString(String str,  int length) {
        return subString(str, 0, length);
    }

    public static String subString(String str) {
        return subString(str, 32);
    }

    public static String split(String originStr, String splitStr, int index) {
        if (StringUtils.isBlank(originStr)) {
            return null;
        }
        return  originStr.split(splitStr)[index];
    }

    public static List<String> getNumberList(String content){
        List<String> numList = new ArrayList<>();
        Pattern p = Pattern.compile("\\d{1,}");
        Matcher m = p.matcher(content);
        while(m.find()) {
            numList.add(m.group());
        }
        return numList;
    }

    /**
     * 根据提供的字符串和日期模板，找到日期并返回
     * @param target
     * @param pattern
     * @return
     */
    public static Date getDateFromStringByPattern(String target,String pattern){
        log.info("getDateFromStringByPattern入参target={}，pattern={}",target,pattern);

        if(StringUtils.isBlank(pattern)){
            log.error("getDateFromStringByPattern pattern为空");
            return null;
        }

        List<String> numberList = getNumberList(target);
        if(CollectionUtils.isEmpty(numberList)){
            log.error("getDateFromStringByPattern 没有数字");
            return null;
        }
        for (String s : numberList) {
            if(pattern.length() != s.length()){
                continue;
            }
            try{
                SimpleDateFormat sdf = new SimpleDateFormat(pattern);
                Date parse = sdf.parse(s);
                Date now = new Date();
                long l = now.getTime() - parse.getTime();
                //100年前、100年后的估计不对吧,太离谱的日期不要
                if(l<-3153600000000L || l> 3153600000000L){
                    continue;
                }
                return parse;
            } catch (ParseException e) {
                e.printStackTrace();
            }

        }
        log.error("getDateFromStringByPattern未找到匹配的日期信息");
        return null;
    }

    public static String getDateStrFromStringByPattern(String target,String pattern){
        Date dateFromStringByPattern = getDateFromStringByPattern(target, pattern);
        if (dateFromStringByPattern == null) {
            return null;
        }
        String format = new SimpleDateFormat(pattern).format(dateFromStringByPattern);
        return format;
    }


    /**
     * 判断中文字符串编码
     *
     * @param str
     * @return
     */
    public static String getEncoding(String str) {
        String encode = "GB2312";
        try {
            if (str.equals(new String(str.getBytes(encode), encode))) {
                String code = encode;
                return code;
            }
        } catch (Exception e) {
            log.error("编码查询异常:{}", e);
        }
        encode = "GBK";
        try {
            if (str.equals(new String(str.getBytes(encode), encode))) {
                String code1 = encode;
                return code1;
            }
        } catch (Exception e1) {
            log.error("编码查询异常:{}", e1);
        }
        encode = "ISO-8859-1";
        try {
            if (str.equals(new String(str.getBytes(encode), encode))) {
                String code2 = encode;
                return code2;
            }
        } catch (Exception e2) {
            log.error("编码查询异常:{}", e2);
        }
        encode = "UTF-8";
        try {
            if (str.equals(new String(str.getBytes(encode), encode))) {
                String code3 = encode;
                return code3;
            }
        } catch (Exception e3) {
            log.error("编码查询异常:{}", e3);
        }
        encode = "US-ASCII";
        try {
            if (str.equals(new String(str.getBytes(encode), encode))) {
                String code4 = encode;
                return code4;
            }
        } catch (Exception e4) {
            log.error("编码查询异常:{}", e4);
        }
        encode = "UTF-16";
        try {
            if (str.equals(new String(str.getBytes(encode), encode))) {
                String code5 = encode;
                return code5;
            }
        } catch (Exception e5) {
            log.error("编码查询异常:{}", e5);
        }
        return "";
    }
}
