package com.mixsmart.sort;

import com.mixsmart.utils.StringUtils;

/**
 * 简单的中文数字排序；应用于字符中含有中文数字时的排序
 * @author lmq  2017年4月28日
 * @version 1.0
 * @since 1.0
 */
public class ChinaNumSort {

	private final String[] CHINA_NUM = new String[]{"一","二","三","四","五","六","七","八","九","十"};
	private static ChinaNumSort instance = new ChinaNumSort();
	
	private ChinaNumSort() {
		
	}
	
	public static ChinaNumSort getIntance() {
		return instance;
	}
	
	/**
	 * 比较排序
	 * @param value 值 
	 * @param otherValue 另外一个值
	 * @return 返回比较结果；
	 * 返回值请参考{@link Comparable#compareTo(Object)}的说明
	 */
	public int sort(String value, String otherValue) {
		int result = 1;
		if(StringUtils.isEmpty(value) || StringUtils.isEmpty(otherValue)) {
			return result;
		}
		int[] posArray = getPosition(value);
		if(posArray[0] == -1) {
			return value.compareTo(otherValue);
		}
		int[] otherPosArray = getPosition(otherValue);
		if(otherPosArray[0] == -1) {
			return value.compareTo(otherValue);
		}
		if(posArray[0] == otherPosArray[0]) {
			value = value.replace(CHINA_NUM[posArray[1]], String.valueOf(posArray[1]+1));
			otherValue = otherValue.replace(CHINA_NUM[otherPosArray[1]], String.valueOf(otherPosArray[1]+1));
			result = value.compareTo(otherValue);
		} else {
			result = value.compareTo(otherValue);
		}
		return result;
	}
	
	/**
	 * 获取位置
	 * @param value 获取value在<code>CHINA_NUM</code>数组中的位置
	 * @return 返回所在位置
	 */
	private int[] getPosition(String value) {
		int[] posArray = {-1,-1};
		for (int i = 0; i < CHINA_NUM.length; i++) {
			int pos = value.indexOf(CHINA_NUM[i]);
			if(pos > -1) {
				posArray[0] = pos;
				posArray[1] = i;
				break;
			}
		}
		return posArray;
	}
}
