package cc.smtweb.biz.mztb.web.tool;

import cc.smtweb.framework.core.util.Consts;
import cc.smtweb.framework.core.util.NumberUtil;
import cc.smtweb.framework.core.util.StringUtil;
import cc.smtweb.system.bpm.util.UtilLogger;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;

import java.math.BigDecimal;
import java.sql.Date;
import java.sql.Timestamp;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created with IntelliJ IDEA.
 * User: AKhh
 * Date: 12-12-26 下午11:55
 * 基础工具类；
 */
@SuppressWarnings("UnusedDeclaration")
public class UtilPub {
    private static SimpleDateFormat dFormat = new SimpleDateFormat("yyyy-MM-dd");
    private static SimpleDateFormat tFormat = new SimpleDateFormat("HH:mm:ss");
    private static SimpleDateFormat dtFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    private static SimpleDateFormat dLFormat = new SimpleDateFormat("yyyyMMddHHmmss");
    private static SimpleDateFormat dLFormat2 = new SimpleDateFormat("yyyyMMdd");
    private static DecimalFormat df2Format = new DecimalFormat("###,###,###,###,##0.00");
    private static DecimalFormat df2 = new DecimalFormat("##############0.00");
    private static DecimalFormat df = new DecimalFormat("#.##");


    public static boolean isEmpty(String str) {
        return str == null || str.trim().length() == 0;
    }

    //判断 是否支持GBK
    public static boolean supportGBK(String str) {
        if (str == null) {
            return true;
        }
        try {
            return str.equals(new String(str.getBytes("gbk"), "gbk"));
        } catch (Exception e) {
            UtilLogger.error("判断【" + str + "】是否支持GBK时出现异常：" + e.getMessage());
            e.printStackTrace();
            return false;
        }
    }

    public static boolean isEmpty(Collection collection) {
        return collection == null || collection.size() == 0;
    }

    public static boolean isEmpty(Object[] o) {
        return o == null || o.length == 0;
    }

    public static boolean isEmptyStr(String str) {
        return str == null || str.trim().length() == 0 || "-".equals(str) || "-1".equals(str) || "null".equals(str);
    }

    //判断Id是否为空id,有可能是"-","-1"
    public static boolean isEmptyId(String id) {
        return id == null || id.trim().length() == 0 || "-".equals(id) || "-1".equals(id) || "null".equals(id) || "(无)".equals(id);
    }

    public static boolean isEmptyId(Long id) {
        return id == null || id == -1 || id == 0;
    }

    public static boolean isNotEmpty(String str) {
        return !isEmpty(str);
    }

    public static boolean isNotEmptyId(String str) {
        return !isEmptyId(str);
    }
    public static boolean isNotEmptyId(long str) {
        return !isEmptyId(str);
    }
    public static boolean isNotEmptyStr(String str) {
        return !isEmptyStr(str);
    }

    public static boolean isNotEmpty(Collection collection) {
        return !isEmpty(collection);
    }

    public static boolean isNotEmpty(Object[] o) {
        return !isEmpty(o);
    }

    /**
     * 获取浮点数(有错误默认为0)，可以识别金额中的逗号格式
     *
     * @param str 带转换的字符串
     * @return 浮点数
     */
    public static double getDoubleIgnoreErr(String str) {
        if (str == null)
            return 0.0;
        str = str.trim();
        if (str.equals(""))
            return 0.0;
        str = str.replaceAll(",", "").replaceAll("，", "");
        try {
            return Double.valueOf(str);
        } catch (Exception e) {
            return 0.0;
        }
    }

    /**
     * 得到int 获取转换的int值，有错返回0
     *
     * @param str 带转换的字符串
     * @return int
     */
    public static int getIntIgnoreErr(String str) {
        return getIntIgnoreErr(str, 0);
    }

    public static int getIntIgnoreErr(String str, int defValue) {
        if (str == null)
            return defValue;
        str = str.trim();
        if (str.equals(""))
            return defValue;
        str = str.replaceAll(",", "").replaceAll("，", "");
        if (str.contains("."))
            str = str.substring(0, str.indexOf('.'));
        try {
            return Integer.valueOf(str);
        } catch (Exception e) {
            return defValue;
        }
    }

