package com.yunzhi.marketing.common;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

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


    /**
     * 获取uuid
     *
     * @return
     */
    public static String getUUIDS() {
        String uuid = UUID.randomUUID().toString().replace("-", "");
        return uuid;
    }

    /**
     * 生成订单号
     *
     * @param tradeType
     * @return
     */
    public static String generateTradeNo(String tradeType) {
        String sdf = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
        int randNum = (int) (new Random().nextDouble() * (9999 - 1000 + 1)) + 1000;// 获取5位随机数
        return tradeType + sdf + randNum;
    }

    /**
     * 元转分
     *
     * @param money
     * @return
     */
    public static Integer yuanToFen(Double money) {
        Double moneyd = money * 100;
        Integer moneyi = moneyd.intValue();
        return moneyi;
    }

    /**
     * 元转分
     *
     * @param money
     * @return
     */
    public static Double fenToYuan(Integer money) {
        return Double.parseDouble(BigDecimal.valueOf(Long.valueOf(money)).divide(new BigDecimal(100)).toString());
    }

    /**
     * double减法运算,防止直接相减失去精度
     *
     * @param m1 减数
     * @param m2 被减数
     * @return
     */
    public static Double subDouble(double m1, double m2) {
        BigDecimal p1 = new BigDecimal(Double.toString(m1));
        BigDecimal p2 = new BigDecimal(Double.toString(m2));
        return p1.subtract(p2).doubleValue();
    }

}
