package com.hc.gpbusiness.model.jwt;

import com.hc.gpbusiness.model.WebUser;
import com.hc.gpbusiness.model.WebUserAdmin;
import com.hc.gpbusiness.model.login.AccessEntity;
import com.hc.gpbusiness.model.login.AuthEntity;
import com.hc.gpbusiness.model.login.TokenEntity;
import com.hc.gpcore.utils.redis.RedisUtil;
import com.hc.gpcore.utils.tool.IdGenerator;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.SerializationUtils;

import java.io.UnsupportedEncodingException;
import java.util.Objects;

@Slf4j
@Component
public class GenerateAuthToken {

    @Autowired
    private RedisUtil redisUtil;

    public AccessEntity generateToken(AuthEntity auth, WebUser user, WebUserAdmin userAdmin) {

        AccessEntity accessEntity = new AccessEntity();
        accessEntity.setAuth(auth);
        TokenEntity tokenEntity = new TokenEntity();
        // 默认超时 8 小时
        tokenEntity.setExpires(60 * 60 * 24 * 7);
        String token = null;
        try {
            token = JWTUtil.sign(auth.getUserName(), IdGenerator.passwordToHash(auth.getPassword()));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        tokenEntity.setId(token);

        if (userAdmin != null) {
            //设置权限级别
            tokenEntity.setPermissionLevel(userAdmin.getPermissionLevel());
        }

        accessEntity.setToken(tokenEntity);
        String accessEntityStr = null;
        try {
            accessEntityStr = new String(Objects.requireNonNull(SerializationUtils.serialize(accessEntity)));
        } catch (Exception e) {
            log.warn("{}-{}用户登录出错", auth.getUserName(), auth.getPassword());
        }
        // 写入到 redis
        redisUtil.set(accessEntity.getToken().getId(),
                accessEntityStr,
                accessEntity.getToken().getExpires());
        if (user != null) {
            accessEntity.setUser(user);
        }
        if (userAdmin != null){
            accessEntity.setUserAdmin(userAdmin);
        }
        log.info("user: {}", auth.getUserName()+" 成功登录系统");
        return accessEntity;
    }
}
