package com.apobates.forum.member.impl.quartz;

import com.apobates.forum.member.dao.MemberDao;
import com.apobates.forum.member.dao.MemberPenalizeRecordsDao;
import com.apobates.forum.member.entity.MemberPenalizeRecords;
import com.apobates.forum.member.entity.MemberStatusEnum;
import com.apobates.forum.utils.DateTimeUtils;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

/**
 * 惩罚到期后重生会员
 * 
 * @author xiaofanku
 * @since 20200611
 */
public class PenalizeResetMemberStatusQuartzJob implements Job{
    @Autowired
    private MemberPenalizeRecordsDao memberPenalizeRecordsDao;
    @Autowired
    private MemberDao memberDao;
    @Value("${site.appname}")
    private String appName;
    private final static Logger logger = LoggerFactory.getLogger(PenalizeResetMemberStatusQuartzJob.class);
    
    @Override
    public void execute(JobExecutionContext jec) throws JobExecutionException {
        logger.info(String.format("[%s][QuartzTask][Member][1]会员惩罚作业开始", appName));
        LocalDateTime finish = LocalDateTime.now();
        LocalDateTime start = DateTimeUtils.beforeMinuteForDate(finish, 1); //作业的执行周期
        //
        List<MemberPenalizeRecords> data = memberPenalizeRecordsDao.findAllByExpire(start, finish).collect(Collectors.toList());
        if (data.isEmpty()) { //没有结果
            logger.info("[QuartzTask][Member][1]没有惩罚记录,作业退出");
            return;
        }
        //
        Set<Long> penalizeIds = new HashSet<>();
        Map<Long, MemberStatusEnum> memberStatus = new HashMap<>();
        //
        for (MemberPenalizeRecords mpr : data) {
            penalizeIds.add(mpr.getId());
            memberStatus.put(mpr.getMemberId(), mpr.getOriginal()); //回到原来的状态
        }
        memberPenalizeRecordsDao.expired(penalizeIds); //false
        memberDao.editMemberStatus(memberStatus);
        logger.info("[QuartzTask][Member][1]会员惩罚作业结束");
    }
}