package cn.wisenergy.service.impl;

import cn.wisenergy.mapper.WorkHolidayMapper;
import cn.wisenergy.model.app.WorkHoliday;
import cn.wisenergy.service.WorkHolidayService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author chenqi
 * @since 2021-01-19
 */
@Service
public class WorkHolidayServiceImpl implements WorkHolidayService {

    @Autowired
    private WorkHolidayMapper workHolidayMapper;

    @Override
    public Boolean isHoliday(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        List<WorkHoliday> workHolidays = workHolidayMapper.selectList(null);
        for (WorkHoliday holiday : workHolidays) {
            if (!yearMonthBetween(date, holiday.getDayStart(), holiday.getDayEnd())) {
                continue;
            }
            if (1 == holiday.getDayType()) {
                return true;
            }
        }
        return calendar.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY ||
                calendar.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY;

    }

  /*  // 获取某时间段内的所有日期
    public List<Date> findDates(Date dBegin, Date dEnd) {
        List<Date> lDate = new ArrayList<>();
        lDate.add(dBegin);
        Calendar calBegin = Calendar.getInstance();
        // 使用给定的 Date 设置此 Calendar 的时间
        calBegin.setTime(dBegin);
        Calendar calEnd = Calendar.getInstance();
        // 使用给定的 Date 设置此 Calendar 的时间
        calEnd.setTime(dEnd);
        // 测试此日期是否在指定日期之后
        while (dEnd.after(calBegin.getTime())) {
            // 根据日历的规则，为给定的日历字段添加或减去指定的时间量
            calBegin.add(Calendar.DAY_OF_MONTH, 1);
            lDate.add(calBegin.getTime());
        }
        return lDate;
    }
*/
    // 判断某个时间是否在时间段内
    private static boolean yearMonthBetween(Date nowDate, Date startDate, Date endDate) {

        long nowTime = nowDate.getTime();
        long startTime = startDate.getTime();
        long endTime = endDate.getTime();
        return nowTime >= startTime && nowTime <= endTime;
    }

}