    /**
     * 得到Long 获取转换的Long值，有错返回0
     *
     * @param str 带转换的字符串
     * @return long
     */
    public static long getLongIgnoreErr(String str) {
        return getLongIgnoreErr(str, 0L);
    }

    public static long getLongIgnoreErr(String str, long defValue) {
        if (str == null)
            return defValue;
        str = str.trim();
        if (str.equals(""))
            return defValue;
        str = str.replaceAll(",", "").replaceAll("，", "");
        try {
            return Long.valueOf(str);
        } catch (Exception e) {
            return defValue;
        }
    }

    public static String getDateStrIgnoreNull(Timestamp obj) {
        if (obj == null)
            return "";
        return dFormat.format(obj);
    }

    public static String getTimeStrIgnoreNull(Timestamp obj) {
        if (obj == null)
            return "";
        return tFormat.format(obj);
    }

    public static Date getCurDate() {
        return new Date(System.currentTimeMillis());
    }

    public static String getCurDateStr() {
        return dFormat.format(new Date(System.currentTimeMillis()));
    }

    public static Timestamp getCurDatetime() {
        return new Timestamp(System.currentTimeMillis());
    }

    public static String getCurDatetimeStr() {
        return dtFormat.format(new Timestamp(System.currentTimeMillis()));
    }

    public static String getCurDatetimeShortStr() {
        return dLFormat.format(new Timestamp(System.currentTimeMillis()));
    }

    /**
     * Func:为空，返回""
     *
     * @param str 带检查的字符串
     * @return ""
     */
    public static String checkNull(String str) {
        if (isEmpty(str))
            return "";
        return str.trim();
    }

    /**
     * 功能：null过滤，返回默认值
     *
     * @param strValue     带检查的字符串
     * @param defaultValue 为空返回的字符串
     * @return str
     */
    public static String checkNull(String strValue, String defaultValue) {
        return strValue == null ? defaultValue : strValue;
    }

    public static String checkNull(Integer n) {
        return checkNull(n, true);
    }

    public static String checkNull(Integer n, boolean zeroToEmpty) {
        int v;
        if (n == null || n == 0)
            v = 0;
        else
            v = n;
        return v != 0 ? String.valueOf(v) : zeroToEmpty ? "" : "0";
    }

    public static String checkNull(Long n) {
        return checkNull(n, 0L);
    }

    public static String checkNull(Long n, long defValue) {
        return n != null ? String.valueOf(n) : String.valueOf(defValue);
    }

    public static String checkNull(Long n, boolean zeroToEmpty) {
        long v;
        if (n == null || n == 0)
            v = 0;
        else
            v = n;
        return v != 0 ? String.valueOf(v) : zeroToEmpty ? "" : "0";
    }

    public static String checkNull(Double n) {
        return checkNull(n, 0d);
    }

    public static String checkNull(Double n, boolean zeroToEmpty) {
        double v;
        if (n == null || n == 0)
            v = 0;
        else
            v = n;
        return v != 0 ? String.valueOf(v) : zeroToEmpty ? "" : "0";
    }

    public static String checkNull(Double n, double defValue) {
        double d = n != null ? n : defValue;
        return UtilPub.getDoubleStr(d);
    }

    //字符串清洗
    public static String clearStr(String str) {
        if (str == null) return "";
        else
            str = str.replaceAll("\u3000", "").replaceAll("\n", "").replaceAll("\b", "").replaceAll("\r", "").replaceAll("\t", "").replaceAll("\\s", "").replaceAll(" ", "").replaceAll("\"", "").trim();
        return str;
    }

    /**
     * Func:取当前年
     *
     * @return ""
     */
    public static String getThisYear() {
        Calendar tlpDate = new GregorianCalendar();
        tlpDate.setTime(getCurDate());
        return String.valueOf(tlpDate.get(Calendar.YEAR));
    }

    /**
     * Func:取当前月
     *
     * @return ""
     */
    public static String getThisMonth() {
        Calendar tlpDate = new GregorianCalendar();
        tlpDate.setTime(getCurDate());
        return String.valueOf(tlpDate.get(Calendar.MONTH));
    }

    /**
     * 功能：空值过滤，返回默认值
     *
     * @param strValue     待检查的字符串
     * @param defaultValue 为空返回的字符串
     * @return str
     */
    public static String checkEmpty(String strValue, String defaultValue) {
        return isEmpty(strValue) ? defaultValue : strValue;
    }

