package com.bofeng.service;

import com.bofeng.JwtHelper;
import com.bofeng.entity.User;
import com.yvan.platform.Conv;
import lombok.val;
import org.apache.shiro.authc.AuthenticationException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

@Service
public class SecurityService {

    @Value("${secret:jztd}")
    private String secret = "jztd";

    @Value("${salt:jztd2}")
    private String salt = "jztd2";

    @Value("${token_time_minutes:30}")
    public int tokenTimeMinutes = 30;

    @Value("${token_time_minutes_mobile:30}")
    public int tokenTimeMinutesMobile = 30;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    public void setVersion(String userId, String tokenVersion) {
        val key = "token:" + userId;
        stringRedisTemplate.opsForValue().set(key, tokenVersion);
    }

    public String getVersion(String userId) {
        val key = "token:" + userId;
        return stringRedisTemplate.opsForValue().get(key);
    }

    public String createPassword(User user, String loginPwd) {
        return loginPwd;
    }

    public String createJwt(User user, boolean isMobile) {
        return JwtHelper.sign(Conv.NS(user.getUserId()),
                user.getVersion(),
                user.getUserType(),
                user.getStaffName(),
                secret,
                isMobile ? tokenTimeMinutesMobile : tokenTimeMinutes);
    }

    public void verify(String jwtToken) {
        final String userId = JwtHelper.getUserId(jwtToken);
        String tokenVersion = getVersion(userId);
        if (!JwtHelper.verify(jwtToken, userId, tokenVersion, secret)) {
            throw new AuthenticationException("tokenVersion expire!");
        }
    }
}
