package cn.com.qmth.stmms.biz.utils;

import java.util.Comparator;

/**
 * 针对大题号+小题号组合情况的通用排序工具
 */
public class QuestionNumberComparator implements Comparator<QuestionNumberBean> {

    public static final QuestionNumberComparator instance = new QuestionNumberComparator();

    @Override
    public int compare(QuestionNumberBean b1, QuestionNumberBean b2) {
        // 比较大题号
        int i = b1.getMainNumber() - b2.getMainNumber();
        if (i != 0) {
            return i;
        }
        // 获取小题号数组
        Integer[] numbers1 = b1.getSubNumbers();
        Integer[] numbers2 = b2.getSubNumbers();
        for (int j = 0;; j++) {
            Integer n1 = j < numbers1.length ? numbers1[j] : null;
            Integer n2 = j < numbers2.length ? numbers2[j] : null;
            if (n1 == null && n2 == null) {
                break;
            }
            // 位数短的优先
            if (n1 == null) {
                return -1;
            }
            if (n2 == null) {
                return 1;
            }
            i = n1 - n2;
            // 某一位比较出大小则返回
            if (i != 0) {
                break;
            }
        }
        return i;
    }

    public static void main(String[] args) {
        QuestionNumberBean b1 = new QuestionNumberBean() {

            @Override
            public Integer getMainNumber() {
                return 1;
            }

            @Override
            public String getSubNumber() {
                return "10-1";
            }
        };
        QuestionNumberBean b2 = new QuestionNumberBean() {

            @Override
            public Integer getMainNumber() {
                return 1;
            }

            @Override
            public String getSubNumber() {
                return "1-10";
            }
        };
        System.out.println(QuestionNumberComparator.instance.compare(b1, b2));
    }
}