    /**
     * 功能：空值过滤，返回默认值
     *
     * @param strValue 待检查的字符串
     * @return str
     */
    public static String checkEmpty(String strValue) {
        return checkEmpty(strValue, Consts.TREE_ROOT_ID);
    }

    public static String checkEmptyId(String strValue, String defaultValue) {
        return isEmptyId(strValue) ? defaultValue : strValue;
    }
    public static Long checkEmptyId(long value, long defaultValue) {
        return isEmptyId(value) ? defaultValue : value;
    }

    public static String checkEmptyId(String strValue) {
        return isEmptyId(strValue) ? "" : strValue;
    }

    public static String getOrigMsg(Throwable e) {
        String s = e.getMessage();
        Throwable t = e.getCause();
        while (t != null) {
            s = t.getMessage();
            t = t.getCause();
        }
        return s;
    }

    //计算一个字符串source的长度(英文和数字占一个长度,其他字符(中文和特殊符号等)占2个长度)
    public static int strLength(String source) {
        int totalLength = source.length();// 总长度
        String otherStr = source.replaceAll("\\d|\\w", "");// 去掉字符串中的数字和英文字符
        int otherLength = otherStr.length();// 占2个长度的字符
        return (totalLength - otherLength) + otherLength * 2;
    }

    /**
     * 格式化最后修改时间
     *
     * @param strTime YYYYMMDDhhmmss
     * @return YYYY-MM-DD hh:mm:ss
     */
    public static String checkLastTime(String strTime) {
        if (isEmpty(strTime))
            return "";
        return checkLastTime(getLongIgnoreErr(strTime));
    }

    public static String checkLastTime(long lngTime) {
        if (0 >= lngTime)
            return "";
        String s1 = String.valueOf(lngTime + "").trim();
        if (s1.length() != 14)
            return "";
        return s1.substring(0, 4).concat("-").concat(s1.substring(4, 6)).concat("-").concat(s1.substring(6, 8)).concat(" ").concat(s1.substring(8, 10)).concat(":").concat(s1.substring(10, 12)).concat(":").concat(s1.substring(12));
    }

    /**
     * 格式化最后修改时间
     *
     * @param strTime YYYYMMDDhhmmss
     * @return YYYY-MM-DD hh:mm:ss
     */
    public static String getTimeFormatValue(String strTime) {
        if (isEmpty(strTime))
            return "";
        return getTimeFormatValue(getTimeDbValue(strTime));
    }

    /**
     * 日期格式化 YYYYMMDDHHMMSS 转 YYYY-MM-DD- HH:MM:SS
     *
     * @param lngTime
     * @return
     */
    public static String getTimeFormatValue(long lngTime) {
        if (lngTime <= 0L) return "";
        String s1 = String.valueOf(lngTime + "").trim();
        if (s1.length() == 8) {//日期
            return s1.substring(0, 4).concat("-").concat(s1.substring(4, 6)).concat("-").concat(s1.substring(6, 8));
        }
        if (s1.length() == 6) {//时间
            return s1.substring(0, 2).concat(":").concat(s1.substring(2, 4)).concat(":").concat(s1.substring(4, 6));
        }
        if (s1.length() == 14) {//日期
            return s1.substring(0, 4).concat("-").concat(s1.substring(4, 6)).concat("-").concat(s1.substring(6, 8)).concat(" ").concat(s1.substring(8, 10)).concat(":").concat(s1.substring(10, 12)).concat(":").concat(s1.substring(12));
        }
        return "";
    }

    /**
     * 日期格式化 YYYY-MM-DD- HH:MM:SS 转 YYYYMMDDHHMMSS
     *
     * @param strTime
     * @return
     */
    public static long getTimeDbValue(String strTime) {
        if (UtilPub.isEmptyId(strTime)) return -1L;

        return UtilPub.getLongIgnoreErr(strTime.replaceAll("-", "").replaceAll(":", "").replaceAll(" ", ""));
    }

    /**
     * 取最后修改时间
     *
     * @return Long
     */
//    public static Long getLastTime() {
//        return UtilDateTime.nowDateTimeNumber();
//    }

