package com.uas.platform.b2b.support;

import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.uas.platform.b2b.dao.TokenDao;
import com.uas.platform.b2b.model.Token;
import com.uas.platform.core.util.encry.Md5Utils;

@Service
public class TokenService {

	@Autowired
	private TokenDao tokenDao;	
	
	public Token saveToken(Token token) {
		if (tokenDao.findTokenByUuAndUserType(token.getUu(), token.getUserType()) != null){
		   tokenDao.delete(tokenDao.findTokenByUuAndUserType(token.getUu(), token.getUserType()));
		}
		token.setTime(new Date());
		return tokenDao.save(token);
	}

	/**
	 * 获取并保存
	 * @param userType
	 * @param uu
	 * @return
	 */
	public String getEncodeToken(String userType, Long uu) {
		Token token = saveToken(new Token(userType, uu));
		return Md5Utils.encode(uu, token.getId());
	}

	/**
	 * 判断token信息是否有效
	 * 
	 * @param type
	 * @param name
	 * @param encodeString
	 * @return
	 */
	public boolean isCertified(String userType, Long uu, String encodeString) {
		Token token = tokenDao.findTokenByUuAndUserType(uu, userType);
		if (token != null) {
			String encode = Md5Utils.encode(uu, token.getId());
			boolean certified = !token.isOutofTime() && encode.equals(encodeString);
			// 只使用一次，即时删除
			tokenDao.delete(token);
			return certified;
		}		
		return false;
	}


}
