package com.yihu.wlyy.job.consult;

import com.yihu.wlyy.entity.consult.ConsultTeam;
import com.yihu.wlyy.job.QuartzHelper;
import com.yihu.wlyy.repository.consult.ConsultTeamDao;
import com.yihu.wlyy.service.quota.JobService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

import static com.yihu.wlyy.job.consult.ConsultCleanerJob.ConsultTerminatorJobKey;

/**
 * @author Sand
 * @since 2016/9/26
 */
@Service
public class ConsultCleaner {
    private final ConsultTeamDao consultTeamDao;
    private final JobService jobService;
    private final QuartzHelper quartzHelper;

    @Autowired
    public ConsultCleaner(QuartzHelper quartzHelper, JobService jobService, ConsultTeamDao consultTeamDao) {
        this.quartzHelper = quartzHelper;
        this.jobService = jobService;
        this.consultTeamDao = consultTeamDao;
    }

    @Transactional
    public void doClean() {
        try {
            System.out.println("开始清除未响应咨询......");

            // 先关闭超过24小时未回应的咨询
            consultTeamDao.updateUnresponsedConsultOver24Hours();

            // 计算下一次执行此任务的时间，若无下次计算时间为50分钟后
            Date nextTriggerTime;

            Page<ConsultTeam> consultTeams = consultTeamDao.getUnresponsedConsultIn24Hours(new PageRequest(0, 1));
            if (consultTeams.getContent().size() > 0) {
                ConsultTeam consultTeam = consultTeams.getContent().get(0);
                Calendar calendar =  new GregorianCalendar();
                calendar.setTime(consultTeam.getCzrq());
                calendar.add(Calendar.HOUR, 24);

                nextTriggerTime = calendar.getTime();
            } else {
                Calendar calendar = GregorianCalendar.getInstance();
                calendar.set(Calendar.MINUTE, calendar.get(Calendar.MINUTE) + 50);
                nextTriggerTime = calendar.getTime();
            }

            System.out.println("计算下次任务执行时间，下次执行在" + nextTriggerTime.toString());

            quartzHelper.startAt(nextTriggerTime,
                    ConsultCleanerJob.class,
                    ConsultTerminatorJobKey + new Date().toString(),
                    null);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
