package com.bonus.boot.manager.manager.utils;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.sql.Blob;
import java.sql.SQLException;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class StringHelper {

    static final Logger log = LoggerFactory.getLogger(StringHelper.class);

    private static String hexString = "0123456789ABCDEF";

    public static String replaceAll(String str, String oldStr, String newStr) {
        return str.replaceAll(oldStr, newStr);
    }

    public static boolean contains(String s1, String s2) {
        if (isEmpty(s1)) {
            return false;
        }
        return s1.contains(s2);

    }

    public static void writeText(String args) {
        File fp = new File("F:\\1.txt");
        PrintWriter pfp;
        try {
            pfp = new PrintWriter(fp);
            pfp.print(args);
            pfp.close();
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

    /**
     * 集合转数组
     *
     * @param list
     * @param separator
     * @return
     */
    public static String listToString(List<String> list, char separator) {
        return StringUtils.join(list.toArray(), separator);
    }

    /**
     * blob中文乱码转码
     *
     * @param
     * @return
     */
    public static String blobToStrings(Blob b) {
        try {
            if (b == null) {
                return null;
            }
            String content = new String(b.getBytes((long) 1, (int) b.length()), "UTF-8");
            return content;
        } catch (SQLException | UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * blob中文乱码转码
     *
     * @param content
     * @return
     */
    public static String blobToString(String content) {
        try {
            return new String(content.getBytes("ISO_8859_1"), "UTF-8");
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return content;
    }

    /**
     * unicode转字符串
     *
     * @param unicode
     * @return
     */
    public static String unicodeToString(String unicode) {
        StringBuffer sb = new StringBuffer();
        String[] hex = unicode.split("\\\\u");
        for (int i = 1; i < hex.length; i++) {
            int index = Integer.parseInt(hex[i], 16);
            sb.append((char) index);
        }
        return sb.toString();
    }

    /**
     *      * 含有unicode 的字符串转一般字符串      * @param unicodeStr 混有 Unicode 的字符串
     *      * @return      
     */
    public static String unicodeStr2String(String unicodeStr) {
        int length = unicodeStr.length();
        int count = 0;
        // 正则匹配条件，可匹配“\\u”1到4位，一般是4位可直接使用 String regex = "\\\\u[a-f0-9A-F]{4}";
        String regex = "\\\\u[a-f0-9A-F]{1,4}";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(unicodeStr);
        StringBuffer sb = new StringBuffer();

        while (matcher.find()) {
            String oldChar = matcher.group();// 原本的Unicode字符
            String newChar = unicode2String(oldChar);// 转换为普通字符
            // int index = unicodeStr.indexOf(oldChar);
            // 在遇见重复出现的unicode代码的时候会造成从源字符串获取非unicode编码字符的时候截取索引越界等
            int index = matcher.start();
            sb.append(unicodeStr.substring(count, index));// 添加前面不是unicode的字符
            sb.append(newChar);// 添加转换后的字符
            count = index + oldChar.length();// 统计下标移动的位置
        }
        sb.append(unicodeStr.substring(count, length));// 添加末尾不是Unicode的字符
        return sb.toString();
    }

    /**
     * unicode 转字符串
     *
     * @param unicode 全为 Unicode 的字符串
     * @return
     */
    public static String unicode2String(String unicode) {
        StringBuffer string = new StringBuffer();
        String[] hex = unicode.split("\\\\u");

        for (int i = 1; i < hex.length; i++) {
            // 转换出每一个代码点
            int data = Integer.parseInt(hex[i], 16);
            // 追加成string
            string.append((char) data);
        }

        return string.toString();
    }

    /*
     * 将字符串编码成16进制数字,适用于所有字符（包括中文）
     */
    public static String encode(String str) {
        // 根据默认编码获取字节数组
        byte[] bytes = str.getBytes();
        StringBuilder sb = new StringBuilder(bytes.length * 2);
        // 将字节数组中每个字节拆解成2位16进制整数
        for (int i = 0; i < bytes.length; i++) {
            sb.append(hexString.charAt((bytes[i] & 0xf0) >> 4));
            sb.append(hexString.charAt((bytes[i] & 0x0f) >> 0));
        }
        return sb.toString();
    }

    public static String decode(String bytes) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream(bytes.length() / 2);
        // 将每2位16进制整数组装成一个字节
        for (int i = 0; i < bytes.length(); i += 2)
            baos.write((hexString.indexOf(bytes.charAt(i)) << 4 | hexString.indexOf(bytes.charAt(i + 1))));
        return new String(baos.toByteArray());
    }

    public static String fillPrefixZero(int v, int len) {
        String vStr = v + "";
        while (vStr.length() < len) {
            vStr = "0" + vStr;
        }
        return vStr;
    }

    public static boolean isEmpty(String str) {
        if (str == null || "" .equals(str.trim()) || "null".equals(str.trim())) {
            return true;
        }
        return false;
    }

    /**
     * 判断字符串 不为空
     */
    public static boolean isNotEmpty(String str) {
        return !isEmpty(str);
    }

	/**
	 * 判断是否是汉字数字
	 * @param str
	 * @return
	 */
	public static boolean isChineseNumber(String str) {
        String regex = "^[一二三四五六七八九十]+$";
        Pattern p = Pattern.compile(regex);
        Matcher m = p.matcher(str);
        if (m.matches()) {
            return true;
        } else {
			return false;
        }
    }
    /**
     * 判断是否是数字
     * @param str
     * @return
     */
    public static boolean isInteger(String str) {
        if(str == null || str == ""){
            return false;
        }
        Pattern pattern = Pattern.compile("^[-\\+]?[\\d]*$");
        return pattern.matcher(str).matches();
    }

    private static Pattern NUMBER_PATTERN = Pattern.compile("[0-9]+(\\.[0-9]+)?");

    /**
     * 判断字符串是否为全部为数字
     * @param str
     * @return
     */
    public static boolean StringIsNum(String str) {
        String bigStr;
        try {
            /** 先将str转成BigDecimal，然后在转成String */
            bigStr = new BigDecimal(str).toString();
        } catch (Exception e) {
            /** 如果转换数字失败，说明该str并非全部为数字 */
            return false;
        }
        Matcher isNum = NUMBER_PATTERN.matcher(str);
        if (!isNum.matches()) {
            return false;
        }
        return true;
    }

    //截取字符串之前的值
    public static String subStringfront(String str,String param){
        return str.substring(0, str.indexOf(param));
    }

    //截取字符串之后的值
    public static String subStringAfter(String str, String param){
        return str.substring(str.indexOf(param));
    }


    /**
     * 解析text/plain格式请求中的json
     *
     * @param request
     * @return
     */
    public static String fetchPostByTextPlain(HttpServletRequest request) {
        try {
            BufferedReader reader = request.getReader();
            char[] buf = new char[512];
            int len = 0;
            StringBuffer contentBuffer = new StringBuffer();
            while ((len = reader.read(buf)) != -1) {
                contentBuffer.append(buf, 0, len);
            }
            return contentBuffer.toString();

        } catch (IOException e) {
            e.printStackTrace();
            log.error("[获取request中用POST方式“Content-type”是“text/plain”发送的json数据]异常:{}", e.getCause());
        }
        return "";
    }

    /**
     * 根据身份证号判断性别
     * @param idNumber
     * @return
     */
    public static String judgeGender(String idNumber) throws IllegalArgumentException{
        System.out.println(idNumber.length());
        if(idNumber.length() != 18 && idNumber.length() != 15){
            throw new IllegalArgumentException("身份证号长度错误");
        }
        int gender = 0;
        if(idNumber.length() == 18){
            //如果身份证号18位，取身份证号倒数第二位
            char c = idNumber.charAt(idNumber.length() - 2);
            gender = Integer.parseInt(String.valueOf(c));
        }else{
            //如果身份证号15位，取身份证号最后一位
            char c = idNumber.charAt(idNumber.length() - 1);
            gender = Integer.parseInt(String.valueOf(c));
        }
        System.out.println("gender = " + gender);
        if(gender % 2 == 1){
            return "男";
        }else{
            return "女";
        }
    }


    /**
     * 根据身份证的号码算出当前身份证持有者的年龄
     *
     * @return
     */
    public static int countAge(String idNumber) {
        if(idNumber.length() != 18 && idNumber.length() != 15){
            throw new IllegalArgumentException("身份证号长度错误");
        }
        String year;
        String yue;
        String day;
        if(idNumber.length() == 18){
            year = idNumber.substring(6).substring(0, 4);// 得到年份
            yue = idNumber.substring(10).substring(0, 2);// 得到月份
            day = idNumber.substring(12).substring(0,2);//得到日
        }else{
            year = "19" + idNumber.substring(6, 8);// 年份
            yue = idNumber.substring(8, 10);// 月份
            day = idNumber.substring(10, 12);//日
        }
        Date date = new Date();// 得到当前的系统时间
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String fyear = format.format(date).substring(0, 4);// 当前年份
        String fyue = format.format(date).substring(5, 7);// 月份
        String fday=format.format(date).substring(8,10);//
        int age = 0;
        if(Integer.parseInt(yue) == Integer.parseInt(fyue)){//如果月份相同
            if(Integer.parseInt(day) <= Integer.parseInt(fday)){//说明已经过了生日或者今天是生日
                age = Integer.parseInt(fyear) - Integer.parseInt(year);
            } else {
                age = Integer.parseInt(fyear) - Integer.parseInt(year) - 1;
            }
        }else{

            if(Integer.parseInt(yue) < Integer.parseInt(fyue)){
                //如果当前月份大于出生月份
                age = Integer.parseInt(fyear) - Integer.parseInt(year);
            }else{
                //如果当前月份小于出生月份,说明生日还没过
                age = Integer.parseInt(fyear) - Integer.parseInt(year) - 1;
            }
        }
        System.out.println("age = " + age);
        return age;
    }

    public static boolean checkMobileIsOk(String mobile) {
        String regex = "^((13[0-9])|(14[5|7])|(15([0-3]|[5-9]))|(17[013678])|(18[0,5-9]))\\d{8}$";
        Pattern p = Pattern.compile(regex);
        Matcher m = p.matcher(mobile);
        boolean isMatch = m.matches();
        return isMatch;
    }
    //计算百分比
    public static String getPercent(double x,double y){
        double f=x*100/y;
        NumberFormat nf=NumberFormat.getNumberInstance();
        nf.setMinimumFractionDigits(2);
        nf.setRoundingMode(RoundingMode.HALF_UP);
        nf.setGroupingUsed(true);
        return nf.format(f)+"%";
    }
}
