package com.njcn.serviceimpl.log;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.njcn.shiro.token.TokenManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import com.njcn.mapper.log.UserLoginMapper;
import com.njcn.mapper.user.UserMapper;
import com.njcn.pojo.log.UserLogin;
import com.njcn.sso.pojo.user.User;
import com.njcn.service.log.UserLoginService;
import com.njcn.utils.AppConfig;
import com.njcn.utils.PubUtils;

import tk.mybatis.mapper.entity.Example;

@Service
public class UserLoginServiceImpl implements UserLoginService {
	@Autowired
	UserLoginMapper userLoginMapper;
	@Autowired
	UserMapper userMapper;
	@Autowired
	AppConfig appConfig;
	@Override
	public List<List> getUserLogin(String startTime, String endTime) {
		// TODO Auto-generated method stub
		SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		List<List> result = new ArrayList<>();
		startTime=startTime.replaceAll("-", "");
		startTime=startTime.replaceAll(" ", "");
		startTime=startTime.replaceAll(":", "");
		endTime=endTime.replaceAll("-", "");
		endTime=endTime.replaceAll(" ", "");
		endTime=endTime.replaceAll(":", "");
		List<UserLogin> userLogin = userLoginMapper.getUserLogin(startTime, endTime);
		if(userLogin.isEmpty()){
			return result;
		}else{
			for(UserLogin login:userLogin){
				List<String> temp=new ArrayList<String>();
				User user=new User();
				String userIndex=login.getUserIndex();
				user.setUserIndex(userIndex);
				user=userMapper.selectOne(user);
				temp.add(user.getLoginName());
				temp.add(login.getIP());
				temp.add(sdf.format(login.getLoginTime()));
				result.add(temp);
			}
		}
		return result;
	}


	/**
	 * 记录用户登陆的操作
	 */
	@Override
	public int insertLogin(String username,String item) {
		// TODO Auto-generated method stub
		String loginIndex=java.util.UUID.randomUUID().toString();
		User user=new User();
		user.setLoginName(username);
		user=userMapper.selectOne(user);
		UserLogin  login=new UserLogin();
		login.setUserLoginIndex(loginIndex);
		login.setUserIndex(user.getUserIndex());
		login.setIP(TokenManager.getToken().getIp());
		login.setAddress("内网登录");
		login.setLoginTime(new Date());
		login.setSystype(item);
		return userLoginMapper.insert(login);
	}

	/**
	 * 获取该用户最后一次登录的信息
	 * @param userIndex 用户索引
	 */
	@Override
	public UserLogin getUserLogin(String userIndex) {
		return userLoginMapper.getLastedLogin(userIndex);
	}

}
