package com.house365.tags;

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

import org.springframework.web.servlet.tags.RequestContextAwareTag;

/**
 * 货币千分位格式化
 * 
 * @author duhui
 * 
 */
public class MoneyFormatViewTag extends RequestContextAwareTag {

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

	/**
	 * money
	 */
	private String money;
	
	public void setScale(Integer scale) {
		this.scale = scale;
	}

	private Integer scale;

	public void setMoney(String money) {
		this.money = money;
	}

	/**
	 * 数字处理，整数部分每三位用“ , ”分隔，小数部分保留两位。
	 */
	public String formatMoney(String money,Integer scale) {
	    String formatMon = "";
		// 四舍五入保留两位小数
		if ( null!=money &&!"".equals(money)) {
			if(null==scale)
			{
				//如果为空，则默认保留两位小数
				formatMon = new BigDecimal(money).setScale(2, BigDecimal.ROUND_HALF_UP)
						.toString();
			}else
			{
				formatMon = new BigDecimal(money).setScale(scale, BigDecimal.ROUND_HALF_UP)
						.toString();
			}
		}
		else
		{
			return "";
		}
		String result = "0.00";
		String str[] = formatMon.split("\\.");
		StringBuffer temp = new StringBuffer(str[0]);
		int len = temp.length();
		for (int i = len - 3; i > 0; i -= 3) {
			if (i < 0) {
				break;
			}
			if (temp.charAt(i - 1) != '-') {
				temp.insert(i, ",");
			}
		}
		if (len > 0) {
			result = temp.toString();
		} else {
			result = "0";
		}
		if (str.length == 1) {
			result += ".00";
		}
		if (str.length == 2) {
			if (str[1].length() == 1) {
				result += "." + str[1] + "0";
			} else {
				result += "." + str[1];
			}
		}
		return result;
	}

	@Override
	protected int doStartTagInternal() throws IOException {

		String formatMoney = formatMoney(money,scale);
		pageContext.getOut().write(formatMoney);
		return SKIP_BODY;
	}
}
