package com.house365.tags;

import java.io.IOException;
import java.math.BigDecimal;
import java.text.DecimalFormat;

import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.tags.RequestContextAwareTag;

/**
 * 数字格式化
 * 
 * @author duhui
 * 
 */
public class NumberFormatViewTag extends RequestContextAwareTag {

    /**
	 * 
	 */
    private static final long serialVersionUID = 1L;

    /**
     * 默认小数位数
     */
    private static final int DEFAULT_DECIMAL_DIGITS = 2;

    /**
     * 原始值
     */
    private String value;

    /**
     * 小数位数
     */
    private int decimaDigits = DEFAULT_DECIMAL_DIGITS;

    /**
     * 是否千分位分割
     */
    private boolean splitThousand;

    /**
     * 设置原始值
     * 
     * @param value 原始值
     */
    public void setValue(String value) {
        this.value = value;
    }

    /**
     * 设置小数位数
     * 
     * @param decimaDigits 小数位数
     */
    public void setDecimaDigits(int decimaDigits) {
        this.decimaDigits = decimaDigits;
    }

    /**
     * 数字处理
     */
    public String formatNumber(String value) {
        if (StringUtils.isBlank(value)) {
            return "";
        } else {
            if (splitThousand) {
                String[] arrStr = value.split("\\.");
                DecimalFormat format = new DecimalFormat(",###");
                String intPart = format.format(Long.valueOf(arrStr[0]));
                if (2 == arrStr.length) {
                    String fractionalPart = new BigDecimal("0." + arrStr[1]).setScale(this.decimaDigits,
                            BigDecimal.ROUND_HALF_UP).toString();

                    intPart += fractionalPart.substring(1, fractionalPart.length());
                } else {
                    StringBuffer sb = new StringBuffer(intPart);
                    sb.append(".");
                    int dig = 0;
                    while (dig < decimaDigits) {
                        sb.append("0");
                        dig++;
                    }
                    intPart = sb.toString();
                }
                return intPart;
            } else {
                if (0 > this.decimaDigits) {
                    this.decimaDigits = DEFAULT_DECIMAL_DIGITS;
                }
                return new BigDecimal(value).setScale(this.decimaDigits, BigDecimal.ROUND_HALF_UP).toString();
            }
        }
    }

    @Override
    protected int doStartTagInternal() throws IOException {
        String number = formatNumber(value);
        pageContext.getOut().write(number);
        return SKIP_BODY;
    }

    public boolean isSplitThousand() {
        return splitThousand;
    }

    public void setSplitThousand(boolean splitThousand) {
        this.splitThousand = splitThousand;
    }

}