    /**
     * 取最后修改日期
     *
     * @return
     */
    public static Long getLastDate() {
        return Long.valueOf(dLFormat2.format(new Timestamp(System.currentTimeMillis())));
    }

    public static String getAmountStr(double amount) {
        return df2Format.format(amount);
    }

    public static String getAmountStrEx(double amount) {
        return df.format(amount);
    }

    public static String getSingleAmountStr(double amount) {
        return df2.format(amount);
    }

    public static String getAmountStr(double amount, boolean zeroShowEmpty) {
        if (zeroShowEmpty && NumberUtil.isEqualsZero(amount))
            return "";
        else
            return df2Format.format(amount);
    }

    public static String getIntStr(int d) {
        if (d == 0)
            return "";
        else
            return String.valueOf(d);
    }

    /**
     * 截取右边的0串
     *
     * @param codeStr
     * @return
     */
    public static String cutZero(String codeStr) {
        int j = 0;
        int len = codeStr.length() - 1;
        for (int i = len; i > -1; i--) {
            if ('0' == codeStr.charAt(i)) {
                j++;
            } else {
                break;
            }
        }
        return codeStr.substring(0, len - j + 1);
    }

    /**
     * 右边补0串
     *
     * @param codeLen
     * @param cutedCode
     * @return
     */
    public static String fillZero(int codeLen, String cutedCode) {
        StringBuilder codeStr = new StringBuilder(20).append(cutedCode);
        for (int len = cutedCode.length(), i = 0; i < codeLen - len; i++) {
            codeStr.append("0");
        }
        return codeStr.toString();
    }

    /**
     * 转换为boolean
     */
    public static boolean toBoolean(String v, boolean b) {
        if (v == null) return b;
        return "1".equals(v) || "true".equalsIgnoreCase(v) || "Y".equalsIgnoreCase(v) || "yes".equalsIgnoreCase(v);
    }

    public static String getDateStr(Object _dateTime) { //yyyymmddhhMMss
        if (_dateTime == null) return "";
        String dateTime = String.valueOf(_dateTime);
        if (UtilPub.isEmpty(dateTime) ) {
            return "";
        } else if(dateTime.length() == 8) {
            return dateTime.substring(0, 4) + "-" + dateTime.substring(4, 6) + "-" + dateTime.substring(6, 8);
        }else if(dateTime.length() == 6) {
            return dateTime.substring(0, 4) + "年" + dateTime.substring(4, 6) + "月报";
        }else {
            return "";
        }
    }

    /**
     * 日期转long
     *
     * @param dateStr YYYY-MM-DD
     * @return YYYYmmDD
     */
    public static long getDateLong(String dateStr) {
        if (UtilPub.isEmpty(dateStr) || dateStr.length() != 10) {
            return -1L;
        }
        String _dateTime = dateStr.replaceAll("-", "");
        return getLongIgnoreErr(_dateTime);
    }

    /**
     * 转日期时间long
     *
     * @param dateStr
     * @return
     */
    public static long getDateTimeLong(String dateStr) {
        if (UtilPub.isEmpty(dateStr)) {
            return -1L;
        }
        String _dateTime = dateStr.replaceAll("-", "").replaceAll(" ", "").replaceAll(":", "");
        _dateTime = StringUtil.getLeft(_dateTime + "00000000000000", 14);
        return getLongIgnoreErr(_dateTime);
    }

    /**
     * 转日期时间long
     *
     * @param dateStr
     * @return
     */
    public static long getEndDateTimeLong(String dateStr) {
        if (UtilPub.isEmpty(dateStr)) {
            return -1L;
        }
        String _dateTime = dateStr.replaceAll("-", "").replaceAll(" ", "").replaceAll(":", "");
        _dateTime = StringUtil.getLeft(_dateTime + "00000000", 8) + "235959";
        return getLongIgnoreErr(_dateTime);
    }

    public static String getDateTimeStr(Object _dateTime) { //yyyymmddhhMMss
        String dateTime = String.valueOf(_dateTime);
        if (UtilPub.isEmpty(dateTime) || dateTime.length() < 14) {
            return "";
        } else {
            String s1 = String.valueOf(dateTime);
            return s1.substring(0, 4) + "-" + s1.substring(4, 6) + "-" + s1.substring(6, 8);// + " " + s1.substr(8, 10) + ":" + s1.substr(10, 12) + ":" + s1.substr(12);
        }
    }

