package com.dsk.common.utils;

import java.math.BigDecimal;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 邮箱和手机号验证
 */
public class CheckUtils {

    public static final String REG_Moblie = "^((13[0-9])|(14(0|[5-7]|9))|(15([0-3]|[5-9]))|(16(2|[5-7]))|(17[0-8])|(18[0-9])|(19([0-3]|[5-9])))\\d{8}$";//手机号
    public static final String REG_Landline = "(\\(\\d{3,4}\\)|\\d{3,4}-|\\s)?\\d{8}";//座机号

    public static final String REG_EMAIL = "[a-zA-Z0-9]+@[a-zA-Z0-9]+\\.[a-zA-Z0-9]+";

    /**
     * 校验email
     * @param email
     * @return
     */
    public static boolean isEmail(String email){
        if (email == null){
            return false;
        }else {
            boolean isMatch = Pattern.matches(REG_EMAIL,email);
            return isMatch;
        }
    }

    /**
     * 校验手机号
     * @param phone
     * @return
     */
    public static boolean isPhone(String phone){
        if (phone == null){
            return false;
        }else {
            Pattern mobilePattern = Pattern.compile(REG_Moblie);
            Pattern landlinePattern = Pattern.compile(REG_Landline);
            Matcher mobileMatcher = mobilePattern.matcher(phone);
            Matcher landlineMatcher = landlinePattern.matcher(phone);
            return mobileMatcher.matches() || landlineMatcher.matches();
        }

    }

    /**
     * Double小数点前的位数
     * @param number
     * @return
     */
    public static int checkIntegerPlaces(Double number) {
        BigDecimal bigDecimal = new BigDecimal(String.valueOf(number));
        String strNumber = bigDecimal.toString();
        int integerPlaces = strNumber.indexOf('.');
        if (integerPlaces == -1) {
            return strNumber.length();
        } else {
            return integerPlaces;
        }
    }

    /**
     * Double小数点后的位数
     * @param number
     * @return
     */
    public static int checkDecimalPlaces(Double number) {
        BigDecimal bigDecimal = new BigDecimal(String.valueOf(number));
        String strNumber = bigDecimal.toString();
        int decimalPlaces = 0;
        int index = strNumber.indexOf('.');
        if (index != -1) {
            decimalPlaces = strNumber.length() - index - 1;
        }
        return decimalPlaces;
    }
}
