package com.jiayue.ipfcst.common.data.service.uploadfilerule;

import com.jiayue.ipfcst.common.core.util.DateMomentUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.time.DateFormatUtils;
import org.springframework.scheduling.support.CronSequenceGenerator;

import javax.persistence.criteria.CriteriaBuilder;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 上报文件规则公共类
 *
 * @author xsl
 * @version 3.0
 */
@Slf4j
public class UploadFileRuleCommonService {
    Long midNightTime = 0L;
    Long endTime = 0L;

    public void caleTime(Date inputParamDate) {
        Date nowDate = new Date();
        // 今日凌晨时间
        Long nowNightTime = DateMomentUtil.getDayStartTime(nowDate.getTime());
        // 指定日期的凌晨时间
        midNightTime = DateMomentUtil.getDayStartTime(inputParamDate.getTime());
        if (nowNightTime.longValue() != midNightTime.longValue()) {
            endTime = midNightTime + 1000 * 60 * 60 * 24-1000;
        } else {
            endTime = nowDate.getTime();
        }
    }

    /**
     * 对每分钟的定时统计是否产生应上报
     *
     * @param tempDateTime
     * @param currentDate
     * @param cronStr
     * @return
     */
    public boolean isEveryTimeShouldFile(Long tempDateTime, Date currentDate, String cronStr, Integer fileRate) {
        // 此判断为了当前时刻应上报的文件还没执行定时，产生的多余的应上报
        try {
            if (DateFormatUtils.format(tempDateTime, "HH:mm").equals(DateFormatUtils.format(currentDate, "HH:mm"))) {
                final CronSequenceGenerator generator = new CronSequenceGenerator(cronStr);
                final Date nextExecutionDate = generator.next(currentDate);
                if (Integer.parseInt(DateFormatUtils.format(currentDate, "mm")) % fileRate == 0) {
                    String ss = DateFormatUtils.format(nextExecutionDate, "ss");
                    if (Integer.parseInt(DateFormatUtils.format(currentDate, "ss")) < Integer.parseInt(ss)) {
                        System.out.println("jin:"+tempDateTime);

                        return false;
                    }
                }
            }
        } catch (Exception e) {
            log.error("计算每分钟应上报文件数量出错：" + e);
        }
        return true;
    }

    /**
     * 对指定时间的定时统计是否产生应上报
     *
     * @param currentDate
     * @param cronStr
     * @return
     */
    public boolean isSpecifiedTimeShouldFile(Date currentDate, String cronStr) {
        // 此判断为了当前时刻应上报的文件还没执行定时，产生的多余的应上报
        try {
            final CronSequenceGenerator generator = new CronSequenceGenerator(cronStr);
            final Date nextExecutionDate = generator.next(currentDate);
            if (DateFormatUtils.format(currentDate, "HH:mm:ss").compareTo(DateFormatUtils.format(nextExecutionDate, "HH:mm:ss")) < 0) {
                return false;
            }
        } catch (Exception e) {
            log.error("计算指定时间应上报文件数量出错：" + e);
        }
        return true;
    }
}