    //删除除 {"0","1","2","3","4","5","6","7","8","9",".","/","-"}以外的字符
    public static String remove(String str) {
        if (isEmpty(str)) return "";
        char[] charArray = str.toCharArray();
        char[] strArray = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '.', '/', '-'};
        for (char c : charArray) {
            if (!ArrayUtils.contains(strArray, c)) {
                str = StringUtils.remove(str, c);
            }
        }
        return str;
    }

    //数字转字符串，如无小数，则去掉.00
    public static String getDoubleStr(double d) {
        return getAmountStr(d).replaceAll(",", "").replaceAll("\\.00", "");
    }

    //将List转为sql语句in后面的常量，'XXX','XXX'格式
    public static String getSqlInstr(Collection<String> list) {
        if (UtilPub.isEmpty(list)) return "";
        StringBuilder sb = new StringBuilder(256);
        Set<String> set = new HashSet<>();
        for (String s : list) {
            if (set.contains(s)) continue;
            set.add(s);
            if (UtilPub.isEmptyId(s)) continue;
            sb.append(",'").append(s).append("'");
        }
        if (sb.length() == 0) return "";
        return sb.substring(1);
    }

    /**
     * 将数组ID转为sql语句in后面的常量
     *
     * @param ids ID数组
     * @return 返回格式：110,1002
     */
    public static String getSqlInIds(String[] ids) {
        if (null == ids || ids.length < 1) return "";
        StringBuilder s = new StringBuilder(128);
        Set<String> set = new HashSet<>();
        for (String id : ids) {
            if (set.contains(id)) continue;
            set.add(id);
            if (UtilPub.isEmptyId(id)) continue;
            s.append(id).append(",");
        }
        if (s.length() == 0) return "";
        return s.substring(0, s.length() - 1);
    }

    /**
     * 将数组ID转为sql语句in后面的常量
     *
     * @param ids ID数组
     * @return 返回格式：110,1002
     */
    public static String getSqlInLongIds(Collection<Long> ids) {
        if (null == ids || ids.size() < 1) return "";
        StringBuilder s = new StringBuilder(128);
        Set<Long> set = new HashSet<>();
        for (Long id : ids) {
            if (set.contains(id)) continue;
            set.add(id);
            if (UtilPub.isEmptyId(id)) continue;
            s.append(id).append(",");
        }
        if (s.length() == 0) return "";
        return s.substring(0, s.length() - 1);
    }

    public static String getSqlInIds(Collection<String> ids) {
        if (null == ids || ids.size() < 1) return "";
        StringBuilder s = new StringBuilder(128);
        Set<String> set = new HashSet<>();
        for (String id : ids) {
            if (set.contains(id)) continue;
            set.add(id);
            if (UtilPub.isEmptyId(id)) continue;
            s.append(id).append(",");
        }
        if (s.length() == 0) return "";
        return s.substring(0, s.length() - 1);
    }

    public static String getSqlInStrIds(Collection<String> ids) {
        if (null == ids || ids.size() < 1) return "";
        StringBuilder s = new StringBuilder(128);
        Set<String> set = new HashSet<>();
        for (String id : ids) {
            if (set.contains(id)) continue;
            set.add(id);
            if (UtilPub.isEmptyId(id)) continue;
            s.append("'" + id + "'").append(",");
        }
        if (s.length() == 0) return "";
        return s.substring(0, s.length() - 1);
    }

