package com.jwipc.util;

import cn.hutool.core.util.ObjectUtil;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;

/**
 * @author shenyang.ou
 * @date 2024/4/19 11:34
 * @desc
 */
public class FormatterPriceUtil {
    /**
     * 价格格式化
     * @param price 待处理价格
     * @param precision  保留小数点
     * @param repair 小数点位数不足是否补0
     * @param thousand 是否需要千分位
     * @param cutType 截取方式 0-四舍五入；1-向下舍入（截断）
     * @return 处理后的价格
     */
    public static String handle(BigDecimal price,Integer precision,Boolean repair,Boolean thousand,Integer cutType){
        if (ObjectUtil.isNull(price)){
            return "";
        }
        price = price.setScale(precision,cutType==0? RoundingMode.HALF_UP:RoundingMode.HALF_DOWN);
        if (!repair){
            price = price.stripTrailingZeros();
        }
        String priceStr = price.toPlainString();
        if (thousand){
            StringBuilder zero = new StringBuilder();
            for (int i = 0;i<precision;i++){
                zero.append("0");
            }
            final String pattern = "#,##0."+zero;
            DecimalFormat df4 = new DecimalFormat(pattern);
            priceStr = df4.format(price);
            if (!repair){
                priceStr = priceStr.replaceAll("0+$", "");
                priceStr = priceStr.replaceAll("\\.$", "");
            }
        }
        return priceStr;
    }
}
