package com.gyee.frame.service.ticket;

import com.gyee.frame.model.ticket.Labor;
import com.gyee.frame.model.ticket.TokenUser;
import com.gyee.frame.util.ticket.TokenCache;
import com.gyee.frame.util.ticket.TokenGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class ShiroService {

    @Autowired
    LaborService laborService;
    @Autowired
    TokenCache tokenCache;

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

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

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

        TokenUser user = new TokenUser();
        user.setLaborNum(labor.getLabornum());
        user.setLaborName(labor.getLaborname());
        user.setDepartment(labor.getDeptnum());
        user.setExpireTime(expireTime);

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

        result.put("token", tokenId);
        result.put("user", user);

        return result;
    }

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

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

    public Map<String, Object> updateToken(String tokenId, TokenUser token){
        Map<String, Object> result = new HashMap<>();

        //当前时间
        Date now = new Date();
        //过期时间
        long expireTime = now.getTime() + EXPIRE * 1000;

        TokenUser user = new TokenUser();
        user.setLaborNum(token.getLaborNum());
        user.setLaborName(token.getLaborName());
        user.setDepartment(token.getDepartment());
        user.setExpireTime(expireTime);

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

        result.put("token", tokenId);
        result.put("user", user);

        return result;
    }
}
