package jnpf.util.attendance;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import jnpf.entity.attendance.FtbAttendanceDailyRule;

import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.Objects;

public class DailyRuleUtil {

    public static List<FtbAttendanceDailyRule> mergeRules(List<FtbAttendanceDailyRule> dayRules) {
        dayRules.sort(Comparator.comparing(FtbAttendanceDailyRule::getOutPoint));
        FtbAttendanceDailyRule preRule = dayRules.get(0);
        List<FtbAttendanceDailyRule> mergeRules = CollUtil.newArrayList(preRule);
        for (int i = 1; i < dayRules.size(); i++) {
            FtbAttendanceDailyRule oldRule = preRule;
            FtbAttendanceDailyRule currRule = dayRules.get(i);
            if (oldRule.getOutPoint().compareTo(currRule.getInPoint()) >= 0 && oldRule.getOutPoint().compareTo(currRule.getOutPoint()) <= 0) {
                oldRule.setOutPoint(currRule.getOutPoint());
                continue;
            }
            preRule = currRule;
            mergeRules.add(preRule);
        }
        return mergeRules;
    }

    /**
     * 向上取半小时为最小单位的时间
     *
     * @param dateTime
     * @return
     */
    public static Date ceilToHalfHour(Date dateTime) {
        if (Objects.isNull(dateTime)) {
            dateTime = DateUtil.offsetMonth(DateUtil.endOfDay(new Date()), 12);
        }
        int minute = cn.hutool.core.date.DateUtil.minute(dateTime);
        if (minute % 30 == 0) {
            return dateTime;
        }

        int nextHalfHour = ((minute / 30) + 1) * 30;
        dateTime.setMinutes(nextHalfHour);
        dateTime.setSeconds(0);
        return dateTime;
    }
}