//    public static List<String> buildSqlIds(Collection<String> ids) {
//        List<String> l = new ArrayList<>();
//        StringBuilder sb = new StringBuilder();
//        int count = 0;
//        Set<String> set = new HashSet<>();
//        for (String id : ids) {
//            if (set.contains(id)) continue;
//            set.add(id);
//            if (count >= ExEnum.Consts.ORACLE_IN_LENGTH) {
//                l.add(sb.substring(1));
//                sb.setLength(0);
//                count = 0;
//            }
//            sb.append(",").append(id);
//            count++;
//        }
//        if (sb.length() > 0) l.add(sb.substring(1));
//        return l;
//    }
//
//    public static List<String> buildSqlIds(Map<String, List<String>> map) {
//        return buildSqlIds(map, ExEnum.Consts.ORACLE_IN_LENGTH);
//    }
//
//
//    public static List<String> buildSqlIds(Map<String, List<String>> map, int size) {
//        List<String> l = new ArrayList<>();
//        StringBuilder sb = new StringBuilder();
//        int count = 0;
//        Set<String> set = new HashSet<>();
//        for (String id : map.keySet()) {
//            if (set.contains(id)) continue;
//            set.add(id);
//            if (count >= size) {
//                l.add(sb.substring(1));
//                sb.setLength(0);
//                count = 0;
//            }
//            sb.append(",").append(UtilPub.getSqlInIds(map.get(id)));
//            count++;
//        }
//        if (sb.length() > 0) l.add(sb.substring(1));
//        return l;
//    }
//
//    public static List<String> buildSqlIds(Collection<String> ids, int size) {
//        List<String> l = new ArrayList<>();
//        StringBuilder sb = new StringBuilder();
//        int count = 0;
//        Set<String> set = new HashSet<>();
//        for (String id : ids) {
//            if (set.contains(id)) continue;
//            set.add(id);
//            if (count >= size) {
//                l.add(sb.substring(1));
//                sb.setLength(0);
//                count = 0;
//            }
//            sb.append(",").append(id);
//            count++;
//        }
//        if (sb.length() > 0) l.add(sb.substring(1));
//        return l;
//    }
//
//    public static List<String> buildSqlIn(Collection<String> ids) {
//        List<String> l = new ArrayList<>();
//        StringBuilder sb = new StringBuilder();
//        int count = 0;
//        Set<String> set = new HashSet<>();
//        for (String id : ids) {
//            if (set.contains(id)) continue;
//            set.add(id);
//            if (count >= ExEnum.Consts.ORACLE_IN_LENGTH) {
//                l.add(sb.substring(1));
//                sb.setLength(0);
//                count = 0;
//            }
//            sb.append(",'").append(id).append("'");
//            count++;
//        }
//        if (sb.length() > 0) l.add(sb.substring(1));
//        return l;
//    }
//
//    /**
//     * 判断字符串是否只包含unicode数字。
//     * <p/>
//     * <p>
//     * <code>null</code>将返回<code>false</code>，空字符串<code>""</code>将返回
//     * <code>true</code>。
//     * </p>
//     * <p/>
//     * <p>
//     * <pre>
//     * StringUtil.isNumeric(null)   = false
//     * StringUtil.isNumeric("")     = true
//     * StringUtil.isNumeric("  ")   = false
//     * StringUtil.isNumeric("123")  = true
//     * StringUtil.isNumeric("12 3") = false
//     * StringUtil.isNumeric("ab2c") = false
//     * StringUtil.isNumeric("12-3") = false
//     * StringUtil.isNumeric("12.3") = false
//     * </pre>
//     *
//     * @param str 要检查的字符串
//     * @return 如果字符串非<code>null</code>并且全由unicode数字组成，则返回<code>true</code>
//     */
//    public static boolean isNumeric(String str) {
//        if (UtilPub.isEmpty(str)) {
//            return false;
//        }
//
//        int length = str.length();
//
//        for (int i = 0; i < length; i++) {
//            if (!Character.isDigit(str.charAt(i))) {
//                return false;
//            }
//        }
//
//        return true;
//    }
//
//    public static boolean isDouble(String str) {
//        if (null == str || "".equals(str)) {
//            return false;
//        }
//        Pattern pattern = Pattern.compile("^[-\\+]?[.\\d]*$");
//        return pattern.matcher(str).matches();
//
//    }
//
//
//    public static boolean strMatch(String regEx, String str) {
//        if (str == null) return false;
//        Pattern pattern = Pattern.compile(regEx);
//        return pattern.matcher(str).matches();
//    }
//
//    /**
//     * 获得某个字符在  字符串中 出现第n次时的 下标
//     *
//     * @param res
//     * @param _c
//     * @param index
//     * @return
//     */
//    public static int getIndexChar(String res, String _c, int index) {
//        Matcher mh = Pattern.compile(_c).matcher(res);
//        int i = 0;
//        while (mh.find()) {
//            i++;
//            if (i == index) {
//                break;
//            }
//        }
//        return mh.start();
//    }
//
//    /**
//     * 将字符串转为指定字符集
//     *
//     * @param str
//     * @param charSet
//     * @return
//     */
//    public static String changeStrCharSet(String str, String charSet) {
//        if (isEmptyId(str)) return str;
//        String newStr = str;
//        try {
//            newStr = new String(str.getBytes(charSet), charSet);
//        } catch (UnsupportedEncodingException e) {
//            return newStr;
//        }
//        return newStr;
//    }
//
//    /**
//     * 转布尔
//     *
//     * @param o
//     * @return
//     */
//    public static boolean getBool(Object o) {
//        if (o == null) return false;
//        String v = o.toString();
//        return "1".equals(v) || "t".equalsIgnoreCase(v) || "true".equalsIgnoreCase(v);
//    }
//
//    /**
//     * 返回当恰能操作系统是否为Linux
//     *
//     * @return boolean
//     */
//    public static boolean osIsLinux() {
//        String s = System.getProperty("os.name");
//        return s != null && s.equalsIgnoreCase("linux");
//    }
//
//    public static boolean strAllEqual(String str) {
//        if (UtilPub.isEmptyId(str)) return true;
//        for (int i = 1; i < str.length(); i++)
//            if (str.charAt(i) != str.charAt(0)) return false;
//        return true;
//    }
//
//    /**
//     * 对中文字段 list排序
//     *
//     * @param list
//     * @param fun  获取排序的值
//     * @param desc 降序
//     * @throws Exception
//     */
//
//    public static <T, R> void sortChineseStrList(List<T> list, Function<T, R> fun, boolean desc) {
//        list.sort((T o1, T o2) -> {
//            int rt = Collator.getInstance(Locale.CHINESE).compare(fun.apply(o1), fun.apply(o2));
//            if (rt < 0) {
//                if (desc) {
//                    return 1;
//                }
//                return -1;
//            }
//            if (rt > 0) {
//                if (desc) {
//                    return -1;
//                }
//                return 1;
//            }
//            return 0;
//        });
//    }
//
//    //遍历集合
//    public static <T> void doForCollection(Collection<T> list, IBeanWorker<T> beanWorker) throws Exception {
//        if (isEmpty(list)) return;
//        for (T bean : list) {
//            beanWorker.doWork(bean);
//        }
//    }
//
//    //遍历map
//    public static <K, V> void doForMap(Map<K, V> map, IMapEntryReader<K, V> reader) throws Exception {
//        if (map == null) return;
//        for (Map.Entry<K, V> entry : map.entrySet()) {
//            reader.readEntry(entry.getKey(), entry.getValue());
//        }
//    }
//
//    public interface IMapEntryReader<K, V> {
//        void readEntry(K key, V value) throws Exception;
//    }
//
//    /**
//     *  将数据库存的金额单位(分) 转换为页面显示的金额单位(元)
//     * @param sc 分   eg:10000 (分)
//     * @return        ->100.0 (元)
//     */
//    public static double scoreShiftYuan(long sc) {
//        if(sc >= 100) {
//            String s = String.valueOf(sc);
//            String s1 = s.substring(s.length() - 2);
//            String s2 = s.substring(0, s.length() - 2);
//            String s3 = s2 + "." + s1;
//            return Double.valueOf(s3);
//        }
//        return 0.1;
//    }

    /**
     * 按身份证号码获取性别
     *
     * @param idNumber 身份证号码
     * @return string
     */
    public static String getGenderByIdNumber(String idNumber) {
        int genderCode = -1; // 性别代码
        if (idNumber.length() == 18) { // 二代身份证号码长度为18位（第17位为性别代码）
            genderCode = idNumber.charAt(16);
        } else if (idNumber.length() == 15) { // 一代身份证号码长度为15位（第15位为性别代码）
            genderCode = idNumber.charAt(14);
        }
        // 两代身份证号码的性别代码都为男奇女偶
        if (genderCode % 2 == 0) {
            return "女";
        }
        return "男";
    }
    /**
     * 根据身份证的号码算出当前身份证持有者的年龄
     *
     * @return
     */
    public static int getAgeByIdNumber(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();// 得到当前的系统时间
        java.util.Date date = new java.util.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;
            }
        }
        return age;
    }


    /**
     * 正则校验
     *
     * @param tel
     * @return
     */
    public static Boolean regCheckTel(String tel) {
        String reg = "^1[3-9]\\d{9}$";
        Pattern pattern = Pattern.compile(reg);
        Matcher matcher = pattern.matcher(tel);
        boolean matches = matcher.matches();
        return matches;
    }

    public static Boolean regCheckUid(String tel) {
        String reg = "(^\\d{15}$)|(^\\d{18}$)|(^\\d{17}(\\d|X|x)$)";
        Pattern pattern = Pattern.compile(reg);
        Matcher matcher = pattern.matcher(tel);
        boolean matches = matcher.matches();
        return matches;
    }

    public static Boolean regCheckEntUid(String tel) {
        String reg = "^_IOZSVa-z\\W]{2}\\d{6}[^_IOZSVa-z\\W]{10}$";
        Pattern pattern = Pattern.compile(reg);
        Matcher matcher = pattern.matcher(tel);
        boolean matches = matcher.matches();
        return matches;
    }

    //银行卡正则校验
    public static Boolean regCheckBank(String bank) {
        String reg = "^[1-9]\\d{9,29}$";
        Pattern pattern = Pattern.compile(reg);
        Matcher matcher = pattern.matcher(bank);
        boolean matches = matcher.matches();
        return matches;
    }

    /**
     * 银行卡长度检验
     *
     * @param cardNo
     * @return
     */
    public static Boolean regCheckBankNo(String cardNo) {
        return cardNo.length() >= 15 && cardNo.length() <= 19;
    }

    /**
     * 数据库的金额单位为分,在前端获取时,得到元
     */
    public static String longFormatToDouble(Long num) {
        return new BigDecimal(num).divide(new BigDecimal(100)).setScale(2).toString();
    }
    /**
     * 实际金额单位：元 转为数据库的金额单位：分
     */
    public static Long doubleFormatToLone(Double num) {
        DecimalFormat df = new DecimalFormat("0");
        String format = df.format(num * 100);
        return Long.parseLong(format.substring(0,format.length()));
    }
    /**
     * 实际金额单位：万元 转为数据库的金额单位：分
     */
    public static Long doubleFormatToWanLone(Double num) {
        DecimalFormat df = new DecimalFormat("0");
        String format = df.format(num * 100 * 10000);
        return Long.parseLong(format.substring(0,format.length()));
    }

    public static String longFormatToDouble(String str) {
        if (UtilPub.isEmptyId(str)) return str;
        long num = Long.parseLong(str);
        return longFormatToDouble(num);
    }

    /**
     * 将带格式的时间转为long（固定格式->2020/2/3 15:30:00 or 2020/2/3）
     *  =>Long(20200203153000 , 20200203000000)
     * @param oldTime
     * @return longTime
     */
    public static long retLongTime(String oldTime) {
        SimpleDateFormat sdf;
        if(oldTime.contains(" ")) {
            sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        }else {
            sdf = new SimpleDateFormat("yyyy-MM-dd");
        }
        java.util.Date parse = null;
        try {
            parse = sdf.parse(oldTime);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        SimpleDateFormat sdfNew = new SimpleDateFormat("yyyyMMddHHmmss");
        String format = sdfNew.format(parse);
        return Long.parseLong(format);
    }
    //税号校验 15或者17或者18或者20位字母、数字组成
    public static Boolean regTax(String tax) {
        String reg = "^[A-Z0-9]{15}$|^[A-Z0-9]{17}$|^[A-Z0-9]{18}$|^[A-Z0-9]{20}$";
        Pattern pattern = Pattern.compile(reg);
        Matcher matcher = pattern.matcher(tax);
        boolean matches = matcher.matches();
        return matches;
    }

    /**
     * excel日期 自动识别成数字（例：45231） 格式化为对应的日期（20231101）
     * @param strDate Excel日期数字
     * @return 字符串类型的日期 例：（20231101）
     * */
    public static String excelStringToDateFormat(String strDate) {
        if(strDate.length() == 5){
            try {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
                Calendar calendar = new GregorianCalendar(1900,0,-1);
                java.util.Date date = DateUtils.addDays(calendar.getTime(),Integer.parseInt(strDate));
                return sdf.format(date);
            }catch (Exception e){
                e.printStackTrace();
                return strDate;
            }
        }
        return strDate;
    }
}
