package com.gyee.frame.shiro.config;


import com.gyee.frame.model.auto.TsysUser;
import com.gyee.frame.model.custom.TokenUser;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class ShiroService {


    @Resource
    TokenCache tokenCache;

    //10天后过期
    public final long EXPIRE = 10 * 24 * 60 * 60;

    public Map<String, Object> createToken(TsysUser user){
        Map<String, Object> result = new HashMap<>();
        if (user == null)
            return result;

        //生成一个token id
        String token = TokenGenerator.generateValue();
        //当前时间
        Date now = new Date();
        //过期时间
        long expireTime = now.getTime() + EXPIRE * 1000;

        TokenUser tokenUser = new TokenUser();
        tokenUser.setLaborNum(user.getId());
        tokenUser.setLaborName(user.getUsername());
        tokenUser.setPassword(user.getPassword());
        tokenUser.setDepartment(user.getDepName());
        tokenUser.setExpireTime(expireTime);

        // 保存并更新token
        tokenCache.saveToken(token, tokenUser);

        result.put("authToken", token);
        result.put("user", tokenUser);

        return result;
    }

    public void logout(String token) {
       tokenCache.removeToken(token);
    }

    public TokenUser findToken(String token) {
        return tokenCache.findUserByToken(token);
    }
}
