package com.ruoyi.framework.web.service;

import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.redis.RedisCache;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Service
public class TokenCheckService extends HttpServlet {

    private static final Logger log = LoggerFactory.getLogger(TokenService.class);
    private static final long serialVersionUID = 1L;

    @Value("${token.header}")
    private String header;

    // 令牌秘钥
    @Value("${token.secret}")
    private String secret;

    // 令牌有效期（默认30分钟）
    @Value("${token.expireTime}")
    private int expireTime;

    @Autowired
    private RedisCache redisCache;



    public TokenCheckService() {
        super();
    }

    public JSONObject doPost(String token) throws ServletException, IOException {
        JSONObject result = new JSONObject();
        if(token == null || "".equals(token.trim())) {
            //错误处理逻辑
            log.error("Token is missing or empty");
            result.put("result", "error");
            result.put("userId","");
        } else {
            //校验token是否合法
            if(check(token)) {
                //token验证通过就返回当前登录用户。对应永洪系统中的用户名。
                String userIdStr = "";
                try
                {
                    Claims claims = parseToken(token);
                    // 解析对应的权限以及用户信息
                    String uuid = (String) claims.get(Constants.LOGIN_USER_KEY);
                    String userKey = getTokenKey(uuid);
                    LoginUser user = redisCache.getCacheObject(userKey);
                    userIdStr = user.getUsername();
                } catch (Exception e)
                {
                    log.error("获取用户信息异常'{}'", e.getMessage());
                }
                result.put("result", "success");
                result.put("userId",userIdStr);
                result.put("userRoles","zhAdmin");
                log.info("parsed token result is："+result);

            } else {
                //token验证没通过就不返回userId。
                log.error("获取用户信息异常");
                result.put("result", "error");
                result.put("userId","");
            }
        }

        return result;
    }

    private boolean check(String token) {
        return true;
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    private Claims parseToken(String token)
    {
        return Jwts.parser()
                .setSigningKey(secret)
                .parseClaimsJws(token)
                .getBody();
    }

    private String getTokenKey(String uuid)
    {
        return CacheConstants.LOGIN_TOKEN_KEY + uuid;
    }

}