package com.hzu.labbooking;

import org.junit.jupiter.api.Test;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;


class LabbookingApplicationTests {

    @Test
    void contextLoads() {
        List<Long> list = new ArrayList<>();
        list.add(1L);
        list.add(2L);
        list.add(3L);
        list.add(4L);
        list.add(6L);
        list.add(7L);
        list.add(9L);
        list.add(11L);

        String convert = convert(list);
        System.out.println(convert);
    }

    private String convert(List<Long> week) {

        Collections.sort(week);
        StringBuilder ans = new StringBuilder();
        if (week == null || week.isEmpty()) {
            return "";
        }

        int sz = week.size();
        if (sz >= 6) {
            boolean f = false;
            for (int i = 1; i < sz; i++) {
                if (week.get(i) - week.get(i - 1) != 2) {
                    f = true; // true表示不连续
                    break;
                }
            }
            if (!f) {
                Long s = week.get(0);
                Long e = week.get(sz - 1);
                if (s == 2) {
                    s--;
                }
                if (e == 15 || e == 17) {
                    e++;
                }
                ans.append("[").append(s);
                ans.append("-");
                ans.append(e).append("周]");
                if (week.get(0) % 2 == 0) {
                    ans.append("双");
                } else {
                    ans.append("单");
                }
                return ans.toString();
            }
        }

        int len = 1; // len表示连续的个数，要求>=2才处理
        int idx = 1; // 周次索引
        long s = 0; // 连续的起点

        ans.append("[");

        while (idx < week.size()) {
            if (week.get(idx) == week.get(idx - 1) + 1) { // 连续
                len++;
                if (len == 2) {
                    s = week.get(idx - 1); //len==2，开始连续，s记录起点
                }
            } else { //不连续
                if (len >= 2) {
                    ans.append(s);
                    ans.append("-");
                    ans.append(week.get(idx - 1));
                } else { //len < 2
                    ans.append(week.get(idx - 1));
                }
                ans.append(",");
                len = 1;
            }
            idx++;
        }

        //最后剩余的一个数字
        if (len >= 2) {
            ans.append(s).append("-");
        }
        ans.append(week.get(idx - 1)).append("周]");

        return ans.toString();
    }

}
