package cn.pluss.platform.util;

import cn.hutool.crypto.digest.MD5;
import org.apache.commons.lang3.StringUtils;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class StringUtil extends StringUtils {

    /**
     * 根据身份证号获取性别
     *
     * @param certNo 身份证号
     * @return 0 男；1 女
     */
    public static String getSexFromCertNo(String certNo) {
        String in17 = String.valueOf(certNo.charAt(16));
        int intIn17 = Integer.parseInt(in17);
        return (intIn17 % 2) >= 1 ? "0" : "1";
    }

    public static final String letterChar = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";

    public static String random6() {
        Random random = new Random();
        String result = "";
        for (int i = 0; i < 6; i++) {
            result += random.nextInt(10);
        }
        return result;
    }

    public static String random6V2() {
        return MD5.create().digestHex(UUID.randomUUID().toString()).substring(0, 6);
    }

    public static String random(int length) {
        Random random = new Random();
        String result = "";
        for (int i = 0; i < length; i++) {
            result += random.nextInt(10);
        }
        return result;
    }

    //生产随机8位userCode
    public static String genRandomNum() {
        int maxNum = 36;
        int i;
        int count = 0;
        char[] str = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K',
                'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W',
                'X', 'Y', 'Z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};
        StringBuffer pwd = new StringBuffer("");
        Random r = new Random();
        while (count < 8) {
            i = Math.abs(r.nextInt(maxNum));
            if (i >= 0 && i < str.length) {
                pwd.append(str[i]);
                count++;
            }
        }
        return pwd.toString();
    }

    //生成指定长度的随机数
    public static String genRandomNum(int length) {
        int maxNum = 36;
        int i;
        int count = 0;
        char[] str = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K',
                'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W',
                'X', 'Y', 'Z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};
        StringBuffer pwd = new StringBuffer("");
        Random r = new Random();
        while (count < length) {
            i = Math.abs(r.nextInt(maxNum));
            pwd.append(str[i]);
            count++;
        }
        return pwd.toString();
    }

    public static String genUuid(){
        return UUID.randomUUID().toString().replace("-","").toUpperCase(Locale.ROOT);
    }

    /**
     * 生成订单号
     *
     * @return
     */
    public static synchronized String getBillno() {
        StringBuilder billno = new StringBuilder();

        // 日期(格式:20080524)
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        billno.append(format.format(new Date()));
        return billno.toString();
    }

    public static boolean isEmpty(Object content) {
        if (content == null) {
            return true;
        }

        if (content instanceof String) {
            return "".equals(content);
        } else {
            return false;
        }
    }

    public static String replaceNonLegalChar(String str) {
        if (str == null) {
            return null;
        }

        str = str.replace("（", "(");
        str = str.replace("）", ")");
        str = str.replaceAll("\\s*", "");

        return str;
    }

    public static boolean isNotEmpty(Object content) {
        return !isEmpty(content);
    }


    /**
     * 计算分页数量
     *
     * @param count
     * @param pageSize
     * @return
     */
    public static int getPageCount(int count, int pageSize) {
        // TODO Auto-generated method stub
        int pageCount = 0;
        if (count == 0) {
            return 0;
        }

        // 页长不能为0
        if (pageSize == 0) {
            return -1;
        }

        if (count % pageSize == 0) {
            pageCount = count / pageSize;
        } else {
            pageCount = count / pageSize + 1;

        }
        return pageCount;

    }

    /**
     * 计算分页数量
     *
     * @param count
     * @param pageSize
     * @return
     */
    public static long getPageCount(long count, int pageSize) {
        // TODO Auto-generated method stub
        long pageCount = 0;
        if (count == 0) {
            return 0;
        }

        // 页长不能为0
        if (pageSize == 0) {
            return -1;
        }

        if (count % pageSize == 0) {
            pageCount = count / pageSize;
        } else {
            pageCount = count / pageSize + 1;

        }
        return pageCount;

    }

    public static boolean equals(String str1, String str2) {
        // TODO Auto-generated method stub
        return str1 == null ? str2 == null : str1.equals(str2);
    }

    /**
     * 返回一个定长的随机纯字母字符串(只包含大小写字母)
     *
     * @param length 随机字符串长度
     * @return 随机字符串
     */
    public static String generateMixStr(int length) {
        StringBuffer sb = new StringBuffer();
        Random random = new Random();
        for (int i = 0; i < length; i++) {
            sb.append(letterChar.charAt(random.nextInt(letterChar.length())));
        }
        return sb.toString();
    }


    /**
     * 返回日时分秒
     *
     * @param second
     * @return
     */
    public static String secondToTime(long second) {
        long days = second / 86400;//转换天数
        second = second % 86400;//剩余秒数
        long hours = second / 3600;//转换小时数
        second = second % 3600;//剩余秒数
        long minutes = second / 60;//转换分钟
        second = second % 60;//剩余秒数
        String min = minutes + "";
        if (minutes < 10) {
            min = "0" + minutes;
        }
        String sec = second + "";
        if (second < 10) {
            sec = "0" + second;
        }

        if (0 < days) {
            return days + "";
        } else {
            return hours + "";
        }
    }

    public static double bigDecimal(Double d) {
        if (d == null) {
            return 0d;
        }
        return new BigDecimal(d).setScale(2, RoundingMode.HALF_UP).doubleValue();
    }

    public static double bigDecimal(Double d, RoundingMode roundingMode) {
        if (d == null) {
            return 0d;
        }
        return new BigDecimal(d).setScale(2, roundingMode).doubleValue();
    }

    public static String isHideMobile(String mobile) {
        if (mobile.length() == 11) {
            mobile = mobile.substring(0, 3) + "****" + mobile.substring(7);
        }
        return mobile;
    }

    public static boolean isNumber(String str) {
        String regex = "^([0-9]+(.[0-9]{1,2})?)|(-[0-9]+(.[0-9]{1,2})?)$";
        Pattern pattern = Pattern.compile(regex);
        Matcher match = pattern.matcher(str);
        // match.find()
        return match.matches();
    }

    /**
     * 隐藏隐私信息。
     *
     * @param param
     * @return
     */
    public static String hideSecret(String param) {
        int len = param.length();
        if (isContainChinese(param)) {
            String replaceValue = "**";
            if (param.length() == 2) {
                replaceValue = "*";
            }
            return param.replaceAll("(.{1})(.*)(.{0})", "$1" + replaceValue + "$3");
        }
        return param.replaceAll("(.{" + (len < 12 ? 3 : 6) + "})(.*)(.{4})", "$1" + "****" + "$3");
    }

    private static boolean isContainChinese(String str) {
        Pattern p = Pattern.compile("[\u4e00-\u9fa5]");
        Matcher m = p.matcher(str);
        if (m.find()) {
            return true;
        }
        return false;
    }

    public static String buildPostForm(String baseUrl, Map<String, String> parameters) {
        java.lang.StringBuffer sb = new StringBuffer();
        sb.append("<form name=\"punchout_form\" method=\"post\" action=\"");
        sb.append(baseUrl);
        sb.append("\">\n");
        sb.append(buildHiddenFields(parameters));
        sb.append("<input type=\"submit\" value=\"pay...\" style=\"display:none\" >\n");
        sb.append("</form>\n");
        sb.append("<script>document.forms[0].submit();</script>");
        java.lang.String form = sb.toString();
        return form;
    }

    public static String buildHiddenFields(Map<String, String> parameters) {
        if (parameters == null || parameters.isEmpty()) {
            return "";
        }
        java.lang.StringBuffer sb = new StringBuffer();
        Set<String> keys = parameters.keySet();
        for (String key : keys) {
            String value = parameters.get(key);
            // 除去参数中的空值
            if (key == null || value == null) {
                continue;
            }
            sb.append("<input type=\"hidden\" name=\"");
            sb.append(key);

            sb.append("\" value=\"");
            // 转义双引号
            String a = value.replace("\"", "&quot;");
            sb.append(a).append("\">\n");

        }
        return sb.toString();
    }

    /**
     * @param src
     * @param replaceSrc      需要替换的字符
     * @param replacementList 替换后的字符
     * @return
     */
    public static String replaceOneByOne(String src, String[] replaceSrc, String[] replacementList) {
        if (replaceSrc == null) {
            throw new IllegalArgumentException("replaceSrc 不能为空");
        }

        if (replacementList == null) {
            throw new IllegalArgumentException("replacementList 不能为空");
        }

        if (replaceSrc.length != replacementList.length) {
            throw new IllegalArgumentException("replaceSrc 和 replacementList的长度必须相等");
        }

        StringBuffer sb = new StringBuffer();

        int start = 0;

        if (replacementList.length == 0) {
            return src;
        }

        for (int i = 0; i < replaceSrc.length; i++) {
            int position = src.indexOf(replaceSrc[i], start);

            if (position == -1) {
                continue;
            }

            sb.append(src, start, position);
            sb.append(replacementList[i]);
            start = position + 1;
        }
        sb.append(src, start, src.length());

        return sb.toString();
    }

    /**
     * 密码校验
     * @param password
     * @return
     */
    public static String passwordCheck(String password){
        int length = password.length();
        if (length >= 7 && length <= 16){
            return password;
        }else {
            return null;
        }
    }

    /**
     * 金额校验
     * @param str
     * @return
     */
    public static boolean isMoney(String str) {
        // 判断小数点后2位的数字的正则表达式
        Pattern pattern = Pattern.compile("^(([1-9]{1}\\d*)|([0]{1}))(\\.(\\d){0,2})?$");
        Matcher match = pattern.matcher(str);
        return match.matches();
    }

}
