package com.apobates.forum.member.impl;

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 com.apobates.forum.member.api.dao.MemberVipExchangeRecordsDao;
import com.apobates.forum.member.entity.MemberVipExchangeRecords;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import com.apobates.forum.member.api.dao.MemberDao;
import com.apobates.forum.member.api.dao.MemberPenalizeRecordsDao;
import com.apobates.forum.member.entity.MemberPenalizeRecords;
import com.apobates.forum.member.entity.MemberStatusEnum;
import com.apobates.forum.utils.DateTimeUtils;

/**
 * 会员作业
 * @author xiaofanku
 * @since 20190804
 */
public class MemberTask {
	@Autowired
	private MemberPenalizeRecordsDao memberPenalizeRecordsDao;
	@Autowired
	private MemberVipExchangeRecordsDao memberVipExchangeRecordsDao;
	@Autowired
	private MemberDao memberDao;
	private final static Logger logger = LoggerFactory.getLogger(MemberTask.class);
	
	//惩罚到期后重生会员
	public void rebirthMemberJob(){
		logger.info("[Task][Member][1]会员惩罚作业开始");
		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("[Task][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);
		memberDao.editMemberStatus(memberStatus);
		logger.info("[Task][Member][1]会员惩罚作业结束");
	}
	//VIP会员到斯后重设会员组
	public void vipExchangeResetMemberGroupJob(){
		logger.info("[Task][Member][3]VIP交易记录作业开始");
		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交易记录作业结束");
	}
}
