package jnpf.attendance.service.filter.impl;

import jnpf.attendance.service.filter.RuleFilter;
import jnpf.attendance.service.filter.RuleFilterContext;
import jnpf.attendance.service.filter.RuleFilterResult;
import jnpf.base.UserInfo;
import jnpf.entity.attendance.FtbAttendanceDailyRule;
import jnpf.enums.attendance.AttendanceTypeEnum;
import jnpf.enums.attendance.v2.WorkBoundaryCoverageEnum;
import jnpf.util.DateDetail;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 请假过滤器
 * 判定需要保留的情况
 * @author yanwenfu
 * @create 2025-09-25
 */
@Component
public class LeaveFilter implements RuleFilter {

    @Override
    public RuleFilterResult keepRule(FtbAttendanceDailyRule rule, RuleFilterContext context, UserInfo userInfo) {

        if (rule.getAttendanceType().equals(AttendanceTypeEnum.LEAVE.getCode())) {
            // 今天的出勤规则如果只有请假, 就返回回去
            // 获取当天的所有非休息规则
            List<FtbAttendanceDailyRule> sameDayRules = context.getRuleList().stream()
                    .filter(v -> DateDetail.checkSameDay(context.getCurDate(), v.getDay()))
                    .filter(v -> !v.getAttendanceType().equals(AttendanceTypeEnum.REST.getCode()))
                    .collect(Collectors.toList());
            // 如果所有非休息规则都是请假，则返回 keep
            boolean allLeave = !sameDayRules.isEmpty() &&
                    sameDayRules.stream().allMatch(v -> v.getAttendanceType().equals(AttendanceTypeEnum.LEAVE.getCode()));
            if (allLeave) {
                return RuleFilterResult.keep();
            }
        }
        if (WorkBoundaryCoverageEnum.LEAVE_COVERED.getCode() == rule.getInUnbounded() || WorkBoundaryCoverageEnum.LEAVE_COVERED.getCode() == rule.getOutUnbounded()) {
            if (DateDetail.checkSameDay(context.getCurDate(), rule.getOutLackPoint()) || DateDetail.checkSameDay(context.getCurDate(), rule.getInPoint())) {
                // 当前出勤规则有上/下班请假覆盖 并且 是跨天(昨日跨今日) || 上班时间是今天
                return RuleFilterResult.keep();
            }
        }
        return RuleFilterResult.discard();
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
