package com.mixsmart.numconvert;

/**
 * 数字转换成中文数字；
 * 如：1转换为“一”；2转换为“二”；3转化为“三”等；
 * 123转换后为“一百二十三”
 * @author lmq
 * @version 1.0
 * @since JDK版本大于等于1.6
 * <p>2016年5月17日</p>
 */
public class ChinaNumConvert extends AbstractNumConvert {
	
	//private static final String[] CHINA_NUMS = {"〇", "一", "二", "三", "四", "五", "六", "七", "八", "九"};
	private static final String[] CHINA_NUMS = {"零", "一", "二", "三", "四", "五", "六", "七", "八", "九"};
	private static final String[] CHINA_UNITS = {"", "十", "百", "千", "万", "十万", "百万", "千万", "亿", "十亿", "百亿", "千亿", "万亿"};
	
	private static final String DECIMAL_FLAG = ".";
	private static final String DECIMAL_CONVERT_FLAG = "点";
	
	@Override
	public String convert(Long num) {
		if(num<10) {
			int numInt = Integer.parseInt(num.toString());
			return CHINA_NUMS[numInt];
		} else if(num == 10) {
			return CHINA_UNITS[1];
		} else {
			char[] charArray = String.valueOf(num).toCharArray();
			StringBuilder resultBuilder = new StringBuilder();
			int len = charArray.length;
			for (int i = 0; i < len; i++) {
				int n = Integer.parseInt(String.valueOf(charArray[i]));
				//相连的零，只出现一次
				if(resultBuilder.lastIndexOf(CHINA_NUMS[0])>-1) {
					if(!CHINA_NUMS[0].equals(CHINA_NUMS[n])) {
						resultBuilder.append(CHINA_NUMS[n]);
					}
				} else {
					resultBuilder.append(CHINA_NUMS[n]);
				}
				if(!CHINA_NUMS[0].equals(CHINA_NUMS[n])) {
					resultBuilder.append(CHINA_UNITS[len-i-1]);
				}
				if(isAfterZero(charArray, len-(i+1))) {
					break;
				}
			}
			charArray = null;
			return resultBuilder.toString();
		}
	}
	
	/**
	 * 判断后面是否都是零
	 * @param chars
	 * @param afterLen
	 * @return
	 */
	protected boolean isAfterZero(char[] chars, int afterLen) {
		boolean is = true;
		for (int i = chars.length-afterLen; i < chars.length; i++) {
			if('0' != chars[i]) {
				is = is && false;
				break;
			}
		}
		return is;
	}

	@Override
	public String convert(Double num) {
		char[] charArray = String.valueOf(num).toCharArray();
		StringBuilder resultBuilder = new StringBuilder();
		int len = charArray.length;
		for (int i = 0; i < len; i++) {
			String value = String.valueOf(charArray[i]);
			if(DECIMAL_FLAG.equals(value)) {
				resultBuilder.append(DECIMAL_CONVERT_FLAG);
			} else {
				int n = Integer.parseInt(value);
				resultBuilder.append(CHINA_NUMS[n]);
				resultBuilder.append(CHINA_UNITS[len-i-1]);
			}
		}
		charArray = null;
		return resultBuilder.toString();
	}
	
}
