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

import com.apobates.forum.member.dao.MemberDao;
import com.apobates.forum.member.dao.MemberVipExchangeRecordsDao;
import com.apobates.forum.member.entity.MemberVipExchangeRecords;
import com.apobates.forum.utils.DateTimeUtils;
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;
import java.time.LocalDateTime;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * Vip会员到期后复位会员的组
 *
 * @author xiaofanku
 * @since 20200921
 */
public class VipExchangeResetMemberGroupQuartzJob implements Job{
    @Autowired
    private MemberVipExchangeRecordsDao memberVipExchangeRecordsDao;
    @Autowired
    private MemberDao memberDao;
    @Value("${site.appname}")
    private String appName;
    private final static Logger logger = LoggerFactory.getLogger(VipExchangeResetMemberGroupQuartzJob.class);

    @Override
    public void execute(JobExecutionContext jec) throws JobExecutionException {
        logger.info(String.format("[%s][QuartzTask][Member][3]VIP交易记录作业开始", appName));
        LocalDateTime finish = LocalDateTime.now();
        LocalDateTime start = DateTimeUtils.beforeMinuteForDate(finish, 1); //作业的执行周期
        //
        List<MemberVipExchangeRecords> data = memberVipExchangeRecordsDao.findAllByExpire(start, finish).collect(Collectors.toList());
        if (data.isEmpty()) { //没有结果
            logger.info("[QuartzTask][Member][3]没有VIP交易记录,作业退出");
            return;
        }
        //
        Set<Long> exchangeIds = new HashSet<>();
        Set<Long> memberIds = new HashSet<>();
        //
        for (MemberVipExchangeRecords ver : data) {
            exchangeIds.add(ver.getId());
            memberIds.add(ver.getMemberId());
        }
        memberVipExchangeRecordsDao.expired(exchangeIds);
        memberDao.editMemberGroup(memberIds);
        logger.info("[QuartzTask][Member][3]VIP交易记录作业结束");
    }
}
