package com.yonge.cooleshow.auth.service.impl;

import java.util.Date;
import java.util.List;

import com.yonge.toolset.mybatis.service.impl.BaseServiceImpl;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.yonge.cooleshow.auth.api.entity.SysUser;
import com.yonge.cooleshow.auth.api.entity.SysUserLogin;
import com.yonge.cooleshow.common.enums.UserLockFlag;
import com.yonge.cooleshow.auth.dal.dao.SysUserDao;
import com.yonge.cooleshow.auth.dal.dao.SysUserLoginDao;
import com.yonge.cooleshow.auth.service.SysUserLoginService;
import com.yonge.toolset.mybatis.dal.BaseDAO;

@Service
public class SysUserLoginServiceImpl extends BaseServiceImpl<Long, SysUserLogin> implements SysUserLoginService {

	@Autowired
	private SysUserLoginDao sysUserLoginDao;

	@Autowired
	private SysUserDao sysUserDao;

	@Override
	public BaseDAO<Long, SysUserLogin> getDAO() {
		return sysUserLoginDao;
	}

	@Override
	public SysUserLogin findLoginByUserId(Long userId) {
		return sysUserLoginDao.findLoginByUserId(userId);
	}

	@Override
	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	public boolean autoUnlock() {
		List<SysUser> users = sysUserDao.queryByStatus(UserLockFlag.LOCKED);
		if (users != null) {
			SysUserLogin userLogin = null;
			Date targetDate = null;
			Date currentDate = new Date();
			Integer lockTime = null;
			for (SysUser user : users) {
				userLogin = get(user.getId());
				if (userLogin != null) {
					lockTime = userLogin.getLockTime();
					if (lockTime == null || lockTime == 0) {
						continue;
					}
					targetDate = DateUtils.addMinutes(userLogin.getLockDate(), lockTime);
					if (targetDate.getTime() < currentDate.getTime()) {
						userLogin.setFailCount(0);
						userLogin.setLockDate(null);
						userLogin.setLockTime(0);
						update(userLogin);

						user.setLockFlag(0);
						user.setUpdateTime(currentDate);
						sysUserDao.update(user);
					}
				}
			}
		}
		return false;
	}
}