package com.hotent.uc.service.impl;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import com.hotent.base.util.time.DateUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Primary;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Service;

import com.hotent.base.service.LoginLogService;
import com.hotent.base.util.BeanUtils;
import com.hotent.base.util.HttpUtil;
import com.hotent.base.util.WebUtil;
import com.hotent.uc.api.model.IUser;
import com.hotent.uc.manager.LoginLogManager;
import com.hotent.uc.model.LoginLog;

import java.time.LocalDateTime;

@Primary
@Service
public class LoginLogServiceImpl implements LoginLogService {
	protected static Logger logger = LoggerFactory.getLogger(LoginLogServiceImpl.class);

	@Resource
	LoginLogManager loginLogManager;
	@Resource
	UserDetailsService userDetailsService;
	
	@Override
	public void log(String account, String loginType) {
		try {
			HttpServletRequest request = HttpUtil.getRequest();
			LoginLog log = loginLogManager.getByAccount(account);
			String ip = WebUtil.getIpAddr(request);
			if(BeanUtils.isEmpty(log)){
				UserDetails userDetails = userDetailsService.loadUserByUsername(account);
				if(BeanUtils.isNotEmpty(userDetails)){
					IUser user = (IUser)userDetails;
					log = new LoginLog();
					log.setAccount(account);
					log.setName(user.getFullname());
					log.setId(user.getUserId());
					log.setLoginSum(1);
					if("mobile".equals(loginType)){
						log.setMobileSum(log.getMobileSum()+1);
					}else{
						log.setPcSum(log.getPcSum()+1);
					}
					log.setIp(ip);
					log.setLoginType(loginType);
                    LocalDateTime currentDate = DateUtil.getCurrentDate();
                    log.setCreateTime(currentDate);
                    log.setUpdateTime(currentDate);
					loginLogManager.create(log);
				}
			}else{
				if("mobile".equals(loginType)){
					log.setMobileSum(log.getMobileSum()+1);
				}else{
					log.setPcSum(log.getPcSum()+1);
				}
				log.setLoginSum(log.getLoginSum()+1);
				log.setIp(ip);
				log.setLoginType(loginType);
				loginLogManager.update(log);
			}
		} catch (Exception e) {
			logger.error("统计用户登录日志失败："+e.getMessage());
		}
		
	}

}
