package com.apobates.forum.trident.event;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import com.apobates.forum.letterbox.api.service.ForumLetterService;
import com.apobates.forum.letterbox.entity.ForumLetter;
import com.apobates.forum.member.api.dao.MemberActiveRecordsDao;
import com.apobates.forum.member.entity.Member;
import com.apobates.forum.member.entity.MemberActiveRecords;
import com.apobates.forum.member.impl.event.MemberSignInEvent;
import com.apobates.forum.utils.DateTimeUtils;
import com.apobates.forum.utils.ip.IPMatcher;
import com.apobates.forum.utils.ip.IPMatcher.IpMatchResult;
import org.springframework.stereotype.Component;

/**
 * 会员登录事件侦听器,异地登录通知
 * @author xiaofanku
 * @since 20190703
 */
@Component
public class MemberSignInNoticeListener implements ApplicationListener<MemberSignInEvent>{
	@Autowired
	private ForumLetterService forumLetterService;
	@Autowired
	private MemberActiveRecordsDao memberActiveRecordsDao;
	private final static Logger logger = LoggerFactory.getLogger(MemberSignInNoticeListener.class);
	
	@Override
	public void onApplicationEvent(MemberSignInEvent event) {
		logger.info("[Member][SignInEvent][1]登录成功开始执行IP地域对比");
		Member m = event.getMember();
		String ipAddr = event.getIpAddr();
		if(IPMatcher.isLoopbackIp(ipAddr)){
			return; //环回地址不通知
		}
		List<MemberActiveRecords> rs = memberActiveRecordsDao.findAllByMemberNames(m.getNames(), 2).collect(Collectors.toList());
		if(rs.size()!=2){
			return; //不满足判断条件
		}
		Optional<IpMatchResult> mr = IPMatcher.getInstance().matchToResult(ipAddr);
		if(!mr.isPresent()){
			return; //没有可供比较的值
		}
		String p = mr.get().getProvince(); String c = mr.get().getCity();
		long matchCount = rs.stream().filter(mar -> mar.getProvince().equals(p) && mar.getCity().equals(c)).count();
		//是否是异地
		if(matchCount == 1){
			forumLetterService.create(getLoginAbnormalNotic(m.getId(), m.getNames(), LocalDateTime.now(), p.concat(c)));
		}
		logger.info("[Member][SignInEvent][1]IP地域对比结束");
	}
	
	//登录时IP变更
	private ForumLetter getLoginAbnormalNotic(long memberId, String names, LocalDateTime loginDateTime, String requestAddress){
		return new ForumLetter(
				"异地登录通知", 
				String.format("亲爱的:%s, 您的帐户于%s在%s完成了登录, 若非本人操作请注意您的帐户安全", names, DateTimeUtils.getRFC3339(loginDateTime), requestAddress), 
				memberId, 
				names);
	}
}
